From sebastien.martini at gmail.com Fri Jan 6 05:05:24 2006 From: sebastien.martini at gmail.com (=?iso-8859-1?B?c+liYXN0aWVu?=) Date: 6 Jan 2006 02:05:24 -0800 Subject: How run web software *locally* easily? In-Reply-To: <1136506381.009884.317330@o13g2000cwo.googlegroups.com> References: <1136506381.009884.317330@o13g2000cwo.googlegroups.com> Message-ID: <1136541924.219133.242200@g44g2000cwa.googlegroups.com> for example like that: python -m CGIHTTPServer From lycka at carmen.se Thu Jan 19 06:05:36 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 19 Jan 2006 12:05:36 +0100 Subject: New Python.org website? In-Reply-To: References: <1137553529.299812.129090@g43g2000cwa.googlegroups.com> <1137636317.961569.251290@g47g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > The trepidation was accounted for solely by a concern that Python would > become involved in any kind of religious controversy, or that someone of > extreme views might claim that Python was associated with, or against, a > particular religious belief. I'm sure there are a number of places where people without extreme views react strongly to christian symbols--whether the reasons for this are well founded or not. ASEA, the A-part of the ABB group, stopped using their old logo in 1933. They realized that what used to be a symbol for electrical motors in schematic diagrams had become associated with something entirely different. In 1933 the general opinion on nazis weren't nearly as negative as it is now, but whatever you thought about politics, ASEA's old logo no longer gave the right associations to people. On the other hand, people on Bali don't seem to worry a bit about the swastikas on their shrines and temples. Different context. We can obviously argue on how much we should worry about the assocations people in various corners of thge world get, whatever we intended. In Sweden, the python snake has for some reason become associated with bad smells. (I think it was Pippi Longstocking who used an expresion that got stuck in the souls of the Swedes--it's all Astrid Lindgren's fault.) I don't expect Guido to rename Python for that reason (Monty would feel fairly neutral in Sweden), but it sometimes seem to be a disadvantage. I think some people I've tried to convince would have been more impressed if Python had been called XYZ or whatever... Here at work, our conference rooms are named after old norse gods, and the new room that was named Vile, was rapidly renamed Vili, when people thought about the meaning of "vile" in English. Actually, considering the status snakes have in christian tradition, I guess you could claim that the snakes neutralize the cross! Personally, I think it looks more like plus sign than like a cross. > Quite apart from the fact that language > choice should not be a religious issue (:-), you are correct in saying > that we must be mindful of sensitivities; as I mentioned, the outline of > the logo hasn't been raised in the year since it was first mooted. I > hope this doesn't mean we need *two* Python logos! It's probably possible to make a Python logo that doesn't look like any religious symbol. I think the plus sign shaped logo had some advantages though. It's not very pretty, but it's simple and a plus is something positive, something that adds value... From skip at pobox.com Wed Jan 18 15:16:46 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 18 Jan 2006 14:16:46 -0600 Subject: a more precise re for email addys In-Reply-To: References: Message-ID: <17358.41518.450368.372823@montanaro.dyndns.org> rbt> re.compile('([\w\.\-]+@[\w\.\-]+)') rbt> re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') rbt> re.compile('(\S+)@(\S+)') rbt> All of these will find email addys, but they also find other rbt> things. I think the only way to decide if your regular expression does what you want is to provide a set of strings it must accept and another set which it must reject. Supply those two sets and I'm sure any number of people here can come up with a regular express that distinguishes the two sets. Skip From xavier.morel at masklinn.net Mon Jan 16 04:14:07 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Mon, 16 Jan 2006 10:14:07 +0100 Subject: instance attributes not inherited? In-Reply-To: References: Message-ID: John M. Gabriele wrote: > I'm having a hard time finding the documentation to the super() function. > I checked the language reference ( http://docs.python.org/ref/ref.html ) > but didn't find it. Can someone please point me to the relevant docs on > super? > > help( super ) doesn't give much info at all, except that super is actually > a class, and calling it the way we are here returns a "bound super object", > but I don't yet see what that means (though I know what bound methods are). > Super is a bit magic, quite complicated, and some people don't like it (basically, super is mainly to be used in complex inheritance case with diamond shape hierarchies and such, to automate the method resolution order). If you want to give a try at understanding "super", you should read Guido's `Unifying types and classes in Python 2.2`, chapters on MRO, super and cooperative methods (http://www.python.org/2.2.3/descrintro.html#mro) (nb: you may also read the rest of the document, it lists all the magic introduced in the language with 2.2). From mwm at mired.org Wed Jan 4 17:17:12 2006 From: mwm at mired.org (Mike Meyer) Date: Wed, 04 Jan 2006 17:17:12 -0500 Subject: Calling GPL code from a Python application References: <86mzicg3vn.fsf@bhuda.mired.org> <86u0ckeaw9.fsf@bhuda.mired.org> <86irszev7k.fsf@bhuda.mired.org> <11ro4jt6q0haoaf@corp.supernews.com> Message-ID: <86r77nd4ev.fsf@bhuda.mired.org> Grant Edwards writes: >> Of course, in cases where it matters (i.e. - I provide public >> access to my legally purchased copy of the Brittanica, or some >> such), copyrights on things other than the program come into >> play. Possibly multiple copyrights. > Huh? As you pointed out, they're giving out a copy of the *data* from the program. That data could well come with a different copyright than the one that applies to the program, so while I may have the right to use it in the program, I may not have the right to hand it out over the internet. The mutliple copyrights comes from thinking about songs, which has seperate copyrights for the lyrics, the tune, and the arrangement. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From derickvn at gmail.com Thu Jan 26 02:27:31 2006 From: derickvn at gmail.com (Derick van Niekerk) Date: 25 Jan 2006 23:27:31 -0800 Subject: Mining strings from a HTML document. References: <1138181024.289284.65470@g44g2000cwa.googlegroups.com> <1138201452.564308.306370@g47g2000cwa.googlegroups.com> Message-ID: <1138260451.655579.228300@g44g2000cwa.googlegroups.com> Thanks, Jay! I'll try this out today. Trying to write my own parser is such a pain. This BeatifullSoup script is very nice! I'll give it a try. If you can help me out with an example of how to do what I explained, I would appreciate it. I actually finished doing an import last night, but there is no way I'm creating another parser from scratch! I tried figuring out what to do by going through the code, but I am still waay too fresh to understand generators and some of the coding conventions. Thanks again From maeckle at arcor.de Mon Jan 30 06:07:23 2006 From: maeckle at arcor.de (maeckle) Date: Mon, 30 Jan 2006 12:07:23 +0100 Subject: reportlab - ttf justify In-Reply-To: <43cfcef1$0$20771$9b4e6d93@newsread4.arcor-online.net> References: <43cfa91d$0$20789$9b4e6d93@newsread4.arcor-online.net> <43cfcef1$0$20771$9b4e6d93@newsread4.arcor-online.net> Message-ID: <43ddf386$0$20773$9b4e6d93@newsread4.arcor-online.net> hi, no success at the reportlab-users list. i also applied the 'spaces patch to fix para splitting'-patch but it's still not justifying the text... is there an other solution? thanks alot!! jm >> maeckle wrote: >>> hi, >>> >>> i'm working with reportlab since a couple of weeks and i managed to >>> create quite nice pdfs... >>> there is a little problem though. since i have to create english and >>> russian content, i use the utf8 support of registered ttf's. the only >>> thing is that it does not support the justify-alignment in paragraph >>> flowables! >>> is there a way to fix that? >>> >>> thanks alot >>> jm >> >> Hi, you'll get better response from the reportlab-users list at >> >> http://two.pairlist.net/mailman/listinfo/reportlab-users >> >> The ttf support has been significantly improved in an svn branch. >> re-ask on that list giving your current version. >> >> I believe the problem with ttf justification was related to using >> space as a splitting character in dynamically subsetted fonts. Someone >> posted a fix for that problem to the users list and I think that has >> gone in to the code now, but I'm not sure if it is on the stable >> branch or not. > > thank you, that helped me alot! > > cheers > jm From kent37 at tds.net Fri Jan 13 09:01:17 2006 From: kent37 at tds.net (kent37 at tds.net) Date: 13 Jan 2006 06:01:17 -0800 Subject: Template language with XPath support for source code generation? In-Reply-To: References: Message-ID: <1137159596.888121.261330@g43g2000cwa.googlegroups.com> Stefan Behnel wrote: > I've been looking through Python templating systems all over the place, but I > just can't find one that supports XPath - which is by far the best thing to > have when you generate stuff from XML. TAL might be able to get me part of the > way (at least, it supports some kind of Path expressions, though only for > object access), but the only available implementation is part of Zope and I > can't make my code depend on Zope only for a template system. I have done a lot of text file generation in Jython and Java using dom4j as the data model and Velocity as the template engine. It's a very powerful combination. dom4j elements have XPath accessors so you can say for example myElement.selectNodes('some/xpath'). Velocity supports introspection on its data so in a template I can say #foreach $item ($parent.selectNodes("some/xpath")) (my syntax may be a little off, this is from memory) ISTM you should be able to do the same thing from CPython with a dom model that has XPath accessors and a template engine that supports calling methods on its data. I think lxml and Cheetah, among others, would work this way. Kent From rurpy at yahoo.com Thu Jan 12 19:14:00 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 12 Jan 2006 16:14:00 -0800 Subject: Is 'everything' a refrence or isn't it? In-Reply-To: References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1136792417.696119@jetspin.drizzle.com> <1136858652.907049.120600@o13g2000cwo.googlegroups.com> Message-ID: <1137111240.338847.23920@f14g2000cwb.googlegroups.com> "Donn Cave" wrote: > In article <1136858652.907049.120600 at o13g2000cwo.googlegroups.com>, > rurpy at yahoo.com wrote: > > "Donn Cave" wrote in message > > news:1136792417.696119 at jetspin.drizzle.com... > ... > > > So you've had time to think about how you would define value, in a > > > few words. Any ideas? > > > > Not yet. The reason is that I am still trying to figure out > > what a value is myself. Do all objects have values? If > > not which do and which don't? What's the value of int(1)? > > An object? Some otherwise unreachable thing that > > represents the abstract concept of the number 1? > > What the value of object()? A few weeks ago I turned > > to that page for enlightenment, with the results I reported. > > > > > I find the topic difficult, myself. I think you really have to apply > > > some context to the question, so there may not be any satisfactory > > > definition for the language reference. > > > > I have a hard time accepting that. I do not think there > > is any aspect of human thought that cannot be described > > by a sufficiently skilled writer. > > But you're asking for more than that. We're not just talking > about how people think about value, you want a definition that's > suitable for a language reference. Whereupon you would indeed > run into the kinds of questions you pose above, and more. > > > > But maybe it would be simple with the right focus. If we could somehow > > > define value, how would that help? I mean, presumably we need to > > > understand all this stuff because we want to write some software, and > > > if we dive in without understanding, our attempts will be plagued with > > > conceptual errors. Is there something about value in particular that > > > seems to be a problem here? ``No, you idiot, that's not a value - > > > THIS is a value!'' > > > > Yes, see above. How can you feel confident working with > > things that aren't understood? (c.f. this thead about > > problems resulting from python beginner's misconceptions > > about references.) > > I'm saying that the definition of value doesn't contribute to > my understanding of my work. I guess we might say that the > whole point of a computer programming language is a mechanism > for the representation and manipulation of values, and our > task is to understand the mechanism enough to work with it. > That's what the language reference is for. I think the difference in our perspectives is that you already *know* what a value is, not necessarily in a way that allows you to write a defintion, but certainly in a way that allows to work effectively with them. As a Python beginner, I do not know, and I need something more than "it is something an object has". I do NOT need eiher some formal specifcation, nor a metaphysical discussion that relates it to platonic ideals and other such concepts. Surely there is some middle ground? From kay.schluehr at gmx.net Mon Jan 23 15:30:01 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 Jan 2006 12:30:01 -0800 Subject: Some thougts on cartesian products In-Reply-To: References: Message-ID: <1138048201.234656.123440@g43g2000cwa.googlegroups.com> Bryan Olson wrote: > There's no such thing; you'd have to define it first. Are duplicates > significant? Order? That's all trivial isn't it? A string is a set of pairs (i,c) where i is an integer number, the index, with 0<=i Message-ID: Duncan Booth wrote: > >Dave Hansen wrote: > >> Stealing from the old C chestnut: >> >> s="s=%c%s%c;print s%%(34,s,34)";print s%(34,s,34) > >Or a bit shorter: > >s='s=%s;print s%%`s`';print s%`s` It was pointed out to me that the shortest Python program which produces itself on stdout is: -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tim.leeuwvander at nl.unisys.com Thu Jan 12 05:00:53 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 12 Jan 2006 02:00:53 -0800 Subject: How can I create a dict that sets a flag if it's been modified In-Reply-To: <1137057338.290239.35260@f14g2000cwb.googlegroups.com> References: <1137057338.290239.35260@f14g2000cwb.googlegroups.com> Message-ID: <1137060053.490865.129480@o13g2000cwo.googlegroups.com> Should the dict flag when the dict itself has been updated? Or also when any of the items in the dict has been updated? Say you have a dict consisting of lists... The dict should be flagged as modified when an item is added; or when an item is replaced (you call dict.__setitem__ with a key that already exists). This is clear, and easy to achieve with a simple wrapper or subclass. But should the dict also be flagged as 'modified' when I append an item to one of the lists that is in the dict? >>> l = d['a'] >>> l.append('1') Does that code mean that the dict should be flagged as 'modified' in your use-case? or not? If yes, then the only feasible way might be to pickle the dict. And if repeated pickling of the same dict is not guaranteed to give the same results, then perhaps pickling d.getitems() would give the right results since, AFAIK, dict.getitems() is at least guaranteed to maintain the same order given that A) The dict is not changed and B) You're using the same Python version. Right? From fredrik at pythonware.com Tue Jan 10 01:01:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Jan 2006 07:01:51 +0100 Subject: Implementing Tuples with Named Items References: Message-ID: Bryan wrote: > in the python cookbook 2nd edition, section 6.7 (page 250-251), there a problem > for implementing tuples with named items. i'm having trouble understanding how > one of commands work and hope someone here can explain what exactly is going on. > without copying all the code here, here is the gist of the problem: > > from operator import itemgetter > > class supertup(tuple): > def __new__(cls, *args): > return tuple.__new__(cls, args) > > setattr(supertup, 'x', property(itemgetter(0))) > > >>> t = supertup(2, 4, 6) > >>> t.x > >>> 2 > > > i understand what itemgetter does, > > >>> i = itemgetter(0) > >>> i((2, 3, 4)) > >>> 2 > >>> i((4, 8, 12)) > >>> 4 > > i understand what property does, and i understand what setattr does. i tested > this problem myself and it works, but i can't understand how t.x evaluates to 2 > in this case. how does itemgetter (and property) know what tuple to use? the missing piece in your puzzle is what's known as "descriptors": http://users.rcn.com/python/download/Descriptor.htm (property returns a descriptor, and the object machinery will use that descriptor to control what happens when you access the 'x' attribute). hope this helps! From finite.automaton at gmail.com Fri Jan 27 02:26:14 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 26 Jan 2006 23:26:14 -0800 Subject: any way to customize the is operator? In-Reply-To: References: <1138342643.119111.281900@g14g2000cwa.googlegroups.com> Message-ID: <1138346774.949296.192520@g14g2000cwa.googlegroups.com> > (objects are not allowed to lie about who they are, or what they are). Dangit! I need to find a less honest programming language. Anyone have a Perl cookbook handy? ... From nicolas.lehuen at gmail.com Sat Jan 28 12:15:24 2006 From: nicolas.lehuen at gmail.com (Nicolas Lehuen) Date: 28 Jan 2006 09:15:24 -0800 Subject: Python vs C for a mail server References: <1138439841.267886.97600@o13g2000cwo.googlegroups.com> <1138445796.313796.135590@g43g2000cwa.googlegroups.com> <9mhI0D4+ciB@jens-theisen.de> Message-ID: <1138468524.895456.172590@g47g2000cwa.googlegroups.com> Jens Theisen wrote: > Please don't be offended, but if anyone could make a point of how Python's > disadvantages in these regards could be alleviated, I'd be very > interested. > > Jens Well, I write Java, C++ and Python code, and I have posted a few thoughts about this on my blog : http://nicolas.lehuen.com/ My two latest problems with coding in C++ are due to the environments : libraries using different string types and the whole problem with the building system. I love the language, but I get a much better leverage through Python and Java due to the quality and ease of use of their built-in and third party libraries. I use C++ only for my core data structure (namely a tuned version of a ternary search tree which I use to build full text indices). Regards, Nicolas From greg.kujawa at gmail.com Wed Jan 18 11:33:56 2006 From: greg.kujawa at gmail.com (gregarican) Date: 18 Jan 2006 08:33:56 -0800 Subject: MSSQL LIKE and IN statements in ADO problem References: <1137598018.349898.213860@g43g2000cwa.googlegroups.com> Message-ID: <1137602036.170824.172970@g47g2000cwa.googlegroups.com> Can't you get rid of the Create Parameter part and directly pass along the value you are looking for? Something like... name = 'raj' cmd.CommandText= \ "SELECT * FROM tb_name WHERE firstname LIKE %%%s" % name This way the value of the name variable gets passed along when the CommandText method is invoked. BTW, this looks too painfully much like Visual Basic than Python :-) Just kidding (kind of) From cdc at maxnet.co.nz Tue Jan 24 18:04:47 2006 From: cdc at maxnet.co.nz (Carl Cerecke) Date: Wed, 25 Jan 2006 12:04:47 +1300 Subject: Weird generator id() behaviour (was Re: Python code written in1998, how to improve/change it?) In-Reply-To: References: <1137697284.101739.30690@z14g2000cwz.googlegroups.com><43d00460@usenet01.boi.hp.com> <1137714834.195896.180550@g47g2000cwa.googlegroups.com><43d0596e@usenet01.boi.hp.com> <43d05ac2@usenet01.boi.hp.com><0001HW.BFFC3AEE0008B851F04B8550@news.individual.de> <43d68bd0@usenet01.boi.hp.com> Message-ID: <43d6b290$1@usenet01.boi.hp.com> Fredrik Lundh wrote: > Carl Cerecke wrote: > > >>It turns out that generators are more efficient than the eval function >>excuting bits of compiled code. About 20-25% faster. > > > why are you using generators to return things from a function, when > you can just return the things ? Trying to find the fastest way to implement finite state machine. The included file times 4 different ways, with functions the fastest. The reason, I think, for the unusual sequence if id()s of the generators - see grandparent post - (and the reason for their poor performance compared to functions), is because the reference to the generator is being lost, then another generator is being created with the same id. Properly done, I would expect generators to out perform functions. These are the numbers I get on a P3 600: $ ./foo.py action generator overhead: 13.25 --- exec: 8.7 --- eval: 10.09 --- generators: 6.68 --- functions: 3.37 #!/usr/bin/env python import time s_on = compile(''' #print 'on' action = next_action() if action == 'lift': state = s_on elif action == 'push': state = s_off else: state = None ''','','exec') s_off = compile(''' #print 'off' action = next_action() if action == 'lift': state = s_on elif action == 'push': state = s_off else: state = None ''','','exec') def f_on(): action = next_action() if action == 'lift': return f_on elif action == 'push': return f_off else: return None def f_off(): action = next_action() if action == 'lift': return f_on elif action == 'push': return f_off else: return None def g_on(): #print "on" action = next_action() if action == 'lift': yield g_on() elif action == 'push': yield g_off() else: yield None def g_off(): #print "off" action = next_action() if action == 'lift': yield g_on() elif action == 'push': yield g_off() else: yield None def actions(n): import random for i in range(n-1): yield random.choice(['lift','push']) yield None r = 1000000 #r = 10 next_action = actions(r).next a = time.clock() while next_action(): pass z = time.clock() print "action generator overhead:",z-a common = z-a print "---" next_action = actions(r).next state = s_on # start state a = time.clock() while state: exec state z = time.clock() print "exec:",z-a-common print "---" next_action = actions(r).next state = s_on # start state a = time.clock() while state: eval(state) z = time.clock() print "eval:",z-a-common print "---" next_action = actions(r).next s_g_on = g_on() s_g_off = g_off() state = s_g_on a = time.clock() while state: #print id(state) state = state.next() z = time.clock() print "generators:",z-a-common print "---" next_action = actions(r).next state = f_on a = time.clock() while state: state = state() z = time.clock() print "functions:",z-a-common From __peter__ at web.de Sat Jan 7 04:10:10 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Jan 2006 10:10:10 +0100 Subject: csv format to DBase III format References: <1136268229.400341.161980@g14g2000cwa.googlegroups.com> <1136537531.485663.265790@o13g2000cwo.googlegroups.com> Message-ID: William wrote: > Peter Otten wrote: >> coriolis_wong at yahoo.com.hk wrote: >> >> > I need to transfer csv format file to DBase III format file. >> > How do i do it in Python language? >> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 > I create a dbf file, it can be opened by Excel but it cannot be opened > by Access. Where is the error in my script. No idea, but here's some brainstorming. > f = open('test.dbf','w') First make sure that you open the file in binary mode 'wb'. If you have an application around that can generate dbfs you could compare a manually created file with the python-generated one. Have you tried the dbf with no records? If that is opened without error, you could successively add records until you find the culprit. Finally, if Excel and Access disagree about the dbf's validity, the Access import filter could be broken. Are there other filters for the Dbase family (Foxpro, Clipper)? Try one of them. Peter From bokr at oz.net Tue Jan 10 00:08:49 2006 From: bokr at oz.net (Bengt Richter) Date: Tue, 10 Jan 2006 05:08:49 GMT Subject: Do you have real-world use cases for map's None fill-in feature? References: <1136669507.225698.313400@g49g2000cwa.googlegroups.com> Message-ID: <43c334c5.692407719@news.oz.net> On 7 Jan 2006 23:19:41 -0800, "Raymond Hettinger" wrote: >I am evaluating a request for an alternate version of itertools.izip() >that has a None fill-in feature like the built-in map function: > >>>> map(None, 'abc', '12345') # demonstrate map's None fill-in feature >[('a', '1'), ('b', '2'), ('c', '3'), (None, '4'), (None, '5')] > I don't like not being able to supply my own sentinel. None is too common a value. Hm, ... unless maybe it can also be a type that we can instantiate with really-mean-it context level like None(5) ;-) >>> map(None(5), 'abc', '12345') # demonstrate map's None fill-in feature [('a', '1'), ('b', '2'), ('c', '3'), (None(5), '4'), (None(5), '5')] But seriously, standard sentinels for "missing data" and "end of data" might be nice to have, and to have produced in appropriate standard contexts. Singleton string subclass instances "NOD" and "EOD"? Doesn't fit with EOF=='' though. >The movitation is to provide a means for looping over all data elements >when the input lengths are unequal. The question of the day is whether >that is both a common need and a good approach to real-world problems. >The answer to the question can likely be found in results from other >programming languages or from real-world Python code that has used >map's None fill-in feature. > What about some semantics like my izip2 in http://groups.google.com/group/comp.lang.python/msg/3e9eb63a1ddb1f46?hl=en (which doesn't even need a separate name, since it would be backwards compatible) Also, what about factoring sequence-related stuff into being methods or attributes of iter instances? And letting iter take multiple sequences or callable/sentinel pairs, which could be a substitute for izip and then some? Methods could be called via a returned iterator before or after the first .next() call, to control various features, such as sentinel testing by 'is' instead of '==' for callable/sentinel pairs, or buffering n steps of lookahead supported by a .peek(n) method defaulting to .peek(1), etc. etc. The point being to have a place to implement universal sequence stuff. >I scanned the docs for Haskell, SML, and Perl and found that the norm >for map() and zip() is to truncate to the shortest input or raise an >exception for unequal input lengths. I scanned the standard library >and found no instances where map's fill-in feature was used. Likewise, >I found no examples in all of the code I've ever written. > >The history of Python's current zip() function serves as another >indicator that the proposal is weak. PEP 201 contemplated and rejected >the idea as one that likely had unintended consequences. In the years >since zip() was introduced in Py2.0, SourceForge has shown no requests >for a fill-in version of zip(). > >My request for readers of comp.lang.python is to search your own code >to see if map's None fill-in feature was ever used in real-world code >(not toy examples). I'm curious about the context, how it was used, >and what alternatives were rejected (i.e. did the fill-in feature >improve the code). > >Also, I'm curious as to whether someone has seen a zip fill-in feature >employed to good effect in some other programming language, perhaps >LISP or somesuch? ISTM in general there is a chicken-egg problem where workarounds are easy. I.e., the real question is how many workaround situations there are that would have been handled conveniently with a builtin feature, and _then_ to see whether the convenience would be worth enough. > >Maybe a few real-word code examples and experiences from other >languages will shed light on the question of whether lock-step >iteration has meaning beyond the length of the shortest matching >elements. If ordinal position were considered as a record key, then >the proposal equates to a database-style outer join operation (where >data elements with unmatched keys are included) and order is >significant. Does an outer-join have anything to do with lock-step >iteration? Is this a fundamental looping construct or just a >theoretical wish-list item? IOW, does Python really need >itertools.izip_longest() or would that just become a distracting piece >of cruft? Even if there is little use for continuing in correct code, IWT getting at the state of the iterator in an erroroneous situation would be a benefit. Being able to see the result of the last attempt at gathering tuple elements could help. (I can see reasons for wanting variations of trying all streams vs shortcutting on the first to exhaust though). Regards, Bengt Richter From bpeng at rice.edu Thu Jan 26 11:54:51 2006 From: bpeng at rice.edu (Bo Peng) Date: Thu, 26 Jan 2006 10:54:51 -0600 Subject: Start a python interactive shell from python. In-Reply-To: References: Message-ID: I think I find what I need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355319 Bo From peter at engcorp.com Wed Jan 18 08:48:49 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Jan 2006 08:48:49 -0500 Subject: [OT] Nit: please don't user "it's" unless you can substitute "it is" without changing your inteded meaning. In-Reply-To: <43ce2072.1408100020@news.oz.net> References: <43ce2072.1408100020@news.oz.net> Message-ID: Bengt Richter wrote: > Typos happen to all of us, but in case you hadn't realized what "it's" > is a contraction for ("it is"), now you do, and you can save yourself further > embarrassment (assuming you care ;-). > If your friends won't tell you, who will ;-) Maybe we can also hold forth on "which" vs. "that", proper use of "I" versus "me" (usually the opposite of what many do), "each" vs. "all", and when to use "whom". Also throw in the old stand-bys "they're" and "their" and other homonyms, but consider that often the mistake is not cause by a poor grasp of grammar but simply by writing too quickly, as one sometimes "hears" the words incorrectly in one's mind as one types, and then not proofreading adequately. (That's my excuse: I always catch "their" swapped with "they're" when proofreading, but I do sometimes use the wrong one when I write quickly.) Of course, even the best of us make such mistakes, and holding everyone to task for it is probably not going to help. This is a problem which only constant and instrusive reminders would cure, and the cure would be far worse than the disease. > OTOH, how does one punctuate the posessive of a word per se? > E.g., the first letter of "it" is "i", but can one write that > as "it"'s first letter is "i," or it's first letter is "i" ? ;-) When a construction is awkward, pick a different one. '''The first letter of the word "it" is "i"''' should be just fine. > I wonder if "Eats Leaves and Shoots" (a book on punctuation) has something on that. > (vs, "Eats, Leaves, and Shoots" -- panda vs gunslinger). Eats Shoots and Leaves: less cowardly than leaving _then_ shooting... also the actual name of the book. ;-) -Peter From yhdanid at yahoo.com Sun Jan 22 02:55:52 2006 From: yhdanid at yahoo.com (Obaid R.) Date: 21 Jan 2006 23:55:52 -0800 Subject: New Python.org website? References: <1137553529.299812.129090@g43g2000cwa.googlegroups.com> <1137636317.961569.251290@g47g2000cwa.googlegroups.com> Message-ID: <1137916552.778616.152030@g43g2000cwa.googlegroups.com> Terry Hancock wrote: > On 18 Jan 2006 18:05:18 -0800 > "Obaid R." wrote: > > I hope it is not counted against me that I am the first > > one to point out that the logo is shaped like a cross. > [...] > > Hey, looks more like a Yin-Yang symbol to me. ;-) True. But I hope you are not arguing that since it looks to you like a Yin-Yang that it makes it therefore not look like a cross. For even Steve did say that there is no point arguing against what appears like a matter of fact. > > > And why ask with any trepidation, Steve? People of > > different backgrounds have dissimilar sensitivities. I > > hope you agree that it would be unfair to blame people for > > such deeply personal affairs. If trepidation on the part > > of even the Red Cross was enough to cancel such > > sensitivities, we would not have had a Red Crescent or a > > cooperation between them. If not proving one's > > subscription to some set of beliefs, such symbols at least > > disprove the same for others. > > No, I'm sorry, intolerance is bad, no matter who practices > it. And what may be forgiveable on a battlefield is not > forgiveable in my workplace. I can understand that there > were specific circumstances leading to the Red Cross/Red > Crescent schism, and that it had to do with long standing > religious intolerance on both sides. It doesn't make it an > example to follow. > It is apparent that you know only part of the story. Kindly allow me to comment here. Contrary to what you might have heard there was never organized religious intolerance of Christianity by the Muslim side. To give just one easy to follow fact of history, consider this: to this day there are Arabic and Aramaic speaking Christians of Catholic, Orthodox, and Coptic origins living in the Middle East. Some say about twenty million or so. The Muslims who lived in modern day Spain, on the other hand, were either wiped out or forcibly made to convert to Christianity. And their numbers were in the hundreds of thousands if not millions. And this is just one example. > But sheesh, if I objected to every picture of the moon I > see (or pictures that vaguely resemble a moon), I would be > in a very sad state. Come to think of it, I have a crescent > as a background on my company website (it's Neptune, not > Luna, but it certainly resembles a crescent moon more than > that Python thing resembles a cross). Nevertheless, I am not > Muslim. > But you see Terry, the point is not that it is just a picture. And let's not forget that as far as we know the moon has always been a natural part of all human life on this earth before and after Islam, and even for those who never heard of Islam. And so the moon is not a Muslim monopoly. If the crescent was dropped altogether as an identifying symbol no Muslim will lose sleep over it. Do you know why? Because it is not an object of worship, Terry. Here is Almighty God's command to us concerning the sun and moon: "Among His Signs are the Night and the Day, and the Sun and the Moon. Do not prostrate to the sun and the moon, but prostrate to Allah, Who created them, if it is Him ye wish to serve." (Translation, Glorious Qur'an, 41: 37) The crescent found its way on top of domes on Mosques only to point to the direction of the Qibla in Mecca, where all Muslims face to pray. When a Mosque is built the crescent on the dome is made to face parallel to the direction of Qibla. The early Muslims could have chosen any other symbol to point to the Qibla, but they choose the crescent only to be different, and hence to be free from the consequences that other symbols might bring. After all some of these symbols are more or less worshiped. And here I am thinking of the cross. I feel I must stress again that there is no intolerance here, brother. It is hard to deny the fact that many people do kiss the cross, kneel before the cross, and pray beneath the crucifix, is it not? If that is not worship then what is? A "Muslim" who does that to the crescent is no Muslim. Period. For a Muslim kneels to no one and worships no one but Almighty God. And just to point to you the significance of this in case you don't know, the greatest sin in Islam is the worshiping of others (or things) besides Almighty God, who has no equals. "Allah forgiveth not that partners should be set up with Him; but He forgiveth anything else, to whom He pleaseth; to set up partners with Allah is to devise a sin Most heinous indeed." (Translation, Glorious Qur'an, 4: 48) And so to summarize: even if I invent a product and place a crescent on it, you are (as a non-Muslim) not under any obligation or threat of confusing your support for your faith (whatever it may be), because the moon is not a Muslim object of worship nor is it a Muslim monopoly. You forcing the cross on a product that Muslims might use, on the other hand, puts them in a difficult position. After all the cross seems like an object of worship and it seems the indispensable source of identity for Christianity. > > I do realize that I have no say in the decisions affecting > > Python's current and future plans. But it makes sense to > > think that like any other marketed product, Python must > > take into consideration the nature of its target audience. > > And if it is to appeal to international users, then points > > of deep contention are better avoided. Don't you agree? I > > am glad the shape has no significance and I thank you for > > patience. > > In America, we call this attitude "politcal correctness", > and it's a dead end street, my friend. > > You do realize that the visual "namespace" for highly > symmetric symbols that have no religious significance to > anyone anywhere is EXTREMELY crowded, right? > > Especially if you are willing to stretch a picture of two > intertwined snakes into a "Christian" cross (Just to savor > the full irony here, let's remember that snakes are > traditionally a symbol of either Paganism or Voodoo). > The "Red Cross/Red Crescent" thing is a sad reality, IMHO. A > relief organization originally based in Europe uses a flag > which is the inverse of the Swiss flag, because the Swiss > have been (for many, many years) neutral, and that flag > happens to sport a cross, because, (guess what?) Switzerland > was traditionally a Christian country. Then someone who is > apparently incredibly intolerant of other people's religious > symbols actually goes and *TAKES OFFENSE* at this symbol of > neutrality, so that they have to go and create an alternate > one just to pander to that intolerance. > > There is no "Red Yin Yang", "Red Eightfold Path", "Red Star > of David" or "Red Serpent and Rainbow" to my knowledge, and > it would be incredibly stupid for there to be any such. > Apparently, the state of religious tolerance is better in > the countries where those symbols hold sway. > > At worst, the cross might be a reference to "The Spanish > Inquisition", which anyone who knows anything about Python > should know is topical. The language is European in > origin, so the use of symbol which has become broadly a > European symbol (secularly -- look at the flags of Europe, > as well as religiously). > > And besides, we all know it's impossible to avoid "religious > wars" when it comes to computer languages. > > In reality, though, it is accidental, and very slight > resemblance. If you can somehow manage to take offense at > that, then please go get some counseling. > > Cheers, > Terry > > -- > Terry Hancock (hancock at AnansiSpaceworks.com) > Anansi Spaceworks http://www.AnansiSpaceworks.com Please do no let my professed background lead you to false assumptions. I do realize what "political correctness" in America is. I am not sure I agree though that it is a dead end street. It may be for those who think that marketing or even political "spin" contribute nothing to the branding, and selling, and hence adoption of products and ideas. Try telling that to those who were "convinced" of the need to go to war. Nevertheless, the dead end theory is not in keeping with what the literature and experts in Business, political science, and Marketing propagate. The point they make is more or less this: it does not matter what you (the marketer) thinks of people's sensitivities. Your views (as a marketer) on that matter do not count; it is the views of the target audience and their sensitivities that do. That, of course, assumes one wishes to push for the highest adoption rates of a given product by a target audience given a specified budget and time frame. And not all logos are offensive to all people or most people. There is a dead end only if we make one. There are many great logos out there: Sony's, IBM's, Microsoft's, Linux's, Apple's, Google's, etc. And almost all come for a Christian background all the same. The crowded name-space your speak of notwithstanding. To conclude, decision makers can call others names, suggest therapy for them all they wish, and even claim that a cross is a circle and all shapes should mean the same thing to all people all they please. But although easy to do, that, I put it to you, is a sure recipe for failure for the selling of any product or idea. And while I agree that choosing a good logo is difficult, it should not be impossible. Others have done a fine job even when they come from similar backgrounds as the one you claim Python came from. Now refusing to identify people's feelings to try to avoid hurting them, even when brought forward to one's attention in good faith, and even going to the point of ridiculing such concerns will do nothing to hurt these people, Terry. Customers are always right. And they will look elsewhere. Peace From bearophileHUGS at lycos.com Fri Jan 13 06:25:41 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Jan 2006 03:25:41 -0800 Subject: Limiting the size of List and making it Homogeneous In-Reply-To: <1137141924.938971.3790@g49g2000cwa.googlegroups.com> References: <1137141924.938971.3790@g49g2000cwa.googlegroups.com> Message-ID: <1137151541.534194.58900@o13g2000cwo.googlegroups.com> The array module allows you to specify a single type of elements. Bye, bearophile From steve at REMOVEMEcyber.com.au Wed Jan 4 21:11:54 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 05 Jan 2006 13:11:54 +1100 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <8664ozd1bm.fsf@bhuda.mired.org> Message-ID: <43BC806A.1040201@REMOVEMEcyber.com.au> Mike Meyer wrote: > Peter Hansen writes: > > >>Steven D'Aprano wrote: >> >>>Python does not have references or pointers, except internally where >>>Python coders can not get to them. It has names and objects. Keep thinking >>>about "call by reference" and you just confuse yourself and others. Think >>>about names and objects and it is simple and straight-forward. >> >>I won't argue the point, but I would point out that the term "name" is >>insufficient for whatever it is that is stored inside a list. > > > Correct. What's stored in a list is a reference. Nonsense. What is stored in the list is an object. Python doesn't have pointers. You are confusing the underlying C implementation, which implements lists as an array of pointers, with the high-level Python code, which doesn't even know what a pointer is. It only has objects. Since we are discussing the perspective from a Python programmer's point of view, it is irrelevant what the C implementation does. If lists held references, you could do this: x = 5 L = [1, 2, x] # the third item points to the same memory location # as x; changing it will also change x L[2] = 7 assert x == 7 which is the behaviour that "call by reference" implies. But it doesn't work that way in high-level Python code. The *reason* it doesn't work is that the object 5 is immutable. If you only ever passed mutable objects around, you would think Python was call by reference. And if you only ever passed immutable objects around, you would think Python was call by value. But since Python has both sorts of objects, it displays both sorts of behaviour. -- Steven. From deets at nospam.web.de Thu Jan 12 16:07:53 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jan 2006 22:07:53 +0100 Subject: File Navigation using python In-Reply-To: References: Message-ID: <42nupaF1kbuqqU1@uni-berlin.de> Danielsen Brian (IFR Contractor External) wrote: > Does anyone know how to do file navigation between drives? I know how to navigate up and down within a drive (for example the C:\ drive), but I don't know how to change drives. I'm looking for something like: > > os.chgdrv('d:\') os.chdir Diez From fuzzyman at gmail.com Sat Jan 21 03:10:08 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Jan 2006 00:10:08 -0800 Subject: Redirecting standard out in a single namespace In-Reply-To: <1137792895.143995.270810@o13g2000cwo.googlegroups.com> References: <1137771435.682063.178150@g14g2000cwa.googlegroups.com> <1137792895.143995.270810@o13g2000cwo.googlegroups.com> Message-ID: <1137831008.806546.212150@f14g2000cwb.googlegroups.com> Ido Yehieli wrote: > I'm sorry, but i don't see how this will solve the problem? It is > exactly the same, only now you've replaced everything in sys except > just sys.stdout? In the solution above (which I haven't had a chance to test) you're just chaning hte reference to sys to point to a different module, so you're not messing with sys itself. This won't affect other code that uses the sys module. Because of the builtin status of the sys module I'm not *convinced* it will work. I'll try it though. > At any rate, perhapse the code you will write will be more maintainable > if instead of redirecting sys.stdout for some of the code just use a > different function (instead of print) for the times where you wish it > to be redirected somewhere else? it will probably make your code > longer, but the maintainer will have one less "gotcha" to worry about a > few months/years down the road. perhapse it is best to not do the > "clever" thing this time ;-) ? We're executing code from another module that uses the print statement a lot. That module isn't our code - other wise we wouldn't have a problem. :-) Changing the module will mean a great deal more to maintain, not less. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From newstonne at web.de Tue Jan 24 03:57:19 2006 From: newstonne at web.de (Roland Heiber) Date: Tue, 24 Jan 2006 09:57:19 +0100 Subject: Testing for the presence of input from stdin. In-Reply-To: References: Message-ID: Will McDonald wrote: > Hi all. > > I'm writing a little script that operates on either stdin or a file > specified on the command line when run. I'm trying to handle the > situation where the script's run without any input gracefully but > can't think how to test for stdin. > Hi, maybe http://docs.python.org/lib/module-fileinput.html is useful for you: "This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed." HtH, Roland From techiepundit at futurepundit.com Thu Jan 12 19:03:20 2006 From: techiepundit at futurepundit.com (Randall Parker) Date: 12 Jan 2006 16:03:20 -0800 Subject: Conditionals stored as text to translate to real compares Message-ID: <1137110600.344216.214280@g14g2000cwa.googlegroups.com> I want to know if there is some way to translate fragments of text into operators (e.g. <, >, <>, ==, etc) to use in conditional expressions. I've got a data structure which is a list of lists. A single list might look like: MyInnerList = ["MyVar",">",7] or MySecondInnerList = ["MyOtherVar","<=",25.5] These all go in something like: MyMainList = [["MyVar",">",7],["MyOtherVar","<=",25.5], and so on...] I have some target device which I go query with the names in the first field (e.g. "MyVar") to get values back. The target device returns all values as strings. Then I want to compare to the value in the third field. In theory the third field might contain floats, integers, or maybe some day strings. So I access the middle operator field like this: OperatorType = MyInnerList[1] # This gets back ">" or "<=" for example TestVal = MyInnerList(2) TargetVal gets filled in by talking to my target device. Then I want to compare TestVal and TargetVal using OperatorType. I'm thinking I have to do something like: if OperatorType == ">": # then do a greater than compare here. BoolVal = TestVal > TargetVal elif OperatorType == ">=": # then do a greater or equal to here. BoolVal = TestVal >= TargetVal and so on. It would seem a lot easier to do: BoolVal = TargetVal EvalStrToOper(">") MyInnerList(2) where EvalStrToOper creates an immediate > sign that then allows that line to get evaluated by the interpreter. Is there any way to do that in Python? Of course, I'd have to guarantee that the ">" or other operators are really legal operators. Also, I'd have to test MyInnerList(2) to make sure it is an appropriate type. From anton.vredegoor at gmail.com Sun Jan 29 10:23:55 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 29 Jan 2006 07:23:55 -0800 Subject: "Intro to Pyparsing" Article at ONLamp References: <1138444565.250434.28030@g47g2000cwa.googlegroups.com> Message-ID: <1138548235.414808.134410@g44g2000cwa.googlegroups.com> Paul McGuire wrote: > There are two types of parsers: design-driven and data-driven. With > design-driven parsing, you start with a BNF that defines your language or > data format, and then construct the corresponding grammar parser. As the > design evolves and expands (new features, keywords, additional options), the > parser has to be adjusted to keep up. > > With data-driven parsing, you are starting with data to be parsed, and you > have to discern the patterns that structure this data. Data-driven parsing > usually shows this exact phenomenon that you describe, that new structures > that were not seen or recognized before arrive in new data files, and the > parser breaks. There are a number of steps you can take to make your parser > less fragile in the face of uncertain data inputs: > - using results names to access parsed tokens, instead of relying on simple > position within an array of tokens > - anticipating features that are not shown in the input data, but that are > known to be supported (for example, the grammar expressions returned by > pyparsing's makeHTMLTags method support arbitrary HTML attributes - this > creates a more robust parser than simply coding a parser or regexp to match > "' > For example, I had this > > experience when parsing chess games from videotext pages I grab from my > > videotext enabled TV capture card. Maybe once or twice in a year > > there's a chess page with games on videotext, but videotext chess > > display format always changes slightly in the meantime so I have to > > adapt my script. For such things I've switched back to 'hand' coding > > because it seems to be more flexible. > > > > Do these chess games display in PGN format (for instance, "15. Bg5 Rf8 16. > a3 Bd5 17. Re1+ Nde5")? The examples directory that comes with pyparsing > includes a PGN parser (submitted by Alberto Santini). Ah, now I remember, I think this was what got me started on pyparsing some time ago. The dutch videotext pages are online too (and there's a game today): http://teletekst.nos.nl/tekst/683-01.html But as I said there can be transmission errors and human errors. And the dutch notation is used, for example a L is a B, a P is a K, D is Q, T is R. I'd be interested in a parser that could make inferences about chess games and use it to correct these pages! > > What I would like to see, in order to improve on this situation is a > > graphical (tkinter) editor-highlighter in which it would be possible to > > select blocks of text from an (example) page and 'name' this block of > > text and select a grammar which it complies with, in order to assign a > > role to it later. That would be the perfect companion to pyparsing. > > > > At the moment I don't even know if such a thing would be feasible... > > There are some commercial parser generator products that work exactly this > way, so I'm sure it's feasible. Yes, this would be a huge enabler for > creating grammars. And pave the way for a natural language parser. Maybe there's even some (sketchy) path now to link computer languages and natural languages. In my mind Python has always been closer to human languages than other programming languages. From what I learned about it, language recognition is the easy part, language production is what is hard. But even the easy part has a long way to go, and since we're also using a *visual* interface for something that in the end originates from sound sequences (even what I type here is essentially a representation of a verbal report) we have ultimately a difficult switch back to auditory parsing ahead of us. But in the meantime the tools produced (even if only for text parsing) are already useful and entertaining. Keep up the good work. Anton. From bokr at oz.net Sun Jan 8 17:20:58 2006 From: bokr at oz.net (Bengt Richter) Date: Sun, 08 Jan 2006 22:20:58 GMT Subject: decorator question References: Message-ID: <43c18ac5.583351344@news.oz.net> On Sun, 08 Jan 2006 23:26:28 +0100, =?ISO-8859-1?Q?Sch=FCle_Daniel?= wrote: [...] > >the code above works fine >but I am wondering wheather it's possible to >write something like this > > >>> def timelogger(f, logfile=sys.stdout): >... def wrapper(*a,**kw): >... logfile.write("started at %s" % time.ctime()) >... t0 = time.time() >... f(*a, **kw) >... t1 = time.time() >... logfile.write("ended at %s" % time.ctime()) >... logfile.write("diff = %f %s" % (t1-t0, "sec")) >... return wrapper > > >>> import time > >>> @timelogger(file("hierher", "a")) ### <<<<<< (1) >... def loops(a,b,c): >... sum = 0 >... for i in range(a): >... for j in range(b): >... for k in range(c): >... sum += 1 >... > >(1) fails to compile >is it possible to pass parameters to a decorator function? > Yes, but then the function must return the same kind of thing a bare decorator-function name would have, which is a function able to take a single argument of a function and return a function. So your decorator won't take f as an argument, just the optional logfile, and it will return a function that does the wrapping like the original decorator. >>> import sys, time >>> def timelogger(logfile=sys.stdout): ... def deco(f): ... def wrapper(*a,**kw): ... logfile.write("started at %s\n" % time.ctime()) ... t0 = time.time() ... f(*a, **kw) ... t1 = time.time() ... logfile.write("ended at %s\n" % time.ctime()) ... logfile.write("diff = %f %s\n" % (t1-t0, "sec")) ... return wrapper ... return deco ... >>> @timelogger() # stdout ... def foo(): pass ... >>> foo() started at Sun Jan 08 14:13:55 2006 ended at Sun Jan 08 14:13:55 2006 diff = 0.000000 sec >>> foo() started at Sun Jan 08 14:14:02 2006 ended at Sun Jan 08 14:14:02 2006 diff = 0.000000 sec >>> @timelogger() # stdout ... def foo(dt): time.sleep(dt) ... >>> foo(5) started at Sun Jan 08 14:14:59 2006 ended at Sun Jan 08 14:15:04 2006 diff = 5.007000 sec >>> foo(.5) started at Sun Jan 08 14:15:16 2006 ended at Sun Jan 08 14:15:17 2006 diff = 0.501000 sec >>> Regards, Bengt Richter From fredrik at pythonware.com Thu Jan 19 04:27:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Jan 2006 10:27:11 +0100 Subject: Arithmetic sequences in Python References: <1137402099.920352.275350@o13g2000cwo.googlegroups.com><7x64ojtyw4.fsf@ruckus.brouhaha.com><1h9byun.1oju1dgt34dliN%aleax@mail.comcast.net><6O-dnTa_XL7-6VPenZ2dnUVZ_tadnZ2d@comcast.com><7xmzht8nbn.fsf@ruckus.brouhaha.com><1h9dhq8.16gsvmfyc0sflN%aleax@mail.comcast.net><7xirsgg6cm.fsf@ruckus.brouhaha.com><1h9drrb.1leza4z8ueoyfN%aleax@mail.comcast.net> <43CF5390.9000707@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > > I much prefer the current arrangement where dict(a=b,c=d) means {'a':b, > > 'c':d} -- it's much more congruent to how named arguments work for every > > other case. Would you force us to quote argument names in EVERY > > functioncall...?! > > Hmmm... should these two forms give different results? > > >>> a = 0 > >>> b = 1 > >>> A = {a: b} > >>> B = dict(a=b) > >>> A, B > ({0: 1}, {'a': 1}) > > I feel very uncomfortable about that. Am I alone? yes. From cowie.rob at gmail.com Tue Jan 17 15:29:18 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 17 Jan 2006 12:29:18 -0800 Subject: Using CGI to interface with an XML-RPC server Message-ID: <1137529758.132297.73050@z14g2000cwz.googlegroups.com> Hi all, Assume I have a working XML-RPC server that runs persistently and correctly accepts remote calls, executes the relevant code and outputs the XML-RPC result. This is fine when using an XML-RPC client. However, I wish to provide a web user interface. I gather it is possible to use PHP as an XML-RPC client but I am unable to do so because of artificially imposed server constraints. All I am able to use is good the old CGI. Is it possible to create python CGI scripts that accept form data in the usual way, package them as an XML-RPC request, call the server, receive the response then format this response into valid HTML to be emitted to the client? Is this desirable (what I mean is... is there an easier way?). Is there a better way to use a web browser as what is essentially an XML-RPC client? FYI, I know that is seems like using XML-RPC in this case is pointless.. it isn't, some users do indeed use the server as intended. Cheers, From python at rcn.com Sun Jan 29 20:39:39 2006 From: python at rcn.com (Raymond Hettinger) Date: 29 Jan 2006 17:39:39 -0800 Subject: Print dict in sorted order References: <1138565199.894137.31990@g49g2000cwa.googlegroups.com> Message-ID: <1138585179.927355.76250@o13g2000cwo.googlegroups.com> [Kamilche] > I have a code snippet here that prints a dict in an arbitrary order. > (Certain keys first, with rest appearing in sorted order). I didn't > want to subclass dict, that's error-prone, and overkill for my needs. I > just need something that returns a value like dict.__str__, with a key > ordering I specify. > > If you have any opinions on how it could be made better, I'm all ears! Here's one more version to throw in the mix: from itertools import count, izip def dict2str(d, preferred_order = ['gid', 'type', 'parent', 'name']): last = len(preferred_order) rank = dict(izip(preferred_order, count())) pairs = d.items() pairs.sort(key=lambda (k,v): rank.get(k, (last, k, v))) return '{%s}' % repr(pairs)[1:-1] d = dict(gid=10, type=20, parent=30, name=40, other=50, rest=60) print dict2str(d) Raymond From bobrien18 at yahoo.com Fri Jan 6 10:57:04 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 6 Jan 2006 07:57:04 -0800 Subject: Spelling mistakes! In-Reply-To: References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> Message-ID: <1136563024.045851.42700@g14g2000cwa.googlegroups.com> try this: class x(object): def __init__(self): self.someName = "hello" def someMethod(self): self.sumName = "bye" find that bug. From exarkun at divmod.com Sun Jan 15 21:20:59 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 15 Jan 2006 21:20:59 -0500 Subject: proposal: another file iterator In-Reply-To: <7xy81hknmf.fsf@ruckus.brouhaha.com> Message-ID: <20060116022059.26200.910215487.divmod.quotient.1080@ohm> On 15 Jan 2006 16:44:24 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >I find pretty often that I want to loop through characters in a file: > > while True: > c = f.read(1) > if not c: break > ... > >or sometimes of some other blocksize instead of 1. It would sure >be easier to say something like: > > for c in f.iterbytes(): ... > >or > > for c in f.iterbytes(blocksize): ... > >this isn't anything terribly advanced but just seems like a matter of >having the built-in types keep up with language features. The current >built-in iterator (for line in file: ...) is useful for text files but >can potentially read strings of unbounded size, so it's inadvisable for >arbitrary files. > >Does anyone else like this idea? It's a pretty useful thing to do, but the edge-cases are somewhat complex. When I just want the dumb version, I tend to write this: for chunk in iter(lambda: f.read(blocksize), ''): ... Which is only very slightly longer than your version. I would like it even more if iter() had been written with the impending doom of lambda in mind, so that this would work: for chunk in iter('', f.read, blocksize): ... But it's a bit late now. Anyhow, here are some questions about your iterbytes(): * Would it guarantee the chunks returned were read using a single read? If blocksize were a multiple of the filesystem block size, would it guarantee reads on block-boundaries (where possible)? * How would it handle EOF? Would it stop iterating immediately after the first short read or would it wait for an empty return? * What would the buffering behavior be? Could one interleave calls to .next() on whatever iterbytes() returns with calls to .read() on the file? Jean-Paul From python at rcn.com Wed Jan 4 18:20:43 2006 From: python at rcn.com (Raymond Hettinger) Date: 4 Jan 2006 15:20:43 -0800 Subject: itertools.izip brokeness References: <1136283553.577340.232330@z14g2000cwz.googlegroups.com> <1136286134.182758.184600@g49g2000cwa.googlegroups.com> <1136328638.694917.291600@g43g2000cwa.googlegroups.com> <1136362998.895356.66640@g44g2000cwa.googlegroups.com> <7x4q4kmj8e.fsf@ruckus.brouhaha.com> Message-ID: <1136416843.654509.222050@g47g2000cwa.googlegroups.com> Paul Rubin wrote: > What do you think of my suggestion of passing an optional arg to the > StopIteration constructor, that the caller can use to resume the > iterator or take other suitable recovery steps? Maybe this could > interact with PEP 343 in some useful way. Probably unworkable. Complex to explain and use. Makes the API heavy. Hard to assure retro-fitting for every possible kind of iterator or iterable. Am not sure of the best solution: 1. Could add an optional arg to zip()/izip() with a mutable container to hold a final, incomplete tuple: final=[]; zip(a,b,leftover=final). This approach is kludgy and unlikely to lead to beautiful code, but it does at least make accessible data that would otherwise be tossed. 2. Could add a new function with None fill-in -- essentially an iterator version of map(None, a,b). Instead of None, a user specified default value would be helpful in cases where the input data stream could potentially have None as a valid data element. The function would also need periodic signal checks to make it possible to break-out if one the inputs is infinite. How or whether such a function would be used can likely be answered by mining real-world code for cases where map's None fill-in feature was used. 3. Could point people to the roundrobin() recipe in the collections.deque docs -- it solves a closely related problem but is not exactly what the OP needed (his use case required knowing which iterator gave birth to each datum). 4. Could punt and leave this for straight-forward while-loop coding. Though the use case seems like it would be common, there may be a reason this hasn't come up since zip() was introduced way back in Py2.0. 5. Could create an iterator wrapper that remembers its last accessed item and whether StopIteration has been raised. While less direct than a customized zip method, the wrapper may be useful in contexts other than zipping -- essentially, anywhere it is inconvenient to have just consumed an iterator element. Testing the wrapper object for StopIteration would be akin to else-clauses in a for-loop. OTOH, this approach is at odds with the notion of side-effect free functional programming and the purported benefits of that programming style. Raymond Hettinger From claird at lairds.us Tue Jan 3 11:08:03 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 03 Jan 2006 16:08:03 GMT Subject: Any wing2.0 users here? References: Message-ID: <9ohq83-1bh.ln1@lairds.us> In article , Alvin A. Delagon wrote: . . . >A little bit OT, I too have been programming python without a debugger, >I got used to php's lack of debugger. Thanks again guys! ?! With NuSphere, Gubed, Komodo, DBG, APD, PhpED, Zend Studio, ..., in what sense does PHP lack a debugger? From rupole at hotmail.com Tue Jan 10 17:55:52 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 10 Jan 2006 17:55:52 -0500 Subject: COM automation, Internet Explorer, DocumentComplete event References: <1136923783.403261.188890@g14g2000cwa.googlegroups.com> Message-ID: <1136933915_157@spool6-east.superfeed.net> PythonCom interfaces implement __cmp__ so that you can just use a straight == comparison. hth Roger "puff" wrote in message news:1136923783.403261.188890 at g14g2000cwa.googlegroups.com... > I'm very new to Python and have a question concerning IE automation and > detection of page completion. > > The MSDN article 180366 states in part: > > ---- > The top-level frame fires the DocumentComplete in the end. So, to check > if a page is done downloading, you need to check if the IDispatch* > parameter is same as the IDispatch of the WebBrowser control. > > For Visual Basic, here is code that performs this check: > > Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, > URL As Variant) > If (pDisp Is WebBrowser1.Object) Then > Debug.Print "Web document is finished downloading" > End If > End Sub > ---- > > I'm able to catch IE's events including DocumentComplete with: > > def OnDocumentComplete(self, pDisp, URL): > > so i have pDisp. Self is the object returned by: > > self.ie = DispatchWithEvents("InternetExplorer.Application", > InternetExplorerEvents) > > that created the automation object. How do I perform the test in > Python? > > Thanks for any help. > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From noway at sorry.com Thu Jan 19 05:47:35 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 19 Jan 2006 10:47:35 GMT Subject: Returning a tuple-struct References: <1137637493.938952.321270@g47g2000cwa.googlegroups.com> Message-ID: groups.20.thebriguy at spamgourmet.com wrote: >>>> time.localtime() > (2006, 1, 18, 21, 15, 11, 2, 18, 0) >>>> time.localtime()[3] > 21 >>>> time.localtime().tm_hour > 21 > > Anyway, I guess there's a few of ways to do this. In the case above, > it would seem reasonable to override __getitem__() and other things to > get that result. I have a generic solution for this (never submitted to the cookbook... should I?) import operator def NamedTuple(*args, **kwargs): class named_tuple_class(tuple): pass values = [] idx = 0 for arg in args: for name in arg[:-1]: setattr(named_tuple_class, name, property(operator.itemgetter(idx))) values.append(arg[-1]) idx += 1 for name,val in kwargs.iteritems(): setattr(named_tuple_class, name, property(operator.itemgetter(idx))) values.append(val) idx += 1 return named_tuple_class(values) >>> t = NamedTuple(("x", 12), ("y", 18)) >>> t (12, 18) >>> t[0] 12 >>> t.x 12 >>> t[1] 18 >>> t.y 18 >>> t.z Traceback (most recent call last): File "", line 1, in ? AttributeError: 'named_tuple_class' object has no attribute 'z' >>> t = NamedTuple(("p", "pos", "position", 12.4)) >>> t (12.4,) >>> t.p 12.4 >>> t.pos 12.4 >>> t.position 12.4 >>> t = NamedTuple(("p", "pos", 12.4), length="foo") >>> t (12.4, 'foo') >>> t.p 12.4 >>> t.pos 12.4 >>> t.length 'foo' -- Giovanni Bajo From rocky at panix.com Sun Jan 15 23:00:00 2006 From: rocky at panix.com (R. Bernstein) Date: 15 Jan 2006 23:00:00 -0500 Subject: Getting better traceback info on exec and execfile - introspection? References: <1137364070.475660.8740@g43g2000cwa.googlegroups.com> Message-ID: "Ziga Seilnacht" writes: > You should check the getFrameInfo function in zope.interface package: > http://svn.zope.org/Zope3/trunk/src/zope/interface/advice.py?rev=25177&view=markup Thanks! Just looked at that. The logic in the relevant part (if I've extracted this correctly): f_globals = frame.f_globals hasName = '__name__' in f_globals module = hasName and sys.modules.get(f_globals['__name__']) or None namespaceIsModule = module and module.__dict__ is f_globals if not namespaceIsModule: # some kind of funky exec kind = "exec" is definitely not obvious to me. exec's don't have module namespace (or something or other)? Okay. And that the way to determine the module-namespace thingy is whatever that logic is? Are the assumptions here be likely to be valid in the future? Another problem I have with that code is that it uses the Zope Public License. But the code is adapted from the Python Enterprise Application Kit (PEAK) which doesn't seem to use the Zope Public License. I'm not sure it's right to adopt a Zope Public License just for this. So instead, I followed the other avenue I suggested which is dissembling the statement around the frame. Talk about the kettle calling the pot black! Yes, I don't know if the assumptions in this method are likely to be valid in the future either. But I can use op-code examination to also help me determine if we are stopped at a def statement which I want to skip over. So here's the code I've currently settled on: from opcode import opname def op_at_frame(frame): code = frame.f_code.co_code pos = frame.f_lasti op = ord(code[pos]) return opname[op] def is_exec_stmt(frame): """Return True if we are looking at an exec statement""" return frame.f_back is not None and op_at_frame(frame.f_back)=='EXEC_STMT' re_def = re.compile(r'^\s*def\s+') def is_def_stmt(line, frame): """Return True if we are looking at a def statement""" # Should really also check that the operand is a code object return re_def.match(line) and op_at_frame(frame)=='LOAD_CONST' But it may just be because I wrote it that I find it easier to understand and more straightforward to fathom. > > And suppose instead of '' I'd like to give the value or the > > leading prefix of the value instead of the unhelpful word ''? > > How would one do that? Again, one way is to go into the outer frame > > get the source line (if that exists), parse that and interpolate > > argument to exec(file). Is there are better way? > > Py library (http://codespeak.net/py/current/doc/index.html) has some > similar functionality in the code subpackage. Again, many thanks. I'll have to study this further. It may be that exec and so on are wrapped so that it's possible to squirrel away the string before calling exec. Again, dunno. But thanks for the pointer. From q.q at q Wed Jan 25 03:16:17 2006 From: q.q at q (Mathijs) Date: 25 Jan 2006 08:16:17 GMT Subject: list comprehention References: <1137688948.317183.159290@z14g2000cwz.googlegroups.com> <1137689209.568911.132120@g14g2000cwa.googlegroups.com> <1137690685.243720.191690@o13g2000cwo.googlegroups.com> Message-ID: 23 jan 2006 ta (Steven D'Aprano) shuo le: >> This is the type of solution I was hoping to see: one-liners, with no >> use of local variables. > > Because you like unreadable, incomprehensible, unmaintainable code? For practical use: no! But I'm just learning python and to understand sets/lists/dicts and it's functions, this seemed like good practise:) and besides that: it's fun! A solution with local vaiables, if-statemenst and a for loop wouldn't be much different from what I know with my current programming skills. > *wink* Yeah, yeah, I know, but I felt a response was on its place. :) From bokr at oz.net Thu Jan 5 13:58:59 2006 From: bokr at oz.net (Bengt Richter) Date: Thu, 05 Jan 2006 18:58:59 GMT Subject: inline function call References: Message-ID: <43bd6179.310635920@news.oz.net> On Thu, 05 Jan 2006 08:47:37 +1100, Steven D'Aprano wrote: >On Wed, 04 Jan 2006 13:18:32 +0100, Riko Wichmann wrote: > >> hi everyone, >> >> I'm googeling since some time, but can't find an answer - maybe because >> the answer is 'No!'. >> >> Can I call a function in python inline, so that the python byte compiler >> does actually call the function, but sort of inserts it where the inline >> call is made? Therefore avoiding the function all overhead. > >The closest thing to that is the following: > > ># original version: > >for i in xrange(100000): > myObject.something.foo() # three name space lookups every loop > > ># inline version: > ># original version: > >foo = myObject.something.foo >for i in xrange(100000): > foo() # one name space lookup every loop > But that isn't in-lining, that's hoisting some expression-evaluation out of a loop on the assumption that the expression has constant value and no side effects. That's good optimization, but it isn't in-lining. Inlining is putting code to accomplish what foo does in place of the foo call. E.g. if under simple conditions and assumptions you in-lined def foo(x,y):return 2*x+y+1 in a = 3*foo(b,c) the code would be a = 3*(2*b+c+1) This could be achieved by a custom import function that would capture the AST and e.g. recognize a declaration like __inline__ = foo, bar followed by defs of foo and bar, and extracting that from the AST and modifying the rest of the AST wherever foo and bar calls occur, and generating suitable substitutions of suitable AST subtrees generated from the ASTs of the foo and bar ASTs and rules for renaming and guaranteeing safe temporary names etc. The modified AST would then pass through the rest of the process to compilation and execution for the creation of a module. You just wouldn't be able to plain old import to do the importing (unless you had the custom import hooked in, and assumed that sources without __inline__ = ... statements would not occur unintended. Without hooking, usage might look like import inliner mymod = inliner.__import__('mymod') # side effect to mymod.pyc and sys.modules and then you could expect calls to designated and defined inline functions in mymod.py to have been inlined in the code of mymod. I've been meaning to do a proof of concept, but I've hinted at these things before, and no one seems much interested. And besides it's really a distraction from more radical stuff I'd like to try ;-) Regards, Bengt Richter From steve at holdenweb.com Thu Jan 26 12:32:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jan 2006 17:32:32 +0000 Subject: Tkinter listener thread? In-Reply-To: <1138293971.203647.163120@g49g2000cwa.googlegroups.com> References: <1138293971.203647.163120@g49g2000cwa.googlegroups.com> Message-ID: gregarican wrote: > I have a Python UDP listener socket that waits for incoming data. The > socket runs as an endless loop. I would like to pop the incoming data > into an existing Tkinter app that I have created. What's the > easiest/most efficient way of handling this? Would I create a separate > thread that has the listener set a certain Tkinter variable if there is > incoming data? Any suggestions would be tremendously appreciated :-) > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From deliverable at gmail.com Tue Jan 17 17:05:00 2006 From: deliverable at gmail.com (braver) Date: 17 Jan 2006 14:05:00 -0800 Subject: magical expanding hash References: <1137478291.342584.83030@g47g2000cwa.googlegroups.com> <1137533023.895288.277950@z14g2000cwz.googlegroups.com> Message-ID: <1137535500.430719.198090@f14g2000cwb.googlegroups.com> The point of this exercise is to compare how either ruby or python can implement perl's default behavior when dealing with hashes. Since these are bread and butter of scripting, having a MEH class handy can enable fast semantically equivalent translation. This can be beneficial for demonstrating feasibility of migrating to python. Instead of debating philosophical justifications, I rather wonder what's the most appropriate pythonic way to solve the problem as stated. From kay.schluehr at gmx.net Thu Jan 19 09:25:29 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jan 2006 06:25:29 -0800 Subject: Efficient implementation of deeply nested lists In-Reply-To: References: <1137662346.819766.149310@g43g2000cwa.googlegroups.com> Message-ID: <1137680729.611996.165940@o13g2000cwo.googlegroups.com> Peter Otten wrote: > Kay Schluehr wrote: > > > I want to manipulate a deeply nested list in a generic way at a > > determined place. Given a sequence of constant objects a1, a2, ..., aN > > and a variable x. Now construct a list from them recursively: > > > > L = [a1, [a2, [....[aN, [x]]...]] > > > > The value of x is the only one to be changed. With each value of x a > > new instance of L is needed so that we actually have a function: > > > > L = lambda x: [a1, [a2, [....[aN, [x]]...]] > > > > I'm seeking for an efficient implementation that does not recompute the > > whole list each time. Any ideas? > > I'd say you are nesting the wrong way. The structure of the sequence is *not* optional. > > >>> items = make_list(range(10)) > >>> def make_list(items): > ... return reduce(lambda *args: args, items) > ... > >>> def update_value(items, value): > ... return items[0], value > ... > >>> items = make_list(range(10)) > >>> items > (((((((((0, 1), 2), 3), 4), 5), 6), 7), 8), 9) > >>> update_value(items, 42) > (((((((((0, 1), 2), 3), 4), 5), 6), 7), 8), 42) > > Obviously I must be missing something. What? The structure of the sequence is *not* optional. Of course you can also take the original sequence and apply: >>> L = list([a1, [a2, [....[aN, [x]]...]]) # shallow copy >>> L[0] = b but it is intended to change the most inner element. I guess there is no way in doing it without a deepcopy / full list construction. Kay From hancock at anansispaceworks.com Thu Jan 5 23:18:39 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 5 Jan 2006 22:18:39 -0600 Subject: Is 'everything' a refrence or isn't it? In-Reply-To: References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <8664ozd1bm.fsf@bhuda.mired.org> <43BC806A.1040201@REMOVEMEcyber.com.au> <86wthfbae0.fsf@bhuda.mired.org> Message-ID: <20060105221839.7d78faa6@samwise.anansi> On Fri, 06 Jan 2006 12:01:09 +1100 "Steven D'Aprano" wrote: > On Wed, 04 Jan 2006 22:51:03 -0500, Mike Meyer wrote: > > >> And if you only ever passed immutable objects around, > >you would > think Python was call by value. > > > > You might. Then again, you might also understand the > > concepts well enough to realize that there isn't any > > difference between CBR and CBV when you're passing > > immutable objects. > > Consider this: > > def do_nothing(x): > pass > > huge_tuple = (None,) * 10000**4 > do_nothing(huge_tuple) > > If Python made a copy of huge_tuple before passing it to > the function, you would notice. Which succinctly demonstrates precisely why a newbie *should* be told that Python passes references instead of values. Without this basic knowledge, the newcomer can't possibly be expected to make intelligent choices of algorithm. But it should probably also be made clear that "reference" means a label assigned to an object, and not a variable containing a memory location (which is what a C "pointer" is). The reference is usually a simple name, but it can also be an container expression following list, dictionary, or class instance (spam, spam[0], spam['eggs'], or spam.ham, for example). Not tuple or string because they are immutable, and so don't have assignable references. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From skip at pobox.com Thu Jan 19 09:58:43 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 19 Jan 2006 08:58:43 -0600 Subject: New Python.org website ? In-Reply-To: References: <43C4E198.2080107@holdenweb.com> <1137573186.943743.32150@g47g2000cwa.googlegroups.com> Message-ID: <17359.43299.514444.4078@montanaro.dyndns.org> >> I'm assured that in print ads the only "content" anyone reads is in >> picture captions, and you damn well better make sure your message is >> conveyed there. Any other "content" only wastes space. I see no >> reason to think that a web page should be designed using any other >> assumption. Roel> I don't agree. I read websites in search for information Roel> (content), not to find advertisements. If a site I want to visit Roel> looks too much like an advertisement, I handle it the same as I Roel> handle any other advertisement: throw it away. Sure, but that's not what JW said. He said that *when looking at ads* the only bits of content people read are the captions of the pictures. He said nothing about what people read when they are reading non-advertising content. Skip From steve at holdenweb.com Tue Jan 10 18:56:21 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Jan 2006 23:56:21 +0000 Subject: - E04 - Leadership! Google, Guido van Rossum, PSF In-Reply-To: References: <43b15d36$0$82640$ed2619ec@ptn-nntp-reader03.plus.net> <1135782518.053020.14730@g43g2000cwa.googlegroups.com> <1h8hyw6.1sioocwkju4zjN%aleax@mail.comcast.net> <1136205478.918848.245620@g44g2000cwa.googlegroups.com> <1h8j7ia.1l5aln617o84osN%aleax@mail.comcast.net> Message-ID: Fredrik Lundh wrote: > TAG.how.come.this.thread.generates.kooks.faster.than.I.can.plonk.them.questionmark > TAG.did.you.just.call.me.a.kook.questionmark TAG.above.tag.not.actually.valid -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From grante at visi.com Sat Jan 21 18:06:51 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 21 Jan 2006 23:06:51 -0000 Subject: Read from Serial Port References: <11t3bbn5ig1uhc8@corp.supernews.com> <43eljmF1mg34vU2@uni-berlin.de> Message-ID: <11t5fkb64ibqhdc@corp.supernews.com> On 2006-01-21, Diez B. Roggisch wrote: >> appropriate platform-specific code. I'll be happy to answer >> questions about the Posix parts of it, but I had the portion of >> my brain containing Win32 knowledge cauterized. > > I'm working on that. Last time I checked there was even some AMIGA > pre-AGA-stuff in there. Which I actually think is cute, but could be > filled with other more useful stuff. Any suggestions for a good > cauterization service? Yea, um, hmm. Don't remember that either. Sloppy work then, eh? Just as well. -- Grant Edwards grante Yow! ... A housewife at is wearing a polypyrene visi.com jumpsuit!! From paul at boddie.org.uk Mon Jan 23 11:48:45 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Jan 2006 08:48:45 -0800 Subject: Launch file based on association References: Message-ID: <1138034925.306861.220950@o13g2000cwo.googlegroups.com> Fredrik Lundh wrote: > Chris Cioffi wrote: > > > Q: If I have a file called "spreadsheet.xls" how can I launch it in what > > ever program it is associated with? I don't care if that program is Excel > > or OpenOffice Calc. I just want to launch the file. > > >>> import os > >>> help(os.startfile) [...] And for a cross-platform experience, try the desktop module: http://www.python.org/pypi/desktop It uses os.startfile on Windows, but also provides access to file/URL opening functionality in KDE, GNOME and Mac OS X. Given a comprehensive enough selection of software (and a sane configuration), even Excel files can be opened in Calc using desktop.open. Paul From googlenews at tooper.org Thu Jan 19 08:06:03 2006 From: googlenews at tooper.org (tooper) Date: 19 Jan 2006 05:06:03 -0800 Subject: Registering COM python based components when not admin In-Reply-To: <1137630743_767@sp6iad.superfeed.net> References: <1137599189.199587.87960@g44g2000cwa.googlegroups.com> <1137630743_767@sp6iad.superfeed.net> Message-ID: <1137675963.221852.51130@g44g2000cwa.googlegroups.com> Thanks for the hint ! From fperez.net at gmail.com Sat Jan 14 19:41:27 2006 From: fperez.net at gmail.com (Fernando Perez) Date: Sat, 14 Jan 2006 17:41:27 -0700 Subject: New Python.org website ? References: <1137165407.149259.306470@o13g2000cwo.googlegroups.com> <43C7CACC.4060602@tim.thechases.com> Message-ID: Tim Chase wrote: >> http://beta.python.org > > In both Mozilla-suite (1.7) and FireFox (1.5), the links on the > left (the grey-backgrounded all-caps with the ">>" at the right) > all intrude into the body text. They're all the same length: Just as an FYI, I see the same problem under Linux, using Firefox 1.0.7 and Konqueror 3.5. Galeon 2.0.0 renders it correctly. I am using a 1920x1200 screen, so if there is any hard pixel-based design in a website, I'm likely to see it garbled into a mess (though the regular 'old' python.org renders just fine on all the browsers I have installed). Kudos to those doing the work, I just hope these problems are ironed out before going live. Cheers, f From greg.kujawa at gmail.com Fri Jan 13 09:57:29 2006 From: greg.kujawa at gmail.com (gregarican) Date: 13 Jan 2006 06:57:29 -0800 Subject: PDA Implementations Message-ID: <1137164249.484345.228830@g43g2000cwa.googlegroups.com> I am in the process of creating an app that runs on various PDA platforms. Currently I have it running on ARM Linux (Sharp Zaurus) and am starting to port it over to ARM Windows Mobile (Dell Axim). Using Python has made the task particularly easier and (dare I say it?) kind of fun. What about porting it over to Palm OS (Palm Tungsten)? Is it worth it in your collective opinion long-term? Checking Python releases targeted for Palm OS I see most of these are a little long in the tooth. For example Pippy uses Python v1.5 I believe. All of the projects targeted for Palm OS are great and extend Python's usefulness for sure. But what about their functionality on newer Palm OS releases such as the Tungsten's? I am mainly looking for xmlrpc calls being passed to an external server using wif-fi and using a widget set. Figuring I am locked into Palm's own widget set. Is it worth it to go to all of this trouble if Palm OS appears to be losing market share and new Palm hardware devices are running Windows Mobile? From drevil_53711 at yahoo.com Mon Jan 9 14:46:50 2006 From: drevil_53711 at yahoo.com (Steve Young) Date: Mon, 9 Jan 2006 11:46:50 -0800 (PST) Subject: build_opener Message-ID: <20060109194650.90117.qmail@web36501.mail.mud.yahoo.com> Hello, I had a question about urllib2's build_opener() statement. I am trying to just get the html from any webpage as a string but I need everything on the page to be the same as what it'd be if I would browse to that page (and at the very least, all the href's). This is my code: url = 'http://news.yahoo.com/fc/world/iraq' req = Request(url) f = build_opener().open(req) page = f.read() f.close() return page so looking at the source of the page browsing to the page, one of the links has an href that looks like this: href = http://news.yahoo.com/s/ap/20051118/ap_on_re_mi_ea/iraq_051118153857;_ylt=AiPsFWWIyLLbGdlCQFLMn8NX6GMA;_ylu=X3oDMTBiMW04NW9mBHNlYwMlJVRPUCUl after running the code and looking at the returned page's same link, it looks like this: href = http://192.168.23.106/s/ap/20051118/ap_on_re_mi_ea/iraq_051118153857 it seems that everything after the semi-colon is missing after running the build_opener(). Is there a way that I can get the page as a string with all the links (href's) to not be missing anything? Thanks. -Steve --------------------------------- Yahoo! DSL Something to write home about. Just $16.99/mo. or less -------------- next part -------------- An HTML attachment was scrubbed... URL: From hancock at anansispaceworks.com Sun Jan 8 14:30:50 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 8 Jan 2006 13:30:50 -0600 Subject: Spelling mistakes! In-Reply-To: <17345.10408.127334.527071@montanaro.dyndns.org> References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> <7xr77ku8oz.fsf@ruckus.brouhaha.com> <17343.7834.618161.400185@montanaro.dyndns.org> <20060106234233.3b98d896@samwise.anansi> <17345.10408.127334.527071@montanaro.dyndns.org> Message-ID: <20060108133050.05131f23@samwise.anansi> On Sun, 8 Jan 2006 08:58:48 -0600 skip at pobox.com wrote: > Sybren> And what's up with using Google to check for spelling? I have a > Sybren> dictionary for that, works a lot better! > > A couple things: > > 1. It's generally faster than reaching for the > dictionary. But not faster than use a dict server! Why not just use (e.g.) kdict? That's what I do. It's got to be at least as accurate as Google, and much more likely to give me the right answer. > 2. The hit count for a word and its misspelling gives > me some measure of > how the rest of the online English-speaking world > thinks that word is spelled. This is useful for words that don't really exist. Or rather, that do exist, but are not documented. ;-) > 3. Some recent words like "podcast" aren't in the now > ancient dictionary > on my shelf. Other words have gained new meanings > since my dictionary was published. Same comment -- Google is good as a backup, but I'd much rather use a dictionary to look up words than a search engine. Wikipedia is another good resource for newer words, brand names, jargon, and slang. BTW, one of the most common programming spelling errors is "deprecate" versus "depreciate" -- I wonder how many people actually realize that both words exist, but have entirely different meanings? "deprecate" means "to be declared unworthy or no longer to be used by an authority" and is pronounced de-pre-KATE, while "depreciate" means "to go down in financial value" and is pronounced "de-PRE-she-ATE". An awful lot of people seem to think that "deprecate" is a misspelling of "depreciate" and then correct the spelling. But then, they must have a funny idea of what it means when a software feature is "deprecated". Maybe they think it's like the opposite of "appreciate" or something? ("We don't appreciate your code anymore"). ;-) I suppose some smart alec is going to argue that "it goes down in value because an authority declared it unworthy". Would be about par for the course. ;-) -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From petr at tpc.cz Tue Jan 31 19:22:53 2006 From: petr at tpc.cz (Petr Jakes) Date: 31 Jan 2006 16:22:53 -0800 Subject: how to parse structured text file? Message-ID: <1138753373.716051.45440@o13g2000cwo.googlegroups.com> I have a file which contains data in the format shown in the sample bellow. How can I parse it to get following: (14,trigger,guard,do_action,15) Thanks a lot for your postings Petr Jakes type: 4 bgrColor: 255 255 255 fgrColor: 0 0 0 objId: 16 Num.Pts: 2 177 104 350 134 objStartId: 14 objEndId: 15 eventName: trigger eventCond: guard eventAction: do_action From hancock at anansispaceworks.com Fri Jan 27 19:11:59 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 27 Jan 2006 18:11:59 -0600 Subject: beta.python.org content In-Reply-To: <43da9352$1@nntp0.pdx.net> References: <43da9352$1@nntp0.pdx.net> Message-ID: <20060127181159.5c9486be@samwise.anansi> On Fri, 27 Jan 2006 13:44:19 -0800 Scott David Daniels wrote: > Paragraph 3 in "Why Python": > Some people uppose because Python ... > I'd prefer the word "suppose." > and later in that paragraph, I'd change: > ... extensions that provide compact numerical > solutions > to: > ... extensions that provide compact high-speed > numerical solutions And while we're at it, let's say "Python is a language for programming high-speed, digital, electronic computers. Do you have any experience with high-speed, digital, electronic computers?" :-D For those who are too young, or weren't film students, the answer is "Yes, my aunt has one". Ironically, this is now funny for exactly the opposite reason from the way it was intended! -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From steve at holdenweb.com Thu Jan 19 06:49:42 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Jan 2006 11:49:42 +0000 Subject: Decimal vs float In-Reply-To: <1137667011.140658.100360@g43g2000cwa.googlegroups.com> References: <1137667011.140658.100360@g43g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > I wonder why this expression works: > > >>>>decimal.Decimal("5.5")**1024 > > Decimal("1.353299876254915295189966576E+758") > > but this one causes an error > > 5.5**1024 > > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: (34, 'Result too large') > Because the Decimal type can represent a larger range of values than the float type. Your first expression give a Decimal result, your second attempts to give a float result. > Another quirk is the follwoing: > > >>>>decimal.Decimal(5.5) > > Traceback (most recent call last): > ... > TypeError: Cannot convert float to Decimal. First convert the float to > a string > > If Mr. interpreter is as slick as he is why doesn't he convert the > float by himself? This is at most a warning caused by possible rounding > errors of float. > Indeed, as the documentation says: """This serves as an explicit reminder of the details of the conversion (including representation error)""". Otherwise you would get numpties using constructions like Decimal(0.1) and then asking why the result was the same as Decimal("0.10000000000000001") (or something similar). Who needs it? Certainly not Mr. interpreter, or his c.l.py friends. > Instead of dealing with awkward wrappers, I wonder if literals > currently interpreted as floats could not be interpreted as Decimal > objects in future? > That would be a very large change in the behaviour of the interpreter, and unfortunately it doesn't take account of the need in decimal to specify the context in which a calculation takes place.You need to be able to specify precision, rounding and a number of other values to make your computations completely specified. What would you use as the default context? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From Lord.Laraby at gmail.com Sat Jan 7 01:03:06 2006 From: Lord.Laraby at gmail.com (LordLaraby) Date: 6 Jan 2006 22:03:06 -0800 Subject: How to Retrieve Data from an HTTPS://URL In-Reply-To: <1136491632.149347.29430@o13g2000cwo.googlegroups.com> References: <1136491632.149347.29430@o13g2000cwo.googlegroups.com> Message-ID: <1136613786.601316.258240@g44g2000cwa.googlegroups.com> You might be using ActiveState python on Windows? If so, you most likely do not have the SSL layer that's required to process HTTPS protocol queries. You should install 'standard' Python from python.org to get the SSL handling functionality. I understand that ActiveState can not distribute the SSL code, for national security reasons. :-) LL From enoch at gmx.net Fri Jan 6 12:39:55 2006 From: enoch at gmx.net (Ernst Noch) Date: Fri, 06 Jan 2006 18:39:55 +0100 Subject: Is 'everything' a refrence or isn't it? In-Reply-To: <86mzi9qod0.fsf@bhuda.mired.org> References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <8664ozd1bm.fsf@bhuda.mired.org> <43BC806A.1040201@REMOVEMEcyber.com.au> <8664oyrutb.fsf@bhuda.mired.org> <426qlvF1glideU1@individual.net> <86mzi9qod0.fsf@bhuda.mired.org> Message-ID: <427obbF1hpc5nU1@individual.net> Mike Meyer wrote: > Ernst Noch writes: > >>Maybe next time showing something like the following trivial snippet >>might help demonstrate that the core of the matter doesn't is not the >>way python treats parameters? > > > Did you insert an extra "doesn't" in that? If so, then I agree about > what isn't the core of the matter. Uhm, yes. Seems the whole message was written too hastily. > > On the other hand, the snippet doesn't help without an > explanation. Especially with misleading comments. Absolutely, it was mainly meant as an example to demonstrate in practice that the way python passes parameters has nothing to do with what happens. > > >>>>>def func(param, what): >> >> if what: >> param['foo'] = 'changed' >> else: >> temp = param['foo'] # temp is _not_ a reference! > > > Except temp *is* a reference. What it's not is a reference to > param['foo']. Instead, it's a reference to the same object that > param['foo'] is a reference to. > Oh dear, yes. I inserted that comment as an afterthought. From roger at deadspam.com Thu Jan 26 10:25:54 2006 From: roger at deadspam.com (Roger L. Cauvin) Date: Thu, 26 Jan 2006 15:25:54 GMT Subject: Match First Sequence in Regular Expression? References: <1h9reyq.z7u4ziv8itblN%aleax@mail.comcast.net> Message-ID: <6S5Cf.3925$1%5.2732@tornado.texas.rr.com> "Alex Martelli" wrote in message news:1h9reyq.z7u4ziv8itblN%aleax at mail.comcast.net... > Tim Chase wrote: > ... >> I'm not quite sure what your intent here is, as the >> resulting find would obviously be "aaa", of length 3. > > But that would also match 'aaaa'; I think he wants negative loobehind > and lookahead assertions around the 'aaa' part. But then there's the > spec about matching only if the sequence is the first occurrence of > 'a's, so maybe he wants '$[^a]*' instead of the lookbehind (and maybe > parentheses around the 'aaa' to somehow 'match' is specially?). > > It's definitely not very clear what exactly the intent is, no... Sorry for the confusion. The correct pattern should reject all strings except those in which the first sequence of the letter 'a' that is followed by the letter 'b' has a length of exactly three. Hope that's clearer . . . . -- Roger L. Cauvin nospam_roger at cauvin.org (omit the "nospam_" part) Cauvin, Inc. Product Management / Market Research http://www.cauvin-inc.com From void at void.com Fri Jan 20 15:56:19 2006 From: void at void.com (Matthias Kaeppler) Date: Fri, 20 Jan 2006 21:56:19 +0100 Subject: PyXML: SAX vs. DOM In-Reply-To: References: Message-ID: Steven Bethard wrote: > I don't have an answer to your real question, but if you're not > committed to a particular XML package yet, you might consider ElementTree: > http://effbot.org/zone/element-index.htm > > The API is much simpler, and the package has a much more sane > organization. ;) Plus, it will be part of the Python standard library > in Python 2.5. That sounds great, thanks. Regards, Matthias From shejo284 at gmail.com Thu Jan 12 03:39:27 2006 From: shejo284 at gmail.com (Sheldon) Date: 12 Jan 2006 00:39:27 -0800 Subject: Reading from input file. In-Reply-To: <1137008850.155816.88960@g49g2000cwa.googlegroups.com> References: <1136939500.529772.49980@z14g2000cwz.googlegroups.com> <1136976935.456780.12790@g44g2000cwa.googlegroups.com> <1137008850.155816.88960@g49g2000cwa.googlegroups.com> Message-ID: <1137055167.597352.233030@f14g2000cwb.googlegroups.com> Hi, after you have read the file then split it like this: file = open('inputfile.txt', 'r').read() import string file = string.split(file,'\n') now if you print file[0] you should only get the first line. Be careful and examine the file for non-continuous sections where a line is empty. That is to say where file[x] = ' '. You should remove these lines from the txt files before you read it with python. It maybe so that python reads the entire file, empty spaces and all, and then you have to remove them after the split with a WHERE statement. This is a much easier way so lets hope that this is so. I hope this was more clear and helpful this time around. Cheers Sheldon From blair.houghton at gmail.com Sun Jan 29 23:01:58 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 29 Jan 2006 20:01:58 -0800 Subject: webbrowser module + urls ending in .py = a security hole? In-Reply-To: <1138593557.824516.116400@g14g2000cwa.googlegroups.com> References: <1138593557.824516.116400@g14g2000cwa.googlegroups.com> Message-ID: <1138593718.079667.241820@g44g2000cwa.googlegroups.com> Oh, uh, Python version 2.4.2, in case you're wondering. --Blair From twic at urchin.earth.li Thu Jan 12 18:10:24 2006 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 12 Jan 2006 23:10:24 +0000 Subject: how do "real" python programmers work? In-Reply-To: <1137097250.592204.129310@g43g2000cwa.googlegroups.com> References: <1137097250.592204.129310@g43g2000cwa.googlegroups.com> Message-ID: On Thu, 12 Jan 2006, bblais wrote: > In Matlab, I do much the same thing, except there is no compile phase. I > have the editor on one window, the Matlab interactive shell in the > other. I often make a bunch of small scripts for exploration of a > problem, before writing any larger apps. I go back and forth editing > the current file, and then running it directly (Matlab looks at the time > stamp, and automagically reloads the script when I modify it). I wouldn't describe myself as an experienced programmer, but this is definitely how i work - editor plus interactive interpreter, using import/reload to bring in and play with bits of of code. Towards the end of coding a program, when i'm done with the inner functions and am working on the main function, which does stuff like command line parsing, setting up input and output, etc, i'll often leave the interpreter and work from the OS shell, since that's the proper environment for a whole program. Often, i'll actually have more than one shell open - generally three: one with an interpreter without my code loaded, for doing general exploratory programming, testing code fragments, doing sums, etc; one with an interpreter with my code loaded, for testing individual components of the code, and one at the OS shell, for doing whole-program tests, firing up editors, general shell work, etc. Another trick is to write lightweight tests as functions in the interpreter-with-code-loaded that reload my module and then do something with it. For example, for testing my (entirely fictional) video compressor, i might write: def testcompressor(): reload(vidzip) seq = vidzip.ImageSequence((640, 480)) for i in xrange(200): frameName = "testmovie.%02i.png" % i frame = Image.open(frameName) seq.append(frame) codec = vidzip.Compressor(vidzip.DIRAC, 9) codec.compress(seq, file("testmovie.bbc", "w")) Then, after editing and saving my code, i can just enter "testcompressor()" (or, in most cases, hit up-arrow and return) to reload and test. You can obviously extend this a bit to make the test routine take parameters which control the nature of the test, so you can easily test a range of things, and you can have multiple different test on the go at once. tom -- Only men's minds could have mapped into abstraction such a territory From gsakkis at rutgers.edu Wed Jan 18 18:34:06 2006 From: gsakkis at rutgers.edu (George Sakkis) Date: 18 Jan 2006 15:34:06 -0800 Subject: A simpler more pythonic approach to adding in References: <1137623909.797313.143860@g43g2000cwa.googlegroups.com> Message-ID: <1137627246.913644.14510@g14g2000cwa.googlegroups.com> A cleaner, though not shorter, rewriting could be: from itertools import chain def ancestors(path): while True: yield path parent = os.path.dirname(path) if parent == path: break path = parent for dir in chain([os.environ['HOME']], ancestors(os.path.realpath('.'))): modules_dir = os.path.join(dir, 'modules') if os.path.exists(modules_dir): sys.path.insert(0,modules_dir) from foo import foo break HTH, George From tuvas21 at gmail.com Mon Jan 23 14:48:36 2006 From: tuvas21 at gmail.com (Tuvas) Date: 23 Jan 2006 11:48:36 -0800 Subject: Oddities of Tkinter In-Reply-To: References: <1138044517.365724.206250@g47g2000cwa.googlegroups.com> Message-ID: <1138045716.122978.279400@g44g2000cwa.googlegroups.com> Nope, that's the oddest thing about it all... Perhaps the statement is called twice or something along those lines, but there again, I can't see how it would be... From jschull at gmail.com Tue Jan 24 10:57:39 2006 From: jschull at gmail.com (jschull at gmail.com) Date: 24 Jan 2006 07:57:39 -0800 Subject: Loading a Python collection from an text-file References: Message-ID: <1138118259.128395.76590@g14g2000cwa.googlegroups.com> another approach (probably frowned upon, but it has worked for me) is to use python syntax (a dictionary, say, or a list) and just import (or reload) the file From claird at lairds.us Sat Jan 7 21:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 08 Jan 2006 02:08:02 GMT Subject: Groupkit and python References: <1136224937.370021.260380@g43g2000cwa.googlegroups.com> Message-ID: In article <1136224937.370021.260380 at g43g2000cwa.googlegroups.com>, jose.r.pacheco at gmail.com wrote: >Hi, >I've built an app using this great software called groupkit >(http://www.groupkit.org/) based on tcl/tk language, now I'd like to >test python possibilities for groupware. Anyone knows about this, I >have made a google search; crossing groupkit and python, but I haven?t >found any project except this one called twisted-python. Do you >believe twisted-python could be a substitute for groupkit?. . . . As I *think* it hasn't appeared in comp.lang.python, I reproduce here remarks by the Groupkit author in (no longer) private e-mail: Twisted offers more of a low-level equivalent to the event-driven IO that comes standard in Tcl, plus many higher level network protocols on top of that. It doesn't offer a focus on groupware application level constructs like session management, awareness, etc., nor am I aware of anything in Python that tries to tackle this niche. If someone were wanting to move GroupKit-like features to Python, twisted would be the best framework to build upon, but as is, it's missing things you'd probably like from GroupKit. From steve at REMOVETHIScyber.com.au Fri Jan 27 20:27:41 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 28 Jan 2006 12:27:41 +1100 Subject: indentation messing up my tuple? References: <1138409154.334017.176760@g49g2000cwa.googlegroups.com> Message-ID: On Fri, 27 Jan 2006 16:45:54 -0800, localpricemaps wrote: > here is my code: > > for row in bs('div', {'style' : 'both'}): What is bs? Is it a secret? > data=[] > > for incident in bs('h3', {'class' : 'name'}): > foodlist = [] > for oText in incident.fetchText( oRE): > foodlist.append(oText.strip() + "','") > food = ''.join(foodlist) Put a "print food" statement at the end of this line to see what you have. > for incident in bs('span', {'class' : 'drink'}): > drink = incident.findNextSibling('a', {'class': 'nojs'}) drinklist = > [] > for oText in drink.fetchText( oRE): > drinklist.append(oText.strip() + "','") > drink = ''.join(drinklist) Put a "print drink" statement at the end of this line to see what you have. > tuple = (food + drink + "\n") > data.append(tuple) This seems awfully pointless. At the beginning of every loop, you set data to the empty list. After a while you append one tuple to it. But you don't use data again, and it just gets reset to the empty list at the beginning of the next loop. What is the purpose of data? > f = open("test.txt", 'a') > f.write ( ''.join( tuple ) ) You are re-opening the file every single time around the loop. You should either do this: f = open("test.txt", "w") for row in bs(...): # processing f.write(one line only) f.close() or do this: data = [] for row in bs(...): # processing # accumulate everything you want in data f.writelines(data) f.close() -- Steven. From tim at pollenation.net Sun Jan 15 17:19:37 2006 From: tim at pollenation.net (Tim Parkin) Date: Sun, 15 Jan 2006 22:19:37 +0000 Subject: New Python.org website ? In-Reply-To: <1137195685.086330.317130@z14g2000cwz.googlegroups.com> References: <1137165407.149259.306470@o13g2000cwo.googlegroups.com> <1137195685.086330.317130@z14g2000cwz.googlegroups.com> Message-ID: <43CACA79.703@pollenation.net> sjdevnull at yahoo.com wrote: > JW wrote: > >>On Fri, 13 Jan 2006 11:00:05 -0600, Tim Chase wrote: >> >> >>>http://tim.thechases.com/pythonbeta/pythonbeta.html >>> >> >>Very strange. With FF 1.0.7, I can just get the buttons to violate the >>next column if I "View>Page Style>Large Text", but I wouldn't have noticed >>it unless Tim had pointed it out. Tim's gifs are much worse than what >>I see. WIth ""View>Page Style>Basic Page Style", it looks really good. > > > Mine looks like Tim's gifs, with "Basic Page Style". > Hi, I've got an old copy of the html and tried to fix the general problem. It's currently on another website http://pyyaml.org/downloads/masterhtml/ Feedback appreciated (it's just the left hand nav width I'm concerned about, all the other html and some styles are probably old). I've tried this with 'min font size' adjustments and it doesn't seem to break. If I don't get any bad feedback I'll roll the changes out. Many thanks Tim From casevh at comcast.net Fri Jan 27 14:19:44 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 27 Jan 2006 11:19:44 -0800 Subject: writing large files quickly In-Reply-To: References: Message-ID: <1138389584.746734.324540@f14g2000cwb.googlegroups.com> rbt wrote: > I've been doing some file system benchmarking. In the process, I need to > create a large file to copy around to various drives. I'm creating the > file like this: > > fd = file('large_file.bin', 'wb') > for x in xrange(409600000): > fd.write('0') > fd.close() > > This takes a few minutes to do. How can I speed up the process? > > Thanks! Untested, but this should be faster. block = '0' * 409600 fd = file('large_file.bin', 'wb') for x in range(1000): fd.write('0') fd.close() From jsfrank.chen at msa.hinet.net Tue Jan 10 22:49:00 2006 From: jsfrank.chen at msa.hinet.net (Thomas Moore) Date: Wed, 11 Jan 2006 11:49:00 +0800 Subject: A bug for unicode strings in Python 2.4? Message-ID: Hi: Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> u=u'\u9019\u662f\u4e2d\u6587\u5b57\u4e32' >>> u.split() [u'\u9019\u662f\u4e2d\u6587\u5b57\u4e32'] >>> I think u should get split. --Frank From noahspurrier at gmail.com Mon Jan 30 21:32:40 2006 From: noahspurrier at gmail.com (Noah) Date: 30 Jan 2006 18:32:40 -0800 Subject: Can a test case tell if VERBOSE is used in pyunit test? Message-ID: <1138674760.407449.189630@g14g2000cwa.googlegroups.com> Is there a way for a test case method in a class derived from unittest.TestCase to tell if the harness was started with the verbose option? I would like my test cases to print out a little extra information if the tests were run with -v or -vv. yours, Noah From rupole at hotmail.com Thu Jan 26 20:17:43 2006 From: rupole at hotmail.com (Roger Upole) Date: Thu, 26 Jan 2006 20:17:43 -0500 Subject: ODBC References: <1138312667.909488.130680@o13g2000cwo.googlegroups.com> Message-ID: <1138324774_399@sp6iad.superfeed.net> >From the syntax, this appears to be the odbc module included with the Pywin32 package. http://sourceforge.net/projects/pywin32/ You probably have it installed with the 2.1.1 version, but not 2.4. hth Roger wrote in message news:1138312667.909488.130680 at o13g2000cwo.googlegroups.com... >I would like to connect to an Oracle database. In python version 2.1 I > used the following code and it worked fine. When I run the code in > version 2.4 it says that the odbc moduled does not exist. How do you > connect to an Oracle database in v2.4? > > oradb=odbc.odbc('oracle/scott/tiger') > stmt='select project_id from s_projects' > cur=oradb.cursor() > cur.execute(stmt) > for rec in cur.fetchall(): > print rec[0] > cur.close() > > Thanks > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From alanmk at hotmail.com Fri Jan 13 16:25:44 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 13 Jan 2006 21:25:44 +0000 Subject: jython base64.urlsafe_b64xxx In-Reply-To: <1137073394.927100.207920@g44g2000cwa.googlegroups.com> References: <1137073394.927100.207920@g44g2000cwa.googlegroups.com> Message-ID: py wrote: > anyone know how to do perform the equivalent base64.urlsafe_b64encode > and base64.urlsafe_b64decode functions that Python has but in jython? > Jython comes with a base64 module but it does not have the urlsafe > functions. Tried copying the pythhon base64.py to replace the Jython > one, and although it did perform the encode/decode it didnt seem to be > correctly decoded. You're probably better off using a java library for the task. There are plenty to choose from, but most embedded as utility classes in bigger packages. Here's a public domain one for example http://dev.i2p.net/cgi-bin/cvsweb.cgi/i2p/core/java/src/net/i2p/data/Base64.java?f=H With javadoc at http://dev.i2p.net/javadoc/net/i2p/data/Base64.html Seems to do what you want. HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From wedig at darwin.epbi.cwru.edu Fri Jan 20 09:38:09 2006 From: wedig at darwin.epbi.cwru.edu (Geoff Wedig) Date: Fri, 20 Jan 2006 09:38:09 -0500 Subject: Using freeze or other application to create linkable dynamic libraries for c++ applications? Message-ID: <43D0F5D1.8000903@darwin.cwru.edu> Is it possible to create a DLL (pr on unix a .a, .so, etc) from python code, perhaps using freeze or some other application? Freeze seems to assume that it's creating the main program body, but I don't really understand it well enough to say. If it doesn't work, is there another application that can be used to do this? From xavier.morel at masklinn.net Tue Jan 17 07:10:49 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Tue, 17 Jan 2006 13:10:49 +0100 Subject: Arithmetic sequences in Python In-Reply-To: <7xr777zvc5.fsf@ruckus.brouhaha.com> References: <1137402099.920352.275350@o13g2000cwo.googlegroups.com> <7xmzhw1lsw.fsf@ruckus.brouhaha.com> <7xr777zvc5.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I don't think this is a valid objection. Python is already full of > syntactic sugar like indentation-based block structure, infix > operators, statements with keyword-dependent syntax, etc. It's that > very sugar that attracts programmers to Python away from comparatively > sugarless languages like Scheme. Indeed, Python is considered by many > to be a sweet language to program in, and they mean that in a nice > way. > > If you want, you can think of it as "flavor" rather than "sugar". We > aren't after syntactic minimalism or we'd be using Scheme. The > criterion for adding something like this to Python should be whether > makes the language taste better or not. I don't know, most of the syntactic sugar I see in Python brings something to the language, or trivialize the generation of structures and constructs that may be complex or awkward without it, it has a natural, honey-ish sweetness full of flavor, it does not taste like some cancer-spawning artificial sweetener ;-) From python at rcn.com Sun Jan 29 01:02:45 2006 From: python at rcn.com (Raymond Hettinger) Date: 28 Jan 2006 22:02:45 -0800 Subject: Using bytecode, not code objects References: Message-ID: <1138514565.112950.212310@o13g2000cwo.googlegroups.com> [Fabiano Sidler] > I'm looking for a way to compile python source to bytecode instead of > code-objects. Is there a possibility to do that? The reason is: I want > to store pure bytecode with no additional data. > > The second question is, therefore: How can I get the correct values > for a given bytecode, such as the stacksize and flags attributes of > the correspondent code object? > > No, I don't want to extract all of these things out of a code object. Why not? The code object gives you all of these values directly. But if you want to make your life unnecessarily hard, you can hack the compiler module just upstream from the creation of the code object -- alter the newCodeObject() method in pyassem.py. It's a pointless exercise, but maybe you'll have fun doing it or perhaps learn not to avoid obvious, direct solutions to the problem at hand. Raymond From steve at holdenweb.com Wed Jan 11 18:06:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Jan 2006 23:06:26 +0000 Subject: How can I determine an HTTPMessage ? In-Reply-To: References: <1137000659.373574.286550@o13g2000cwo.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > > >>>Can you tell me what to look for in an HTTPMessage that is an error? I >>>have looked at the header objects and I cannot determine an error >>>message. >> >>I was thinking of a number between one and a thousand, and I forgot it. >>Could someone please remind me what it was? > > > 204. > Thanks. This is *such* a helpful group. I'll write it down this time. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From Ido.Yehieli at gmail.com Sun Jan 29 06:54:40 2006 From: Ido.Yehieli at gmail.com (Ido Yehieli) Date: 29 Jan 2006 03:54:40 -0800 Subject: SLUT distibution mangled? In-Reply-To: References: <1138457494.565368.62690@g44g2000cwa.googlegroups.com> <1138457723.888258.167930@z14g2000cwz.googlegroups.com> <1138487092.992012.217660@f14g2000cwb.googlegroups.com> Message-ID: <1138535680.673177.55580@f14g2000cwb.googlegroups.com> ok, Thanks Paul! From fredrik at pythonware.com Thu Jan 19 13:21:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Jan 2006 19:21:58 +0100 Subject: add pexpect to the standard library, standard "install" mechanism. References: <1137693045.144942.89730@g49g2000cwa.googlegroups.com> Message-ID: "funkyj" wrote: > I love pexpect because it means I may never have to use expect again (I > don't do any heavy expect lifting -- I just need simple tty control)! > > As a python advocate I find it embarassing how difficult it is do the > following in python (without pexpect): > > - logon to a remote system using ssh > - do an 'ls' and exit the remote shell > - print the output from the remote shell session. > > pexpect, of course, makes this childs play (see the pexpect sshls.py > example for one way to do this). > > I'm surprised that, as useful as pexpect is, it has not been included > in the standard python library. How can we get this wonderful package > in the standard library? > > TANGENT: it would be nice if python included a standard "tarfile > install" program to make installing 3rd party packages like pexpect > easier. > > bash $ pinstall_tarfile foo-pkg.tgz > > This install program would > + look at your sys.path for a suitable install directory > + check for appropriate directory permissions > + check whether the tarfile extracts to the CWD or a subdir > (the rest of the script is adjusted accordingly -- assume subdir > behavior). > + tell the user where you plan to install the package. confirm > that this is OK. > + extract the tarfile and create/update the foo.pth file. > > Perhaps such an install script is already in the standard python > library and I just haven't stumbled across it? any special reason why pexpect cannot ship with a standard distutils setup.py file (or even egg support) ? From petr at tpc.cz Tue Jan 31 19:32:47 2006 From: petr at tpc.cz (Petr Jakes) Date: 31 Jan 2006 16:32:47 -0800 Subject: how to parse structured text file? In-Reply-To: <1138753373.716051.45440@o13g2000cwo.googlegroups.com> References: <1138753373.716051.45440@o13g2000cwo.googlegroups.com> Message-ID: <1138753967.173560.167470@g14g2000cwa.googlegroups.com> Sorry I was not precise enough in my description. In the file, there is of course more sections starting with the keyword type: I would like to only analyze sections which start with the sequence: type: 4 Petr jakes From Ido.Yehieli at gmail.com Tue Jan 24 08:59:20 2006 From: Ido.Yehieli at gmail.com (Ido Yehieli) Date: 24 Jan 2006 05:59:20 -0800 Subject: Using non-ascii symbols In-Reply-To: References: Message-ID: <1138111160.327037.127210@g43g2000cwa.googlegroups.com> >> Is this idea absurd or will one day our children think >> that restricting to 7-bit ascii was absurd? Both... this idea will only become none-absurd when unicode will become as prevalent as ascii, i.e. unicode keyboards, universal support under almost every application, and so on. Even if you can easly type it on your macintosh, good luck using it while using said macintosh to ssh or telnet to a remote server and trying to type unicode... From duncan.booth at invalid.invalid Wed Jan 11 09:19:39 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jan 2006 14:19:39 GMT Subject: try: except : References: <7xy81okzej.fsf@ruckus.brouhaha.com> <7x7j988ahi.fsf@ruckus.brouhaha.com> Message-ID: Tom Anderson wrote: >> class NeverRaised(Exception): >> def __init__(self, *args): >> raise RuntimeError('NeverRaised should never be raised') > > Briliant! Although i'd be tempted to define an > UnraisableExceptionError to signal what's happened. Or ... > > class ImpossibleException(Exception): > def __init__(self, *args): > raise ImpossibleException, args > > Although crashing the interpreter is probably overkill. Crashng the interpreter would be, but what you just wrote is simply a more obscure way of raising RuntimeError :-) >>> class ImpossibleException(Exception): ... def __init__(self, *args): ... raise ImpossibleException, args ... >>> raise ImpossibleException Traceback (most recent call last): File "", line 3, in __init__ RuntimeError: maximum recursion depth exceeded From mwm at mired.org Mon Jan 2 06:51:22 2006 From: mwm at mired.org (Mike Meyer) Date: Mon, 02 Jan 2006 06:51:22 -0500 Subject: Application architecture (long post - sorry) References: <1136057979.197888.126890@g49g2000cwa.googlegroups.com> <86lky180ce.fsf@bhuda.mired.org> <1136122915.782386.189860@g14g2000cwa.googlegroups.com> Message-ID: <86bqyu7sqt.fsf@bhuda.mired.org> limeydrink at hotmail.com writes: > In response to Mike's post... > > I know exactly where you're coming from and you are right a web based > solution is the simplest and would be the fastest to develop and > rollout etc. but.. > > The cost is in the data, in the uk you get charged for the amount of > data you send/receive by GPRS and this data you are paying for would > ideally be useful data and not the HTML to present it. I'll take your word for it that you don't have GPRS providers in the UK that have an all-you-can eat plan. They all do in the US. However, HTML doesn't *have* to be the bloated crap that seems to be produced by most designers - more more accurately, by the GUI tools they use to produce HTML. Used properly, it can be a very sparse encoding system. Not as good something designed for the data at hand, and not as good a binary format, but not awful, either. Further, you may be able to save bandwidth by putting some of the HTML on the mobile device. For example, the form your field engineers fill in to note that a job has been done could be kept on the PDA (assuming it's static), and just opened in the browser, filled in, and submitted. Palm did this with their PQA technology - a PQA was a set of HTML files that were "compiled" into a representation their browser understood. Finally, if the data bandwidth is really a serious problem, you might want to look into a solution at a different level. For instance, if you're using a VPN to get to your internal network, some VPN technologies include facilities to compress the data traveling across the network. That will reduce the difference in bandwidth usage between the various encoding formats you might consider. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mwm at mired.org Sat Jan 14 22:44:55 2006 From: mwm at mired.org (Mike Meyer) Date: Sat, 14 Jan 2006 22:44:55 -0500 Subject: Why keep identity-based equality comparison? References: <1136846444.954839.58960@g47g2000cwa.googlegroups.com> <1136931692.016693.113860@f14g2000cwb.googlegroups.com> <86mzi3fw2b.fsf@bhuda.mired.org> <86hd86wj1r.fsf@bhuda.mired.org> Message-ID: <86acdyupc8.fsf@bhuda.mired.org> Noam Raphael writes: > Mike Meyer wrote: >> Noam Raphael writes: >>>>>Also note that using the current behaviour, you can't easily >>>>>treat objects that do define a meaningful value comparison, by >>>>>identity. >>>>Yes you can. Just use the "is" operator. >>>Sorry, I wasn't clear enough. In "treating" I meant how containers >>>treat the objects they contain. For example, you can't easily map a >>>value to a specific instance of a list - dict only lets you map a >>>value to a specific *value* of a list. >> Wrong. All you have to do is create a list type that uses identity >> instead of value for equality testing. This is easier than mapping an >> exception to false. > You're suggesting a workaround, which requires me to subclass > everything that I want to lookup by identity (and don't think it's > simple - I will have to wrap a lot of methods that return a list to > return a list with a modified == operator). No, I'm suggesting a general solution that works for *every* case where you want something other than the standard equality case. > I'm suggesting the use of another container class: iddict instead of > dict. That's all. You're suggesting adding a new builtin type to the language that deals with one special case. Is this special case really that common? I don't recall seeing anyone else ask for it in the last 10 years or so. > I don't think that mapping an exception to false is so hard (certainly > simpler than subclassing a list in that way), and the average user > won't have to do it, anyway - it's the list implementation that will > do it. I disagree with both your assessments. Subclassing is trivial. And every user who wants to compare elements in a container that might include heterogenous types has to deal with this issue. That's more than just lists, even if you only pay atttention to builtin types. Nuts - you have to deal with it when you're adding elements to a dictionary. >>>Another example - you can't >>>search for a specific list object in another list. >> Your proposed == behavior doesn't change that at all. > It does - *use idlist*. You're mixing two proposals into the same thread. You'll forgive me for referring to the original proposal. >>>>I will point out why your example usages aren't really usefull if >>>>you'll repeat your post with newlines. >>> >>>Here they are: >>>* Things like "Decimal(3.0) == 3.0" will make more sense (raise an >>>exception which explains that decimals should not be compared to >>>floats, instead of returning False). >> While I agree that Decimal(3.0) == 3.0 returning false doesn't make >> sense, having it raise an exception doesn't make any more sense. This >> should be fixed, but changing == doesn't fix it. > No, it can't be fixed your way. It was decided on purpose that Decimal > shouldn't be comparable to float, to prevent precision errors. I'm > saying that raising an exception will make it clearer. So how come I can compare decimals to floats? >>> type(d) >>> d < 2.0 True >>> d > 0.0 False Are you proposing we should break this, which currently functions correctly? You're correct that this can't be fixed by "fixing" decimal alone. It requires more work than that. It may not be possible to fix this properly before Py3K. But your proposal can't be done until then anyway. I've already started the process of proposing a proper fix. >>>* You won't be able to use objects as keys, expecting them to be >>>compared by value, and causing a bug when they don't. I recently wrote >>>a sort-of OCR program, which contains a mapping from a numarray array >>>of bits to a character (the array is the pixel-image of the char). >>>Everything seemed to work, but the program didn't recognize any >>>characters. I discovered that the reason was that arrays are hashed >>>according to their identity, which is a thing I had to guess. If >>>default == operator were not defined, I would simply get a TypeError >>>immediately. >> This isn't a use case. You don't get correct code with either version >> of '=='. While there is some merit to doing things that make errors >> easier to find, Python in general rejects the idea of adding >> boilerplate to do so. Your proposal would generate lots of boilerplate >> for many practical situations. > I would say that there's a lot of merit to doing things that make > errors easier to find. That's what exceptions are for. Exceptions are for finding *programming errors*? That's a rather unusual view of exceptions. > Please say what those practical situations are - that what I want. > (I understand. You think that added containers and a try...except fro > time to time aren't worth it. I think they are. Do you have any other > practical situations?) That try...except is the boilerplate I'm talking about. > You are right that I'm suggesting a try...except when testing if a > list contains an object, but a case when you have a list with floats > and Decimals, and you rely on "Decimal("3.0") in list1" to find only > Decimals seems to me a little bit far-fetched. If you have another > example, please say it. But you're suggesting changing *far more* than just decimals, and have made multiple suggestions. Exactly what are you looking for an example of? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From scott.daniels at acm.org Sun Jan 29 19:44:27 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 29 Jan 2006 16:44:27 -0800 Subject: Help saving output onto a text file In-Reply-To: <1138578429.949295.251670@g43g2000cwa.googlegroups.com> References: <1138578429.949295.251670@g43g2000cwa.googlegroups.com> Message-ID: <43dd6085$1@nntp0.pdx.net> continium at gmail.com wrote: > If I have a simple program that for example calculates > the squares of 2 to 100 times, how can I write the resulting output > onto a separate text file? > > I know about the open() function and I can write strings and such in > text files but I'm not able to write the output of my programs. Simplest way: results = open('myname.txt', 'w') print >>results, 'This goes out.' print >>results, 'Similarly, this is the next line.' results.close() Slightly more obscure, but if your program is already printing: import sys former, sys.stdout = sys.stdout, open('myname.txt', 'w') results, sys.stdout = sys.stdout, former results.close() Really the closes (and swap back in the change-stdio case) should be done in a "finally clause of a try: ... finally: ... block, but that may not be where you are now. So I'd really use (for myself): Explicit file prints: results = open('myname.txt', 'w') try: print >>results, 'This goes out.' print >>results, 'Similarly, this is the next line.' # You can call functions to print, but they need to get # results and use the same form as above. # If you write your code using print >>var, ... # you can set var to None to go to the "normal" output. finally: results.close() Captured "standard" output: import sys former, sys.stdout = sys.stdout, open('myname.txt', 'w') try: print 'This goes out.' print 'Similarly, this is the next line.' # Even if you call a function that prints here, # its output is captured to your file finally: results, sys.stdout = sys.stdout, former results.close() --Scott David Daniels scott.daniels at acm.org From lycka at carmen.se Thu Jan 19 09:25:22 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 19 Jan 2006 15:25:22 +0100 Subject: PyCon Vs. Europython In-Reply-To: <1137627135.819692.38900@z14g2000cwz.googlegroups.com> References: <1137627135.819692.38900@z14g2000cwz.googlegroups.com> Message-ID: Simon Burton wrote: > My employer has given me the choice to go to either Pycon or Europython > this year, > and I need some help deciding which would be more useful (for me, my > company, and python itself). > > I am mainly interested in scientific/engineering applications of > python; As far as I understand, the content of this years EuroPython is far from decided. I haven't seen any call for papers yet. You are obviously taking a risk if you opt for EPC even if you like the PyCon program. On the other hand, EPC 2006 will take place at CERN, which might be interesting for someone with an interest in science, so I suspect that it will attract more scientists than previous conferences. From ejensen at visi.com Sun Jan 1 15:53:12 2006 From: ejensen at visi.com (Ed Jensen) Date: Sun, 01 Jan 2006 20:53:12 -0000 Subject: Python article in Free Software Magazine References: Message-ID: <11rgg9o8rbchcd9@corp.supernews.com> Steven D'Aprano wrote: > I don't want to nit-pick all my way through the article, which > is very decent and is worth reading, but I will say one more thing: you > describe Python as "an expressive, interpreted language". Python is no > more interpreted than Java. Like Java, it is compiled into byte-code which > is then executed by a virtual machine. It has a separate compilation and > execution step. The most-used desktop/server JVM, the Sun JVM, takes things one step further and compiles often-executed bytecode into native code. It can then execute native code. AFAIK, the most-used desktop/server Python VM doesn't do that. From steve at holdenweb.com Sun Jan 15 11:41:35 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Jan 2006 16:41:35 +0000 Subject: socket.gethostbyaddr() question In-Reply-To: <1137340074.852853.242350@g47g2000cwa.googlegroups.com> References: <1137340074.852853.242350@g47g2000cwa.googlegroups.com> Message-ID: Harlin Seritt wrote: > I have a list of IP addresses I am testing with socket.gethostbyaddr(). > For the most part, I am able to get a hostname returned to me when I > run gethostbyaddr(). I am also hoping this will allow me to tell if a > computer is up or down. However, in my environment, I am finding that I > am able to get a hostname even though I am unable to actually ping that > server (when I ping a server i like this, I get 'request timed out' > messages telling me that the server is not up). > > Other times, I am able to ping a server with success but the > gethostbyaddr() request will not be able to return a hostname for me > making me think that machine is truly down when I know it's not. Can > anyone give me any pointers as to why this happens? Is there anyway I > can do a reliable ping to another server with Python? I am not > interested in doing system calls with a system Ping client (I have to > ping way too many machines and this either takes too long or causes > severe memory leakage due to MS's horrible ping client). Also, I am > unable to use Jeremy Hylton's Python ping client because it does little > more than call gethostbyaddr(). Thanks for taking a look at this. > If you have the ability to run code on the machines you are interested in you might want to consider Nicola Larosa's heartbeat recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 You may also find something useful in http://pynms.sourceforge.net/ping.html regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From fred at adventistcare.org Wed Jan 18 08:39:50 2006 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 18 Jan 2006 08:39:50 -0500 Subject: ldap passwd need help Message-ID: <1A4BF05172023E468CB6E867923BC90410954F@accmail2.sunbelt.org> I've got the python-ldap version 2.0.11 with python 2.4 under Linux I've got the ldap stuff working for groups, but now I'm trying to use it to change a user password. I get a return of 2 and no error messages but it does not change ldap. I've tried it with uid = 'joeblow' and with oldpw=whatever it was with the same result. Anyone know what I'm missing? class LdapUser: def __init__(self, uri=uri, binddn=BINDDN, password=""): self.ldap = ldap.initialize(uri) self.ldap.simple_bind(binddn, password) def chg_pw(self,uid,oldpw,newpw): print self.ldap.passwd_s(uid,oldpw,newpw) if __name__=="__main__": Ldap = LdapUser(password="secret") Ldap.chg_pw("uid=joeblow,ou=abc,ou=def,dc=ghi,dc=org","", "new.pass") --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From peter at monicol.co.uk Sat Jan 21 15:00:56 2006 From: peter at monicol.co.uk (Peter) Date: 21 Jan 2006 12:00:56 -0800 Subject: Error in Python documentation References: <1137871708.915016.176070@g49g2000cwa.googlegroups.com> Message-ID: <1137873656.237220.318070@g14g2000cwa.googlegroups.com> >From http://www.python.org/doc/2.4.2/ go to the Library reference http://www.python.org/doc/2.4.2/lib/lib.html from there to the index (i) at http://www.python.org/doc/2.4.2/lib/genindex.html. In the index select 'p' and click to reach http://www.python.org/doc/2.4.2/lib/types.html#l2h-90 . At the foot of this page is a link: "See About this document... for information on suggesting changes." which if you follow takes you to http://www.python.org/doc/2.4.2/lib/about.html where there is: If you find specific errors in this document, either in the content or the presentation, please report the bug at the Python Bug Tracker at SourceForge. So you need to add a bug to the Python bug tracker -- at least so it seems. Peter From roccomoretti at hotpop.com Tue Jan 3 13:06:45 2006 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 03 Jan 2006 12:06:45 -0600 Subject: One-step multiples list generation? In-Reply-To: <43babb0b$0$15459$636a55ce@news.free.fr> References: <43bab67c@news.bezeqint.net> <43babb0b$0$15459$636a55ce@news.free.fr> Message-ID: Damien Wyart wrote: > * Efrat Regev in comp.lang.python: > >>Suppose I have some non-numerical Foo and would like to create a list >>of 20 Foo-s. Is there a one-step method (not a loop) of doing so? > > > Maybe : > > [ Foo ] * 20 > > or, more verbose, > > [ Foo for _ in range(20) ] > If Foo is mutable, keep this in mind: >>> a = [ [] ]*20 # A list of 20 empty lists >>> print id(a[0]) == id(a[1]) True >>> a[0].append(1) >>> print a [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] >>> >>> b = [ [] for _ in range(20) ] # A list of 20 empty lists >>> print id(b[0]) == id(b[1]) False >>> b[0].append(1) >>> print b [[1], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []] From cs at totallybogus.com.invalid Sun Jan 1 12:51:40 2006 From: cs at totallybogus.com.invalid (Cousin Stanley) Date: Sun, 01 Jan 2006 11:51:40 -0600 Subject: Problems with Tkinter References: Message-ID: <1136137900_1127@spool6-east.superfeed.net> > My first try fiddling around with GUIs ended disappointing, > instead of showing the window title as expected 'Demofenster' > ist still shows 'tk' instead. > > What did I do wrong? > > > #!/usr/bin/env python > > from Tkinter import * > fenster = Tk() > fenster.title = 'Demofenster' > fenster.mainloop() Steffen .... To set the Tk window title try .... fenster.title( 'Demofenster' ) -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From Brian.Danielsen at infineon.com Thu Jan 12 14:17:46 2006 From: Brian.Danielsen at infineon.com (Danielsen Brian (IFR Contractor External)) Date: Thu, 12 Jan 2006 14:17:46 -0500 Subject: File Navigation using python Message-ID: Does anyone know how to do file navigation between drives? I know how to navigate up and down within a drive (for example the C:\ drive), but I don't know how to change drives. I'm looking for something like: os.chgdrv('d:\') Help Brian L. Danielsen brian at astroexec.com From juho.schultz at helsinki.fi Wed Jan 11 09:12:58 2006 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Wed, 11 Jan 2006 16:12:58 +0200 Subject: how to improve this simple block of code In-Reply-To: <1136987885.792305.119640@f14g2000cwb.googlegroups.com> References: <1136987885.792305.119640@f14g2000cwb.googlegroups.com> Message-ID: py wrote: > Say I have... > x = "132.00" > > but I'd like to display it to be "132" ...dropping the trailing > zeros...I currently try this > > if x.endswith("0"): > x = x[:len(x)-1] > if x.endswith("0"): > x = x[:len(x)-1] > if x.endswith("."): > x = x[:len(x)-1] > > I do it like this because if > x = "132.15" ...i dont want to modify it. But if > x = "132.60" ...I want it to become "132.6" > > is there a better way to do this? It seems a bit ugly to me. > > T.I.A > (thanks in advance) > x = x.rstrip('0') # removes trailing zeros x = x.rstrip('.') # removes trailing dot(s) From ram0812 at hotmail.com Thu Jan 19 07:53:14 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 19 Jan 2006 04:53:14 -0800 Subject: MSSQL LIKE and IN statements in ADO problem In-Reply-To: <1137661774.301820.188640@g44g2000cwa.googlegroups.com> References: <1137598018.349898.213860@g43g2000cwa.googlegroups.com> <1137611031_8547@sp6iad.superfeed.net> <1137661774.301820.188640@g44g2000cwa.googlegroups.com> Message-ID: <1137675194.297332.289060@g47g2000cwa.googlegroups.com> Ok guys! The problem seems to be much easier to be solved than first thought. -->Shoot<-- Using the correct CreateParameter statement seems to do the trick. For example creating the parameter as cmd.CreateParameter(name,const.adVarChar, const.adParamInput, Size=16, Value=value[i]) # Name, Type, Direction, Size, Value works pretty good with the LIKE statement For the IN statement I have not yet found a good way. As of now in am looping through the values and creating various parameters Snippet: ## ##Global initialization ## typeMap= { types.IntType: const.adInteger, types.LongType: const.adBigInt, } query = "SELECT * FROM tb_name WHERE firstname IN %(in_params)" ## ##add parameters and construct the ? values for the in statements ##Note the code below is a pseudo type thing and can contain syntax errors ## in_parameters = [1,2,3,4,5] n_index = 0 in_params = '' for i in in_parameters: in_params += '?,' name = 'name_%s' % i p=cmd.CreateParameter(name, typeMap[type(i)], const.adParamInput, Size=16, Value=i) # Name, Type, Direction, Value cmd.Parameters.Append(p) query = query % {'in_params': in_params[:-1]} Any inputs to improve the IN statement logic? My dream is to use just one create parameter for the SQL list so that the query looks like query = "SELECT * FROM tb_name WHERE firstname IN ?" Nice and easy... :-) Thanks in advance! /Raja Raman From aleax at mail.comcast.net Sun Jan 22 01:24:21 2006 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 21 Jan 2006 22:24:21 -0800 Subject: new.instancemethod as a form of partial() References: <1137909252.302630.194980@g44g2000cwa.googlegroups.com> Message-ID: <1h9jcq2.ec9nsg114qtk7N%aleax@mail.comcast.net> wrote: ... > So it seems that instancemethod() don't like "None" as the instance. "bound methods" and "unbound methods" are instance of the same type, distinguished by one thing: the im_self of an unbound method is None, the im_self of a bound method is anything else. So, when you pass None as the instance, instancemethod likes it just fine... and returns an "unbound method" as the result, so you haven't actually achieved your goal (you must still pass the first parameter explicitly -- all you've "gained" by wrapping a function into an unbound method is an implicit typecheck on the first argument, and if, as the class, you're using 'object' as in your example, that's not much use [even in other cases, it's no great shakes;-)]). Alex From j.spies at hccnet.nl Mon Jan 2 14:40:39 2006 From: j.spies at hccnet.nl (Jaap Spies) Date: Mon, 02 Jan 2006 20:40:39 +0100 Subject: - E04 - Leadership! Google, Guido van Rossum, PSF In-Reply-To: <1h8j7ia.1l5aln617o84osN%aleax@mail.comcast.net> References: <43b15d36$0$82640$ed2619ec@ptn-nntp-reader03.plus.net> <1135782518.053020.14730@g43g2000cwa.googlegroups.com> <1h8hyw6.1sioocwkju4zjN%aleax@mail.comcast.net> <1136205478.918848.245620@g44g2000cwa.googlegroups.com> <1h8j7ia.1l5aln617o84osN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > Anton Vredegoor wrote: > ... > >>>>only hire people with long backstabbing histories. >>> >>>Such as...? Guido van Rossum? Greg Stein? Vint Cerf? Ben Goodger? > > ... > >>No insider information is necessary, the job requirements make it >>absolutely clear (at least to me) that Google is a company with an >>elitist culture, > > > Absolutely yes, in terms of who we want to work at Google: we DO want > GREAT people. And we don't keep this a secret, either: right up there > at , we say "our strategy is simple: we > hire great people". Rather than hiring a LOT of people, we prefer to be > extremely, obsessively selective, and try to hire ONLY a few people, > ones who we can convince ourselves do deserve that adjective, "great". > > This does mean that we definitely tend err on the side of caution, and > FAIL to hire some people who are also great, just because we can't > determine with sufficient certainty that they indeed are -- I've seen > this happen more than once, and deeply regret it (for both Google and > the person), but I have no idea how we could do better without relaxing > our extremely elitist standards (we do debate these issues internally > all of the time, trying to do better, but have found no magic wand yet). > > But this has nothing to do with "only people with backstabbing > histories", which looks like an unsupported, generalized insult. > > >>just like most universities. In fact I am convinced >>that universities (and this time I have extensive, first person and >>historic information) are elitist. > > > No doubt they try to be, mostly (except where governments or other > institutions "twist their arms" to force them to admit huge masses of > students), but I've met many people with advanced degrees from even the > best/most elitist universities, such as Stanford or MIT, where it sure > looked to me as if the university's attempts to only graduate the very > best have definitely failed. > > >>We can discuss that if you want but to me it's appararent that *titles* >>are a strong indication of elitism. Further more I am convinced that > > > Requiring a certain title for a job is mostly a desperate attempt to > reduce the huge amount of work and effort it takes to hire great people, > whittling down the number of resumes to be considered divided by the > number of hires from the high thousands to the low hundreds. If there > were available infinite resources for the job of hiring/selection, we > could easily interview, say, 6000 candidates for a post, giving each a > week or so of concentrated attention to probe their abilities; alas, > this would require about 120 person-years from our people for the > selection process. So, if nobody at Google did ANYTHING BUT interview > candidates, given that we have a bit over 5000 employees now, we could > hire in the course of 2006 another 40 or so, without doing anything > else. (The numbers are all off the top of my head, but I think they may > be roughly the right orders of magnitude). > > This is just impractical: we need to hire many more than 40, AND cannot > afford to have all existing employees do nothing but select new ones. > So, we need to shrink the ratio drastically, on both factors: say 10 > instead of 40 hours of selection per candidate, and 50 rather than 6000 > candidates being considered per post. So we perform selection in > stages, and most candidates out of those many thousands-per-job are > "weeded out" at the very first stage, e.g. by failing to meet specific > qualifications. > > I wish that, as you say, "titles" were indeed strong indications of > excellence. Unfortunately, they aren't, but in some cases they're > better than nothing. Many of our job descriptions, as I pointed out in > another post on this thread, say "BS or equivalent experience" or words > to that effect; if you can show the "or equivalent", and can get past > the first hurdle, then that title is the least of the issues. For > example, if we advertised a job requiring "PhD or equivalent", and among > the candidates were Bill Gates, Larry Page, and Sergey Brin, none of > whom has obtained a PhD to the best of my knowledge, they would surely > be able to display the "or equivalent" based on their accomplishments > and experience, and thus get past that first hurdle. > > > >>uses to discredit paranormal phenomena. For example, careers are >>"construed" because scientific success is credited to persons higher in >>the hierarchy and mistakes are the faults of research assistents or >>students. Only if this system breaks down we see reports of "scientific > > > Can you show that happening for Guido van Rossum, for example, or Greg > Stein? What "hierarchy" were they in, to enable them, as you're > accusing, to take credit for accomplishments that are not their own, and > deflect blame to poor maligned underlings? > > You've made a very specific and insulting claim about Google hiring only > people with long histories of backstabbing, and yet it appears that > you're failing to substantiate it. Hurling such accusations (ones which > obviously must involve specific people, since the whole thread, as > indicated by the subject, starts with Guido's working for Google) > without being able to provide any substance is, in my strongly held > opinion, quite reprehensible, and doesn't reflect well on you. > > > >>However for *me* personally, because I am deserted by my government, >>the university community, friends and family, and left to fend for >>myself, there is no pressing need to keep up the facade so I can >>finally see it for what it is. >> >>I hope this answers some of your questions about my position. Anyway, I >>think its better to talk about positive things, like trying to convince >>google to hire any and all people who can program irrespective of their >>corruption history. > > > People who distinguish themselves as outstanding contributors to > open-source projects can generally clear the "or equivalent" hurdle > without difficulty. Do you consider a history of such contributions to > be a "corruption history" and evidence of "backstabbing", too? To > emerge as such an outstanding contributor, titles are irrelevant: all > you need, besides willingness and ability to invest your time that way, > are outstanding technical ability (particularly in design and coding, > but testing and debugging are also very important, and so is a knack for > writing good documentation -- one can become an "outstanding > contributor" through many possible combinations of such skills) AND any > of a wide range of suitable character and personality traits. > > To focus on the latter: I would never want Google to hire somebody, no > matter how great a programmer they might be, who can accuse, for > example, Guido van Rossum, of having a "long history of backstabbing", > without any substantial data to back up the accusation, just to vent > their frustration at their personal situation. You DID say that Google > hires ONLY people with long histories of backstabbing, and by the very > definition of the word "ONLY" this means you are accusing me, Guido, > Greg, etc, etc, of having "long histories of backstabbing" -- and after > hurling such insults, and providing NO specific data to support them, > you're hallucinating that you can now switch "to talk about positive > things"?! > > One reason I'm so happy we've hired Guido is that, in addition to his > technical excellence, he's just a great guy, wonderful to work with. > Technical excellence is a necessary but not sufficient quality: one ALSO > needs suitable combinations of character and personality, and Guido has > them, in spades. There is an enormous variation of personalities and > character traits at Google (we DO value diversity!), but they all have > in common the fact that they can combine into small, fluid teams which > become even more productive than "the sum of their parts", because > teammates LIKE AND RESPECT AND TRUST each other. I do not see how > somebody whose behavior included such unsubstantiated "backstabbing" > accusations could be productive in this way. > > > And, about the job-posting you liked better...: > > >>Run by an engineer, this work environment is a meritocracy. You will be > > > To me, "meritocracy" and "elitism" are close to being synonyms, in most > contexts. "Meritocracy" is defined somewhere on the net as: > """ > A system of government whereby a particular standard of ability is used > as the basis by which political leadership is determined or accrues to > an existing elite. > """ > Note the connection with "elite", which in turn gives us "elitism". I > do like "meritocracy" because it specifically mentions *ability*, but of > course ability (including technical skill, which in turn is enhanced by > appropriate experience, AND 'softer' character/personality issues) is > what a successful firm bases its "elite" on (or tries to; if it fails, > and hires people bereft of sufficient ability, it won't prosper long). > > > Alex That all been said. My recommandation: hire that man! Jaap From xavier.morel at masklinn.net Thu Jan 12 14:53:59 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Thu, 12 Jan 2006 20:53:59 +0100 Subject: Freezing In-Reply-To: <1137091960.767015.176860@g47g2000cwa.googlegroups.com> References: <1137091489.145991.91030@g43g2000cwa.googlegroups.com> <1137091960.767015.176860@g47g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > The first line of that example has to be: > > s = |set([1, 3, 5])| > > But I don't know/remember why set() can't accept many values like > max/min: > > max([1,2,5]) > max((1,2,5)) > max(1,2,3) > > Bye, > bearophile > How about just providing a freeze method on `object` (since everything will inherit from object) that can freeze the object? In fact the freeze protocol could provide 2 methods: freeze and frozen, the former would freeze the object in place (e.g. freeze the object it's applied to) while the later would return a frozen copy of the object it's applied to. That way, it could even be used as a const-like parameter to a function (with frozen) Examples: >>> l = [0, 1, 2, 3] >>> l.append(5) >>> l [0, 1, 2, 3, 5] >>> l.frozen() [0, 1, 2, 3, 5] >>> fl = l.frozen() >>> l.append(7) >>> l [0, 1, 2, 3, 5, 7] >>> fl.append(7) Traceback (most recent call last): ... WhateverError: frozen 'list' object cannot modified >>> fl [0, 1, 2, 3, 5] >>> l.freeze() >>> l [0, 1, 2, 3, 5, 7] >>> l.append(9) Traceback (most recent call last): ... WhateverError: frozen 'list' object cannot modified One could even dream of a melt/molten method pair that'd behave at the opposite of the freeze/frozen pair (to have the ability to "unfreeze" an object if needed) No new keyword, no new token, no new structure, no new builtin, same functionalities. From me at somewhere.com Mon Jan 16 07:44:24 2006 From: me at somewhere.com (Joe bloggs) Date: 16 Jan 2006 12:44:24 +0000 Subject: boost.python on Debian Message-ID: <87oe2c4a1j.fsf@localhost.localdomain> Can anyone tell me how to get boost.python to work on Debian Sarge? When I try to build the tutorial hello world example bjam reports: /usr/share/doc/libboost-doc/examples/libs/python/example/boost-build.jam attempted to load the build system by invoking 'boost-build ../../../tools/build/v1 ;' but we were unable to find "bootstrap.jam" in the specified directory or in BOOST_BUILD_PATH (searching /usr/share/doc/libboost-doc/examples/libs/python/example/../../../tools/build/v1, /usr/share/boost-build). I have looked for 'bootstrap.jam' but it doesn't exist on my system. I suppose that the Debian boost package doesn't have the same structure as the official one, and is missing some files. Can anyone tell me how to fix this? From gh at ghaering.de Sun Jan 15 12:17:15 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 15 Jan 2006 18:17:15 +0100 Subject: [ANN] pysqlite 2.1.0 released Message-ID: <43CA839B.5020305@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.1.0 released ======================= I'm pleased to announce the availability of pysqlite 2.1.0. This is a major release with many new features and some internal changes. While the code was tested by a few people who tracked Subversion, users are still adviced to test their applications intensively with the new release before upgrading them to pysqlite 2.1.0. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a relational database management system contained in a relatively small C library. It is a public domain project created by D. Richard Hipp. Unlike the usual client-server paradigm, the SQLite engine is not a standalone process with which the program communicates, but is linked in and thus becomes an integral part of the program. The library implements most of SQL-92 standard, including transactions, triggers and most of complex queries. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. ======= CHANGES ======= Statement caching ================= Planned since the start of the pysqlite2 development, the most difficult to implement feature has now been implemented: transparent statement caching. What is statement caching? Every SQL engine has a COMPILE and EXECUTE phase. In older pysqlite releases, every SQL statement (except for executemany) was always COMPILED and EXECUTED. With statement caching, pysqlite can transparently optimize away the COMPILE step. The statement cache is implemented using a LRU cache with a default capacity of 100. The cache is per connection - it's capacity can be set when opening a connection: con = sqlite.connect(..., cached_statements=30) In a nutshell, this means the 100 most used SQL statements in your application will only have to be COMPILED once by the SQLite engine. This will of course only work well if you use the parameter-form of the execute() method, i. e. for: cur.execute("insert into foo(bar) values (?)", ("xy",)) cur.execute("insert into foo(bar) values (?)", ("ab",)) the SQL statement "insert into foo(bar) values (?)" will then only be compiled once. Users have seen significant performance improvements with the statement caching in pysqlite 2.1.0: http://lists.initd.org/pipermail/pysqlite/2005-November/000234.html More flexibility for TEXT data ============================== Until now, pysqlite would always return Unicode strings for text data, unless you did some crazy trickery. If you prefer to retrieve text data as Python bytestrings or a different type, you can now set a text_factory callable per connection: con.text_factory = str # ... to always return bytestrings An optimized shortcut has been enabled to retrieve Unicode strings for non-ASCII data, but bytestrings for non-ASCII text: con.text_factory = sqlite.OptimizedUnicode or something custom: con.text_factory = lambda x: unicode(x, "utf-8", "ignore") Highly optimized row_factory for column access by name ====================================================== A new function has been implemented that allows for case-insensitive column access by name with minimal performance and memory impact, unlike a dictionary or db_row-based approach. To enable it, set the row_factory attribute of your connection to sqlite.Row: from pysqlite2 import dbapi2 as sqlite con = sqlite.connect(...) con.row_factory = sqlite.Row cur = con.cursor() cur.execute("select name_last, age from people") for row in cur: print row["Name_Last"], row[1] Convenience methods =================== The execute(), executemany() and executescript() methods are now also available in the Connection class. This allows you to write very concise code like this: con = sqlite.connect(...) con.execute("insert into foo(bar) values (5)") for row in con.execute("select bar from foo"): print row API changes =========== The row_factory attribute has been moved from the Cursor class to the Connection class. For backwards compatibility, using it on the Cursor class still works. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFDyoObdIO4ozGCH14RAt9uAJ9EO8jHuLjhPleYjWWUe+lt++GsngCeInQY CxfGAxmV5I8UMuM620wWTac= =jsNu -----END PGP SIGNATURE----- From khemkaamit at gmail.com Thu Jan 12 10:49:22 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 12 Jan 2006 21:19:22 +0530 Subject: Timeout at command prompt In-Reply-To: <7xmzi1fogy.fsf@ruckus.brouhaha.com> References: <1137014674.861185.223470@o13g2000cwo.googlegroups.com> <7xmzi1fogy.fsf@ruckus.brouhaha.com> Message-ID: <1360b7230601120749r3de80f4bl1b42b138ec2e6113@mail.gmail.com> I tried it on "Python 2.4.1" on '2.6.11-1.1369_FC4smp with gcc version 4.0.0' .. which works fine .. may be it could be an issue with some other combinations .. cheers, amit On 12 Jan 2006 07:35:57 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Amit Khemka writes: > > import signal > > TIMEOUT = 5 # number of seconds your want for timeout > > signal.signal(signal.SIGALRM, input) > > signal.alarm(TIMEOUT) > > > > def input(): > > try: > > foo = raw_input() > > return foo > > except: > > # timeout > > return > > This doesn't work with raw_input under linux, maybe because the > readline lib is snagging the timer interrupt or something. Use > sys.stdin.readline instead. SF bug: > > http://sourceforge.net/tracker/index.php?func=detail&aid=685846&group_id=5470&atid=105470 > -- > http://mail.python.org/mailman/listinfo/python-list > -- ---- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. From peter at engcorp.com Thu Jan 26 18:49:58 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Jan 2006 18:49:58 -0500 Subject: Automatic Logging In-Reply-To: <1138312387.806806.133110@g14g2000cwa.googlegroups.com> References: <1138312387.806806.133110@g14g2000cwa.googlegroups.com> Message-ID: daftspaniel at gmail.com wrote: > Sorry if this is a FAQ but Google returns a *lot* of results for Python > Logging :-) > > I am looking for a tool that will automatically add logging to existing > code e.g. Function Entries and Exits, Return values etc. Perhaps you are looking for nothing more than this standard function: >>> help(sys.settrace) Help on built-in function settrace in module sys: settrace(...) settrace(function) Set the global debug tracing function. It will be called on each function call. See the debugger chapter in the library manual. Combine that with the standard library "logging" package and it meets your specs as stated above. -Peter From aleax at mail.comcast.net Sun Jan 29 23:56:26 2006 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 29 Jan 2006 20:56:26 -0800 Subject: A class with eventhandlers ? References: Message-ID: <1h9y22w.185b2buad429mN%aleax@mail.comcast.net> Runsun Pan wrote: ... > or, more specific, a function/method-specific error > handling feature: > > c.load.onError( IOErrorHook) > c.load( filename ) > > Is there such a mechnism around? If not, is it possible > to make such a thing ? Never heard of one, but you could surely make a custom metaclass satisfying your specs (==wrapping each method into an instance of a type providing such an onError method, as well as a __call__ delegating to the real method within a suitable try/except). Sounds like a lot of work to me, though;-). Alex From tuvas21 at gmail.com Thu Jan 26 15:04:18 2006 From: tuvas21 at gmail.com (Tuvas) Date: 26 Jan 2006 12:04:18 -0800 Subject: Possible memory leak? In-Reply-To: <1138285656.279927.29140@g14g2000cwa.googlegroups.com> References: <1138139496.541121.322750@g47g2000cwa.googlegroups.com> <43D73B94.6000804@REMOVEMEcyber.com.au> <1138285656.279927.29140@g14g2000cwa.googlegroups.com> Message-ID: <1138305858.863851.299790@g49g2000cwa.googlegroups.com> I have made one confirmation. The only identifiable difference that I have seen is that one runs on python 2.4.2, and the other 2.4.1. Oddly enough, it's the first one that's the one that is having more problems than the second... Why that is, I don't know. It still could be something else, but... From steve at holdenweb.com Fri Jan 20 22:49:44 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Jan 2006 03:49:44 +0000 Subject: OT: excellent book on information theory In-Reply-To: <11t3a6tr7t6fd40@corp.supernews.com> References: <009301c61ac0$718df6d0$0200a8c0@FATDESK> <11t3a6tr7t6fd40@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-01-21, Steven D'Aprano wrote: [...] >>But the real question is why it is that American publishers >>believe their readers are so lazy and ignorant that they >>require special "translations" of British books. I don't know >>anyone who has said "I'm glad that I read the American edition >>of [Harry Potter/Discworld/pick your own example], it was much >>better than the British edition." Not even American fans. > > > The next thing you know, there are going to be American > translations of Jane Austin where a girl says to her sister > "dude, he is such a hottie!" and she replies "oh my god, for > sure!" > Like, gag me with a spoon, dude. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From cowie.rob at gmail.com Wed Jan 18 12:14:19 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 18 Jan 2006 09:14:19 -0800 Subject: Using CGI to interface with an XML-RPC server In-Reply-To: References: <1137529758.132297.73050@z14g2000cwz.googlegroups.com> Message-ID: <1137604459.785753.268450@o13g2000cwo.googlegroups.com> >Python ships with cgi and xmlrpc support (cgi and xmlrpclib, respectively), >so I'm not sure why you even think you have to ask... > 1. use cgi to parse form data > 2. use xmlrpclib to issue request > 3. use print or your favourite html templating library to generate > output > >(it might be a good idea to check with your web server admins, though, >to make sure they don't have a problem with outgoing HTTP requests) So it is possible. I'm aware of cgi and xmlrpc modules. The reason I have asked is that there appears to be much difficulty when tying these two things together. I also wanted to see if anyone mentioned CGIXMLRPCserver which is part of the stdlib. I am unsure if this is what I am looking for. I have been unable to fully comprehend the documentation. Thanks for your help. From david at dawninglight.net Fri Jan 13 20:02:43 2006 From: david at dawninglight.net (David Blewett) Date: Fri, 13 Jan 2006 20:02:43 -0500 Subject: Pythonic wrappers for SQL? In-Reply-To: References: Message-ID: <20060113200243.uidq2qbffjvks8k0@mail.dawninglight.net> Quoting Kenneth McDonald : > I need to do some data manipulation, and SQLite is a nice little > product for it, except of course that I'd need to write SQL. Are > there any good libraries out there that let one write (basic) queries > in a Pythonic syntax, rather than directly in SQL? Funny you should bring this up. I was just looking at a few sites about this today. First is an article on Devx that explains a way to do this: http://www.devx.com/dbzone/Article/22093/1954?pf=true Then I found a package that does the heavy lifting: http://www.penguin.cz/~ondrap/sqlabstr_cond.php David ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From tim.leeuwvander at nl.unisys.com Wed Jan 18 05:43:24 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 18 Jan 2006 02:43:24 -0800 Subject: New Python.org website ? In-Reply-To: References: <43C4E198.2080107@holdenweb.com> <1137574511.134535.30390@g49g2000cwa.googlegroups.com> <1137577741.221027.11640@g14g2000cwa.googlegroups.com> Message-ID: <1137581004.474565.201000@g14g2000cwa.googlegroups.com> I need to supply a username/password before I can look at the SVN repository in my webbrowser; I tried username/pwd 'anonymous' but that don't work. cheers, --Tim From kent at kentsjohnson.com Sat Jan 7 10:23:39 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 07 Jan 2006 10:23:39 -0500 Subject: question about mutex.py In-Reply-To: References: Message-ID: <43bfd964$1_2@newspeer2.tds.net> Jean-Paul Calderone wrote: > Did you read the module docstring? > > Of course, no multi-threading is implied -- hence the funny interface > for lock, where a function is called once the lock is aquired. > > If you are looking for a mutex suitable for multithreaded use, see the > threading module. I have always seen mutexes used in multi-threaded programs. I'm curious, what is the usefulness of a non-thread-safe mutex? I'm sure it must be good for something, I just can't figure it out. Thanks, Kent From sybrenUSE at YOURthirdtower.com.imagination Mon Jan 16 03:06:42 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 16 Jan 2006 09:06:42 +0100 Subject: ConfigParser: writes a list but reads a string? References: Message-ID: Terry Carroll enlightened us with: > It looks like ConfigParser will accept a list to be writing to the > *.ini file; but when reading it back in, it treats it as a string. It doesn't say so explicitly in the manual, but I did find this: """The values in defaults must be appropriate for the "%()s" string interpolation.""" So if the defaults go through %s, perhaps all values do. > Is there a pythonic way to read in a list from a .INI file with > ConfigParser? I'd pickle() the list, and store that instead. Then you can unpicle() it and regain your list. > I would not expect this conversion; rather, an exception when trying > to write the list if the list is not supported. I agree with you. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From homepricemaps at gmail.com Tue Jan 24 14:11:34 2006 From: homepricemaps at gmail.com (homepricemaps at gmail.com) Date: 24 Jan 2006 11:11:34 -0800 Subject: getting a KeyError:'href' any ideas? In-Reply-To: <86psn6schp.fsf@bhuda.mired.org> References: <1136485231.236129.98410@g47g2000cwa.googlegroups.com> <86psn6schp.fsf@bhuda.mired.org> Message-ID: <1138129894.305010.266640@g44g2000cwa.googlegroups.com> what is the syntax used to find a child of td? Mike Meyer wrote: > "homepricemaps at gmail.com" writes: > > Please use less whitespace in your posts in the future. There's really > no need to put two blank lines between sections. > > > i have an > > href which looks like this: > > > > > > > > here is my code > > for incident in row('td', {'class':'all'}): > > n = incident.findNextSibling('a', {'class': 'btn'}) > > link = incident.findNextSibling['href'] + "','" > > any idea what i'm doing wrong here with the syntax? thanks in advance > > It's not the syntax, it's the logic. the a element is not a sibling of > the td element, it's a child. findNextSibling is going to return the > next td, assuming there is one. Trying to index > incident.findNextSibling in the next line is also broken. That's a > method, not an indexable object. So that line will also break. > > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From wmcdonald at gmail.com Mon Jan 23 06:38:05 2006 From: wmcdonald at gmail.com (Will McDonald) Date: Mon, 23 Jan 2006 11:38:05 +0000 Subject: Testing for the presence of input from stdin. Message-ID: <1f8fae340601230338q1180d7f3k@mail.gmail.com> Hi all. I'm writing a little script that operates on either stdin or a file specified on the command line when run. I'm trying to handle the situation where the script's run without any input gracefully but can't think how to test for stdin. I can test for a file argument on the command line using getopt and validate its existence with os.path.exists. If it doesn't I can print the useage. I can get the script to behave as expected when content's piped to it using sys.stdin but I'd like to know that there's data coming from stdin or fail and print the useage again. Is there a simple way to achieve this? Thanks, Will. Here's what I've got so far... #!/usr/bin/python # # hail - heads and tails import sys, os, getopt def hail(file,headlines=10,taillines=10): lines = file.readlines() sys.stdout.writelines(lines[:headlines]) sys.stdout.writelines(lines[taillines:]) def useage(): print "Useage: hail [OPTION] [FILE]" print " -t, --top # lines from top (default 10)" print " -b, --bottom # lines from bottom (default 10)" print " -h, --help display this help and exit" def main(): try: opts, args = getopt.getopt(sys.argv[1:], "t:b:h", ['top=','bottom=','help']) except getopt.GetoptError: useage() sys.exit(2) for o,a in opts: if o in ("-t", "--top"): toplines = a if o in ("-b", "--bottom"): bottomlines = a if o in ("-h", "--help"): useage() sys.exit() if len(args) == 1 and os.path.exists(str(args[0])): file = (str(args[0])) # else: # file = sys.stdin hail(file,headlines=toplines,taillines=bottomlines) if __name__ == "__main__": main() From http Tue Jan 17 16:45:44 2006 From: http (Paul Rubin) Date: 17 Jan 2006 13:45:44 -0800 Subject: magical expanding hash References: <1137478291.342584.83030@g47g2000cwa.googlegroups.com> <1137523154.114949.69610@f14g2000cwb.googlegroups.com> <7xk6cyvd94.fsf@ruckus.brouhaha.com> <1137528218.895388.112560@g49g2000cwa.googlegroups.com> <7x1wz6wq1n.fsf@ruckus.brouhaha.com> <1137533023.895288.277950@z14g2000cwz.googlegroups.com> Message-ID: <7xoe2a8r5j.fsf@ruckus.brouhaha.com> "braver" writes: > Exactly, << as in C++/ruby streams. But notice the extra checks needed > to see whether we want a new leaf which is an array or a number, or we > create an intermediate hash level. Would the checks look the same in > python? You could check what is being shifted and make a new leaf of the appropriate type. If you put a number there though, you wouldn't be able to then add more nodes beneath that number. From python-url at phaseit.net Sun Jan 22 22:48:01 2006 From: python-url at phaseit.net (Magnus Lycka) Date: Mon, 23 Jan 2006 03:48:01 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 23) Message-ID: QOTW: "The IEEE-754 standard doesn't wholly define output conversions, and explicitly allows that a conforming implementation may produce any digits whatsoever at and after the 18th signficant digit, when converting a 754 double to string. In practice, all implementations I know of that exploit that produce zeroes at and after the 18th digit -- but they could produce 1s instead, or 9s, or digits from pi, or repetitions of the gross national product of Finland in 1967." - Tim Peters "If you can't do a first version in six months with a team of six people it is a sign that you don't really know what you want." - Jack Diederich Besides the layout for the new Python web site, work on converting the content from the current site has begun: http://groups.google.se/group/comp.lang.python/browse_frm/thread/330af3b245145f7e/429bd0c83ff89b0c?rnum=3#429bd0c83ff89b0c There has been interest in Sudoku solvers on comp.lang.python lately: http://groups.google.se/group/comp.lang.python/search?q=sudoku&start=0&scoring=d& Don't expect to use the ConfigParser for non-text data. Use ConfigObj instead when that's what you need: http://groups.google.se/group/comp.lang.python/browse_frm/thread/3b5f75051b1fb57c How do you use Python without installing it on your computer? http://groups.google.se/group/comp.lang.python/browse_frm/thread/8ed65089a7c01e3b Should a web development framework be included in the standard library? http://groups.google.se/group/comp.lang.python/browse_frm/thread/d3e9bd6d002df4d4 Claudio Grondi tries to grok Python by asking questions that seem to confuse those who try to answer: http://groups.google.se/group/comp.lang.python/browse_frm/thread/b6515a4574dc9292 No, regular expressions aren't supposed to be gargantuan, but there should really be a proper exception when they are: http://groups.google.se/group/comp.lang.python/browse_frm/thread/64df1dd7202e247e This is neither the first nor the last week, when someone asks questions related to a mismatch between binary floats and decimal numbers: http://groups.google.se/group/comp.lang.python/browse_frm/thread/fe07673b9f77738e How do we generate graphics dynamically with Python CGI scripts? http://groups.google.se/group/comp.lang.python/browse_frm/thread/8179735820c85cb A PHP programmer is making efforts to figure out Python, in particular with regards to threads, databases and modularity. (Welcome Robin!) http://groups.google.se/group/comp.lang.python/browse_frm/thread/bf75a37e9242cce http://groups.google.se/group/comp.lang.python/browse_frm/thread/2055bab118aeec50 Numarray, Numeric, NumPy... There should be one--and preferably only one--obvious way to do it. So, which is it? http://groups.google.se/group/comp.lang.python/browse_frm/thread/2a308411c39c042 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From goldfita at signalsguru.net Wed Jan 4 14:58:58 2006 From: goldfita at signalsguru.net (Todd) Date: 4 Jan 2006 11:58:58 -0800 Subject: Why doesn't this work--Extending Python--? References: <1136402287.078043.148980@g49g2000cwa.googlegroups.com> Message-ID: <1136404738.540031.85940@f14g2000cwb.googlegroups.com> jeremito wrote: > I have written a simple C++ program in my efforts to learn how to > extend Python. It is shown below. Everything compiles and installs > correctly, but I get strange answers. I know the function "Pi" is > correct because when I call it from a C++ code it gives the correct > answers. This is what I get when I run it in Python: > 27 int Particles; > 28 int Pie; > 29 if (!PyArg_ParseTuple(args, "i", &Particles)) > > 30 return NULL; > > 31 Pie = Pi(Particles); > > 32 return Py_BuildValue("d", Pie); Just scanning over this, looks like what you want is double Pie. You have int. The compiler probably gave a warning. http://www.signalsguru.net/ From fredrik at pythonware.com Fri Jan 13 02:45:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Jan 2006 08:45:48 +0100 Subject: Help me in this please--is Python the answer? References: <1137030845.599886.25020@g14g2000cwa.googlegroups.com><1137073009.269890.185610@g44g2000cwa.googlegroups.com> <1137093756.704854.27210@o13g2000cwo.googlegroups.com> Message-ID: Adrian Holovaty wrote: > I would never use TurboGears or Ruby on Rails over Django for any > performance-intensive Web app. In my opinion, both frameworks make some > poor design decisions regarding the importance of performance. I hope you're aware that this sounds a lot like late 90's anti-dynamic- language propaganda... "I would never use Perl or Python over C++ for any performance- "intensive Web app. In my opinion, both languages make some poor design decisions regarding the importance of performance." (you all know all the counter-arguments) From fredrik at pythonware.com Thu Jan 26 06:10:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Jan 2006 12:10:39 +0100 Subject: While loop - print several times but on 1 line. References: Message-ID: Danny wrote: > Great! It's been solved. > > The line, as Glaudio said has a "," at the end and that makes it go onto > one line, thanks so much man! > > var = 0 > while <= 5: > print a[t[var]], > var = var +1 > prints perfectly, thanks so much guys. if you wanted spaces between the items, why didn't you say that ? > How could I make this print: texttexttexttexttext? >>> for i in range(5): ... print "text" ... text text text text text >>> for i in range(5): ... print "text", ... text text text text text >>> import sys >>> for i in range(5): ... sys.stdout.write("text") ... texttexttexttexttext >>> oh well. From samschul at pacbell.net Sun Jan 8 23:37:11 2006 From: samschul at pacbell.net (sam) Date: 8 Jan 2006 20:37:11 -0800 Subject: Building Pywin32 source code? Message-ID: <1136781431.261576.241700@o13g2000cwo.googlegroups.com> Has anyone been able to access the source code for Pywin32 at sourceforge? I have been able to use TortouseCVS to access other CVS projects,but with the Pywin32 cvs site, I can not log in. Sam Schulenburg From alecw at pobox.com Thu Jan 5 11:51:11 2006 From: alecw at pobox.com (Alec Wysoker) Date: 5 Jan 2006 08:51:11 -0800 Subject: Occasional OSError: [Errno 13] Permission denied on Windows References: <1136476700.356482.319110@g44g2000cwa.googlegroups.com> Message-ID: <1136479871.681559.233570@o13g2000cwo.googlegroups.com> >> Using Python 2.3.5 on Windows XP, I occasionally get OSError: [Errno >> 13] Permission denied when calling os.remove(). This can occur with a >> file that is not used by any other process on the machine, > > How do you know that? Yeah, good point. I don't really know. I should have said no process that I am aware of is using the file. I'll give sleep a try instead of gc. Thanks. From theller at python.net Mon Jan 9 13:01:28 2006 From: theller at python.net (Thomas Heller) Date: Mon, 09 Jan 2006 19:01:28 +0100 Subject: Win32 Binary-only for 2.3.x? References: <1136408074.219748.259910@g43g2000cwa.googlegroups.com> <1136538861.588634.269840@g43g2000cwa.googlegroups.com> Message-ID: Trent Mick writes: > [Fuzzyman wrote] >> Out of interest, doesn't the Python binary use the registry (and >> environment variables) for building sys.path ? > > Yes, good point... > >> >> Won't you still have conflicting path issues if you use an alternative >> binary with an existing 'normal' install ? > > ...but it is possible to effectively disable the use of the registry by > a given pythonXY.dll -- if you know how to edit the String Table of the > DLL. Basically there is a string entry in that table that is used as > part of the registry path for registry usage. > > Here is how I do it: > - open MS Visual C++ 6 (I'm sure you can do all this with VS.NET, I > just haven't done it.) > - Ctrl+O for the open file dialog > - Files of type: Executable files (.exe;.dll;.ocx) > - Open as: Resources > - browse to and open pythonXY.dll > - In the string table there is an entry with Value=1000 and Caption=X.Y > (i.e. "2.3" for python23.dll, "2.4" for python24.dll, etc.). That > "X.Y" string is what determines that part of the registry lookup path > for: > HKLM/Software/Python/PythonCore/X.Y/PythonPath > - You could change the "Caption" value to "FuzzyWuzzyWuzzaBear" to > effectively disable usage of the registry for sys.path building by > that pythonXY.dll. py2exe also does something like this in the copy of pythonXY.dll that it creates, to avoid the resulting exe pulling in sys.path entries from the registry. Thomas From dek at bosshog.lbl.gov Tue Jan 10 13:54:54 2006 From: dek at bosshog.lbl.gov (David E. Konerding DSD staff) Date: Tue, 10 Jan 2006 18:54:54 +0000 (UTC) Subject: 2D canvas for GTK References: Message-ID: In article , Sandro Dentella wrote: > Il 2006-01-09, John Bauman ha scritto: >> >> "Sandro Dentella" wrote in message >> news:slrnds33dl.r3n.sandro at bluff.diade.it... >>>I need a (decent) canvas for PyGTK. I used tkinter.canvas with real >>>pleasure >>> in the past but now I need to use the canvas in a Gtk application. Does >>> anybody know of one with similar capabilities? It must work on Windows >>> too. >>> It must be able to produce postscript output. >> >> I think that PyCairo might be what you're looking for, at least if you're >> using gtk 2.8. > > No, that's definitely a lower level tool. I need someting that has > rectangles, lines, possibility to move object around, easy bindings, tags > for objects, grouping. All that is already in tkinter.canvas but I need to > use it from a GTK application. > > Any other ideas? If you can afford the include GNOME as a dependency, then gnome-canvas or diacanvas2 is your best bet. dave From xavier.morel at masklinn.net Sat Jan 7 16:14:11 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Sat, 07 Jan 2006 22:14:11 +0100 Subject: Stackless Python In-Reply-To: References: Message-ID: Christian Tismer wrote: > Xavier Morel wrote: > >> Would anyone have more informations about that? It doesn't seem to be an >> issue on my side (since I tried to access the Stackless site from two >> different connections and 3 computers) but I can't rule it out. > > Thanks to Carl Friedrich, I restarted the Zope process. > > I have no idea why it broke, the site was running since 38 days > without problems. The Zope/Plone process was still there, blocking > the port. > > Maybe I should go for something simpler than Plone... > > Don't hesitate to ask on the mailing list for all the things > you will not find on the site. The list works :-) > > ciao - chris Ah yes, much better now, thank you very much (BTW the first time I got a dead stackless.com was between xmas and new year's eve, so the website has probably been down for more than 10 days, just so you know, if you want to check your logs or something). From khaispidey at hotmail.com Tue Jan 17 09:56:29 2006 From: khaispidey at hotmail.com (Kr z) Date: Tue, 17 Jan 2006 14:56:29 +0000 Subject: Hi, about socket programming and threading Message-ID: An HTML attachment was scrubbed... URL: From nszabolcs at gmail.com Tue Jan 10 11:35:33 2006 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 10 Jan 2006 08:35:33 -0800 Subject: Do you have real-world use cases for map's None fill-in feature? In-Reply-To: <1136883395.171612.154130@f14g2000cwb.googlegroups.com> References: <1136669507.225698.313400@g49g2000cwa.googlegroups.com> <7xhd8drddl.fsf@ruckus.brouhaha.com> <1136883395.171612.154130@f14g2000cwb.googlegroups.com> Message-ID: <1136910933.583691.273770@z14g2000cwz.googlegroups.com> > There are so many varieties of iterator that it's probably not workable > to alter the iterator API for all of the them. i always wondered if it can be implemented: there are iterators which has length: >>> i = iter([1,2,3]) >>> len(i) 3 now isn't there a way to make this length inheritible? eg. generators could have length in this case: >>> g = (x for x in [1,2,3]) >>> # len(g) == len([1,2,3]) == 3 of course in special cases length would remain undefined: >>> f = (x for x in [1,2,3] if x>2) >>> # len(f) == ? IMHO there are special cases when this is useful: L=list(it) here if it has length, then list creation can be more effective (required memory is known in advance) nsz From bdesth.quelquechose at free.quelquepart.fr Mon Jan 9 08:50:13 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 09 Jan 2006 14:50:13 +0100 Subject: Newbie with some doubts. In-Reply-To: <1136425014.404309.300600@g43g2000cwa.googlegroups.com> References: <1136425014.404309.300600@g43g2000cwa.googlegroups.com> Message-ID: <43c25e4c$0$5240$626a14ce@news.free.fr> Edgar A. Rodriguez a ?crit : > Hi everybody, > > Im newbie to Python (I found it three weeks ago) , in fact Im newbie to > programming. I'm being reading and training with the language, but I > still wondering about what Classes are used to. A class is the definition of a type of object, and let you add your own object types to the language. In fact, as soon as you're programming in Python, you are using classes and objects, even if you're not aware of it. *Everything* in Python is an object (ie: an 'instance' of a class). The string "foo" is an instance of class string, the number 42 is an instance of class int, etc. Even functions are objects (instances of class function, yes), so you can access (and modify) the properties of a function: def fun(): "a dummy function" return "foo" fun.___doc__ =>"a dummy function" fun.__class__ => > Could you please give > me some examples?? Let's go with the good ole (and very dumb) example of a shapes drawing program. # The procedural (ie: no classes) version: def draw_line(from, to): # code here def draw_square(origin, width): # code here def draw_circle(center, radius): # code here shapes = [ {'type': 'square', 'origin' : (10,10), 'width' : 20}, {'type': 'circle', 'center': (40, 40), 'radius': 10}, {'type', 'line', 'origin' : (42,42) 'end' : (48,84)} ] def draw_shape(shapes): for s in shapes: if s['type'] == 'line': draw_line(s['origin'], s['end']) elif s['type'] == 'square': draw_square(s['origin'], s['width']) elif s['type'] == 'circle': draw_circle(s['center'], s['radius']) else: raise TypeError, "item %s is not a valid shape" % s # the ObjectOriented version : class Line(object): def __init__(self, origin, end): self.origin = origin self.end = end def draw(self): # code here class Circle(object): def __init__(self, center, radius): self.center = center self.radius = radius def draw(self): # code here class Square(object): def __init__(self, origin, width): self.origin = origin self.width = width def draw(self): # code here shapes = [ Square((10,10), 20), Circle((40, 40),10), Line((42,42), (48,84)), ] def draw_shapes(shapes): for s in shapes: s.draw() Now try to add to both versions a new type of shape, 'rect', with origin, width and height. In the first case, you'll need to modify the draw_shapes() function. In the second case, since each shape type know how to draw itself (this is called 'encapsulation'), you'll only have to define the Rect class. The example being a small and dumb example, the advantage may not be that obvious, but think of what this would mean for a full-featured shape drawing program. And there is of course *much* more than this in OOP... HTH From http Tue Jan 10 04:05:40 2006 From: http (Paul Rubin) Date: 10 Jan 2006 01:05:40 -0800 Subject: Do you have real-world use cases for map's None fill-in feature? References: <1136669507.225698.313400@g49g2000cwa.googlegroups.com> <7xhd8drddl.fsf@ruckus.brouhaha.com> <1136883395.171612.154130@f14g2000cwb.googlegroups.com> Message-ID: <7x7j98pi57.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > > iterator = check_empty(iterator) > > There are so many varieties of iterator that it's probably not workable > to alter the iterator API for all of the them. In any case, a broad > API change like this would need its own PEP. The hope was that it wouldn't be an API change, but rather just a new function dropped into the existing library, that could wrap any existing iterator without having to change or break anything that's already been written. Maybe the resulting iterator couldn't support every operation, or maybe it could have a __getattr__ that delegates everything except "next" to the wrapped iterator, or something. The obvious implementation methods that I can see are very kludgy but maybe something better is feasible. I defer to your knowledge about this. From jmdeschamps at gmail.com Thu Jan 5 10:04:50 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 5 Jan 2006 07:04:50 -0800 Subject: Quickest way to make py script Web accessible In-Reply-To: <1136467079.041848.239470@g14g2000cwa.googlegroups.com> References: <1136467079.041848.239470@g14g2000cwa.googlegroups.com> Message-ID: <1136473490.891707.257700@g43g2000cwa.googlegroups.com> rtilley at vt.edu wrote: > What is the quickiest and easiest way to make a py script run on a Web > server? I have access to an Apache Web server running on Linux. > > I'm often asked to run some of my scripts on behalf of others. My hope > is to make a simple Web-based interface where people could run the > scripts themselves whenever they like... instead of asking me. > > I'd rather not rewrite the scripts with PHP. Any tips on a fast, easy > way of doing this? > > Thanks! If it's just using the web to *run* a python script on the server, then a simple cgi-script which will spawn a process for other scripts. You need a web form that permit the user to choose the script he/she wants executed. That form will point (action='your_cgi_script.py') to the script who's job will be to spawn the other script, submitting the user choice. One HTML page for the script choices and one extra python script to receive the cgi call, seems easy! If it doesn't look that way to you, don't hesitate to let it be known, and on which part... Jean-Marc From trentm at ActiveState.com Mon Jan 9 13:40:25 2006 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 9 Jan 2006 10:40:25 -0800 Subject: modifying DLL string table programatically (Was: Win32 Binary-only for 2.3.x?) In-Reply-To: References: <1136408074.219748.259910@g43g2000cwa.googlegroups.com> <1136538861.588634.269840@g43g2000cwa.googlegroups.com> Message-ID: <20060109184025.GD20750@activestate.com> [Thomas Heller wrote] > py2exe also does something like this in the copy of pythonXY.dll that it > creates, to avoid the resulting exe pulling in sys.path entries from the > registry. Do you have a quick pointer to the code that does this? I wasn't easily able to automate doing this with COM code last time I tried. Trent -- Trent Mick trentm at activestate.com From jimburton1 at gmail.com Mon Jan 23 17:15:02 2006 From: jimburton1 at gmail.com (jimburton) Date: 23 Jan 2006 14:15:02 -0800 Subject: problem getting started with pyDB2 Message-ID: <1138054502.290682.189330@g47g2000cwa.googlegroups.com> Hi, I'm using python 2.4, DB2 8.1 (with development libraries) on ubuntu linux 5.10. I installed PyDB2 1.1 but when I try to connect to any database I've got this: >>> import DB2 >>> conn = DB2.connect(dsn='sample', uid='db2inst1', pwd='secret') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/DB2.py", line 271, in __init__ self._db = _db2.connect(*args, **kwargs) _db2.DatabaseError: ('I', -1, 'Invalid Handle') >>> After installing pydb2 I got errors about the missing file libdb2.so.1 so I copied this file from /opt/IBM/db2/V8.1/lib into /usr/lib - am I now missing other libs? If so how do I let python know about the db2 libs? Thanks! From http Tue Jan 10 14:03:39 2006 From: http (Paul Rubin) Date: 10 Jan 2006 11:03:39 -0800 Subject: Augmented generators? References: Message-ID: <7xwth7nbw4.fsf@ruckus.brouhaha.com> "Andrew Koenig" writes: > Can anyone think of an easy technique for creating an object that acts like > a generator but has additional methods? > For example, it might be nice to be able to iterate through an associative > container without having to index it for each element. Normally you'd define a class and give it __iter__ and next operations. I guess that can get messy. Does it qualify as easy for your purposes? > Of course I can write such a beast as a class, but that prevents me from > taking advantage of the yield statement in its implementation. You can make an internal function that's a generator with a yield statement (or a generator expression instead of a function, if simple enough). The class's 'next' method would loop through the generator and return each value from it. Let me try your example: class kviter: def __init__(self, d): self.d = d def __iter__(self): def iter1(d, s=self): for k in d: # lambda not really needed here, but you wanted value to # be callable instead of just an attribute s.value = (lambda r=d[k]: r) yield k return iter1(self.d) a = {1:5,2:6,3:7} it = kviter(a) for b in it: print b, it.value() >>> ## working on region in file /usr/tmp/python-15915wBw... 1 5 2 6 3 7 From aleax at mail.comcast.net Sat Jan 7 01:13:23 2006 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 6 Jan 2006 22:13:23 -0800 Subject: Spelling mistakes! References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> Message-ID: <1h8ri7o.1p05k5rvar4zfN%aleax@mail.comcast.net> KraftDiner wrote: ... > Frankly how are you ever to know if this type of error is occuring? . Alex From duncan.booth at invalid.invalid Mon Jan 23 13:03:42 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jan 2006 18:03:42 GMT Subject: list comprehention References: Message-ID: Mathijs wrote: > Op 20 jan 2006 vond Duncan Booth : >> Or in other words, define a function to return a dictionary >> containing a count of the number of occurrences of each element in >> the list (this assumes that the list elements are hashable). Then you >> just add up the values in the test list making sure each count is >> limited to no higher than the reference count. > > Thanks. Though I don't know much about python (yet), this is more or > less the way I'de do it the language I'm more comfortable with (object > pascal), and I wouldn't label this as a pythonic solution. I could be > wrong, though:) > I'm curious what you think isn't pythonic about this solution? From steve at REMOVETHIScyber.com.au Mon Jan 2 20:08:41 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 03 Jan 2006 12:08:41 +1100 Subject: Python or Java or maybe PHP? References: <1136144930.290622.111730@g43g2000cwa.googlegroups.com> <1h8hws4.z8ye5p3m14ruN%aleax@mail.comcast.net> <1136180656.710369.102120@z14g2000cwz.googlegroups.com> <863bk66tdt.fsf@bhuda.mired.org> Message-ID: On Mon, 02 Jan 2006 19:35:10 -0500, Mike Meyer wrote: > What SPARK papers I have > found concentrate more on correctness than productivity: IIRC, they > claim millions of lines of production code with no errors. Writing error-free code is easy. That's just a matter of incremental improvement of error-full code. Writing error-free code *the first time* is hard. One wonders how many edit-compile-test cycles it takes to get these millions of lines of error-free code. -- Steven. From steve at REMOVETHIScyber.com.au Wed Jan 18 17:15:55 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 19 Jan 2006 09:15:55 +1100 Subject: check to see if value can be an integer instead of string References: <1137549772.543188.69240@g44g2000cwa.googlegroups.com> <1137586997.546906.228510@g14g2000cwa.googlegroups.com> Message-ID: On Wed, 18 Jan 2006 04:23:17 -0800, nephish wrote: > it isn't really that i will want to change it to an integer anyway. the > script uses a table to reference a value to a key, if the key is a > group of letters, that code tells the script to do something. if the > value is a number, it means an equipment failure. The thing is, all the > values come out as strings (they are read from a text file). > so what you put first with the try/except looks like my best answer. def do_this(): print "Do this" def do_that(): print "Doing something else" code_table = { "abc": do_this, "def": do_that, "xyz": do_this } error_table = { "001": "Broken widget", "002": "Overloaded doohickey"} if code_table.has_key(value_from_hardware): code_table[value_from_hardware]() else: try: print error_table[value_from_hardware] except KeyError: raise CustomHardwareError("Unknown value!") -- Steven. From roccomoretti at hotpop.com Wed Jan 11 10:44:36 2006 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 11 Jan 2006 09:44:36 -0600 Subject: New Python.org website ? In-Reply-To: References: Message-ID: Roy Smith wrote: > Steve Holden wrote: > >>http://beta.python.org > > All I can say is, "Wow!". If nothing else, it will forever eliminate the > idea that the web site doesn't look professional. It's almost *too* slick. I agree with the "too slick" impression. The "learn why" pictures particularly unnerve me. It looks like a marketing team with a focus group got ahold of the website. Great for reaching the PHB crowd. I'm not sure what J. Random Hacker will think though. From iladijas at gmail.com Thu Jan 12 12:04:21 2006 From: iladijas at gmail.com (fynali) Date: 12 Jan 2006 09:04:21 -0800 Subject: How to remove subset from a file efficiently? Message-ID: <1137085461.300279.82480@f14g2000cwb.googlegroups.com> Hi all, I have two files: - PSP0000320.dat (quite a large list of mobile numbers), - CBR0000319.dat (a subset of the above, a list of barred bumbers) # head PSP0000320.dat CBR0000319.dat ==> PSP0000320.dat <== 96653696338 96653766996 96654609431 96654722608 96654738074 96655697044 96655824738 96656190117 96656256762 96656263751 ==> CBR0000319.dat <== 96651131135 96651131135 96651420412 96651730095 96652399117 96652399142 96652399142 96652399142 96652399160 96652399271 Objective: to remove the numbers present in barred-list from the PSPfile. $ ls -lh PSP0000320.dat CBR0000319.dat ... 56M Dec 28 19:41 PSP0000320.dat ... 8.6M Dec 28 19:40 CBR0000319.dat $ wc -l PSP0000320.dat CBR0000319.dat 4,462,603 PSP0000320.dat 693,585 CBR0000319.dat I wrote the following in python to do it: #: c01:rmcommon.py barredlist = open(r'/home/sjd/python/wip/CBR0000319.dat', 'r') postlist = open(r'/home/sjd/python/wip/PSP0000320.dat', 'r') outfile = open(r'/home/sjd/python/wip/PSP-CBR.dat', 'w') # reading it all in one go, so as to avoid frequent disk accesses (assume machine has plenty memory) barredlist.read() postlist.read() # for number in postlist: if number in barrlist: pass else: outfile.write(number) barredlist.close(); postlist.close(); outfile.close() #:~ The above code simply takes too long to complete. If I were to do a diff -y PSP0000320.dat CBR0000319.dat, catch the '<' & clean it up with sed -e 's/\([0-9]*\) * PSP-CBR.dat it takes <4 minutes to complete. I wrote the following in bash to do the same: #!/bin/bash ARGS=2 if [ $# -ne $ARGS ] # takes two arguments then echo; echo "Usage: `basename $0` {PSPfile} {CBRfile}" echo; echo " eg.: `basename $0` PSP0000320.dat CBR0000319.dat"; echo; echo "NOTE: first argument: PSP file, second: CBR file"; echo " this script _does_ no_ input validation!" exit 1 fi; # fix prefix; cost: 12.587 secs cat $1 | sed -e 's/^0*/966/' > $1.good cat $2 | sed -e 's/^0*/966/' > $2.good # sort/save files; for the 4,462,603 lines, cost: 36.589 secs sort $1.good > $1.sorted sort $2.good > $2.sorted # diff -y {PSP} {CBR}, grab the ones in PSPfile; cost: 31.817 secs diff -y $1.sorted $2.sorted | grep "<" > $1.filtered # remove trailing junk [spaces & <]; cost: 1 min 3 secs cat $1.filtered | sed -e 's/\([0-9]*\) * $1.cleaned # remove intermediate files, good, sorted, filtered rm -f *.good *.sorted *.filtered #:~ ...but strangely though, there's a discrepancy, the reason for which I can't figure out! Needless to say, I'm utterly new to python and my programming skills & know-how are rudimentary. Any help will be genuinely appreciated. -- fynali From brianc at temple.edu Mon Jan 16 12:51:38 2006 From: brianc at temple.edu (Brian Cole) Date: Mon, 16 Jan 2006 12:51:38 -0500 Subject: Extracting results from a large hotshot profile In-Reply-To: <43CBE154.2090907@vrplumber.com> References: <54b165660601160704i4c8e97f1jeeb1970930edd793@mail.gmail.com> <43CBC6F6.1020201@rogers.com> <54b165660601160905v3ce32a57w209be28de4fc938f@mail.gmail.com> <43CBE154.2090907@vrplumber.com> Message-ID: <54b165660601160951t6484ed44k22595853d5c2ecb@mail.gmail.com> Tried replacing sys.getrecursionlimit() with 40,000. Choked with the same error, just took longer to get there. It looks like depth is not reset to zero after the yield: if (not i%yieldCount) and i: yield i, files, functions Should it be? On 1/16/06, Mike C. Fletcher wrote: > Brian Cole wrote: > > >Thanks for the tip. I got the following error message when trying to > >run your profiler. > > > > > ... > > > File "c:\Documents and Settings\coleb2\My Documents\software\Python24\Lib\site > >-packages\runsnakerun\hotshotreader.py", line 95, in loadHotshot > > localDeltas[depth] = 0 > >IndexError: index out of bounds > > > > > ... > > >As the traceback shows I'm running this on Windows. I'm gonna go > >wrestle with installing wxPython and Numeric on my Linux box and see > >if that makes a difference. > > > > > Not likely. The hotshotreader module is creating an array of > sys.getrecursionlimit() long integers to store the accumulated local > times. It does the same to track the number of frames. Most likely > your main program is setting sys.getrecursionlimit explicitly and as a > result it winds up with a larger possible stack. You can try replacing > the sys.getrecursionlimit() calls with some big number (say 40,000, or > just multiply the recursion limit by 10 or 20 if you like) and see if > that solves the problem. Probably should allow for setting the value on > the command-line I guess. I suppose there may also be cases where a > recursive call to the interpreter gets a whole separate stack... or > maybe there's something going on with threads intermixing to create > greater depth. > > Let me know if that helps, > Mike > > -- > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > > From greg.kujawa at gmail.com Sun Jan 22 13:41:13 2006 From: greg.kujawa at gmail.com (gregarican) Date: 22 Jan 2006 10:41:13 -0800 Subject: Tkinter Mouse Cursor Message-ID: <1137955273.348456.273720@z14g2000cwz.googlegroups.com> Checking a couple of examples I tried changing the Tkinter mouse cursor to indicate a busy state while my app is pushing/pulling xmlrpc data. It doesn't seem to make a difference as I don't notice the cursor actually change in the span of the 3-5 second transaction. I tried changing the cursor of the root widget, the toplevel widget, etc. all to no avail. Is there something really basic I'm overlooking? Is it enough to just change the state and that's it, or do I have to explictly refresh things? From sw at wordtech-software.com Wed Jan 11 18:38:01 2006 From: sw at wordtech-software.com (Kevin Walzer) Date: Wed, 11 Jan 2006 18:38:01 -0500 Subject: Python+tkinter errors on OSX In-Reply-To: References: Message-ID: <343e8$43c596db$4275d90a$15903@FUSE.NET> John Chambers wrote: > Sp my latest adventure is attempting to use python's Tkinter module on a > few machines. > On my PB (OSX 10.3.9), I got the following confusing results: > > /Users/jc: python > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import Tkinter > Traceback (most recent call last): > File "", line 1, in ? > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/Tkinter.py", > line 38, in ? > import _tkinter # If this fails your Python may not be configured > for Tk > ImportError: No module named _tkinter >>>> ^D > /Users/jc: ls -l > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/*inter* > > -rw-r--r-- 1 root wheel 154289 13 Sep 2003 > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/Tkinter.py > > -rw-r--r-- 1 root wheel 262073 13 Sep 2003 > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/Tkinter.pyc > > -rw-r--r-- 1 root wheel 262073 13 Sep 2003 > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/Tkinter.pyo > > /Users/jc: > > So I'm trying to discover what's going wrong here, and how to fix it. > It does appear that Tkinter has been "installed", in some weak sense > of the term. Under /System/Library/... there's a lib-tk directory, and > it contains some Tkinter.* files. Furthermore, python's import command > clearly looked there and did something with the expected Tkinter.py > file. But whatever it did was clearly not enough, because something > called "_tkinter" was expected but not found. > > I also experimented with PATH and PYTHONPATH, to no apparent > effect on anything. > > Anyone here know how to diagnose and/or fix this? What's it trying > to tell me? I have a feeling that it's there somewhere, but the proverbial > ducks aren't lined up quite right. > > (Or maybe this isn't the right NG for such questions. If so, what might > be a better one?) You probably don't have Tcl/Tk installed. A package for 10.3 is available at http://tcltkaqua.sourceforge.net. -- Cheers, Kevin Walzer, PhD WordTech Software - "Tame the Terminal" http://www.wordtech-software.com sw at wordtech-software.com From fredrik at pythonware.com Mon Jan 9 09:50:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Jan 2006 15:50:24 +0100 Subject: Help with dynamic attributes. References: <1136817573.798749.112050@g43g2000cwa.googlegroups.com> Message-ID: "Mr.Rech" wrote: > class foo(object): > def __init__(self, list_of_lists): > self.lol = list(list_of_lists) > > for i in range(len(list_of_lists)): > exec 'self.x%d = self.lol[%d]' % (i, i) > > self.shape = tuple(len(item) for item in self.lol) generator expressions are anonymous functions, and the "self" in that line is a free variable (that is, it belongs to an outer scope). Python uses static analysis to identify free variables, and that doesn't mix well with exec. > Any better way to get the same attributes I got with the exec statement? use setattr(self, name, value) From bokr at oz.net Sun Jan 8 22:51:19 2006 From: bokr at oz.net (Bengt Richter) Date: Mon, 09 Jan 2006 03:51:19 GMT Subject: Newline at EOF Removal References: Message-ID: <43c1d82e.603168840@news.oz.net> On Sun, 08 Jan 2006 17:10:01 -0600, "Alex Nordhus" wrote: > > >I am looking for a way to strip the blank line and the empty newline at >the end of the text file. I can get the blank lines removed from the >file but it always leaves the end line (which is blank) as a newline. My >code is here and it works but leaves the newline at the end of the file. >How do I get rid of it? > >import re >f = open("oldfile.txt") >w = open("newfile.txt", "wt") >for line in f.readlines(): > line = re.sub(r'^\s+$', '', line) > > > w.write(line) > >w.close() > >I have tried everything I know and still falling short. Any help? > First, you don't need re for that, and second, why write a zero-length ''? It might even confuse some file system. You don't need readlines either. Try (untested) # open f and w as before [1] for line in f: if line.strip(): w.write(line) # write only non-blank lines [1] BTW, I didn't see the 't' mode in http://docs.python.org/lib/built-in-funcs.html description of open/file, but I have a nagging doubt about saying it's not valid. Where did you see it? Regards, Bengt Richter From arkestra at gmail.com Sun Jan 8 05:55:48 2006 From: arkestra at gmail.com (arkestra) Date: 8 Jan 2006 02:55:48 -0800 Subject: PIL implementation In-Reply-To: References: <1136618430.148279.247980@z14g2000cwz.googlegroups.com> Message-ID: <1136658279.401634.3610@f14g2000cwb.googlegroups.com> The error message is --> "Syntax error" and it highlights the last "else" statement. thanks for the reply. From robin at reportlab.com Thu Jan 19 11:25:54 2006 From: robin at reportlab.com (Robin Becker) Date: Thu, 19 Jan 2006 16:25:54 +0000 Subject: reportlab - ttf justify In-Reply-To: <43cfa91d$0$20789$9b4e6d93@newsread4.arcor-online.net> References: <43cfa91d$0$20789$9b4e6d93@newsread4.arcor-online.net> Message-ID: <43CFBD92.7090503@chamonix.reportlab.co.uk> maeckle wrote: > hi, > > i'm working with reportlab since a couple of weeks and i managed to > create quite nice pdfs... > there is a little problem though. since i have to create english and > russian content, i use the utf8 support of registered ttf's. the only > thing is that it does not support the justify-alignment in paragraph > flowables! > is there a way to fix that? > > thanks alot > jm Hi, you'll get better response from the reportlab-users list at http://two.pairlist.net/mailman/listinfo/reportlab-users The ttf support has been significantly improved in an svn branch. re-ask on that list giving your current version. I believe the problem with ttf justification was related to using space as a splitting character in dynamically subsetted fonts. Someone posted a fix for that problem to the users list and I think that has gone in to the code now, but I'm not sure if it is on the stable branch or not. -- Robin Becker From david.murmann at rwth-aachen.de Wed Jan 11 15:44:35 2006 From: david.murmann at rwth-aachen.de (David Murmann) Date: Wed, 11 Jan 2006 21:44:35 +0100 Subject: Reading from input file. In-Reply-To: <1136939500.529772.49980@z14g2000cwz.googlegroups.com> References: <1136939500.529772.49980@z14g2000cwz.googlegroups.com> Message-ID: <42l91aF1juvhhU1@news.dfncis.de> hi! i find it rather hard to understand your problem, but i'll try anyway: paczkow at gmail.com schrieb: > So.. for my future Python script, the input data are in form of: > 1 > 1233.2E-3 2123.2323 2E+2 3453.3E+1 > 1233.2E-3 2123.2323 2E+2 3453.3E+1 > 1233.2E-3 2123.2323 2E+2 3453.3E+1 > 2 > 1233.2E-3 2123.2323 2E+2 3453.3E+1 > 1233.2E-3 2123.2323 2E+2 3453.3E+1 > 1233.2E-3 2123.2323 2E+2 3453.3E+1 > and so on... are these 1's and 2's there to indicate different files, or do they really appear in the input files? > The number 1 and 2 and so on, are the numbers of measurments, which are > different in number depending on analyzed case. So sometimes it could > be 3 and sometimes 1000 or more. > > What I want to achieve, I want to compare or rather get difference > between two similar input files. I tried to work with "readline" > command, however it is hard to use it (for me) since input files are > different in its size (3,1000 or more input points). Therefore, I > decided to ask you for help how to do it. Esspecially how to make that > python script which will be reading data, each line, and each column > of input file and therefore will compare it with different input file > giving finally difference size between each measures for example: > First data at point 1 minus first data from point 1 from different > input file: > (1233.2E-3) - (1233.3E-3) = -0.1E-3 well, from what i understood you might try something like this: ------------------------------- from itertools import izip # iterate over two files at once (stopping at the shorter ones end) for lines in izip(file('inputfile1'), file('inputfile2')): # split the lines into columns columns = [line.split() for line in lines] # calculate and print the difference of the individual entries for x, y in izip(*columns): print float(x)-float(y), print ------------------------------- if this (or something similar) does not work for you, you could take a look at the difflib module: http://docs.python.org/lib/module-difflib.html hope that helps, David. From deets at nospam.web.de Tue Jan 31 13:16:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 31 Jan 2006 19:16:14 +0100 Subject: Question about idioms for clearing a list References: Message-ID: <449nrpF13n66U1@uni-berlin.de> Steven Watanabe wrote: > I know that the standard idioms for clearing a list are: > > (1) mylist[:] = [] > (2) del mylist[:] > > I guess I'm not in the "slicing frame of mind", as someone put it, but > can someone explain what the difference is between these and: > > (3) mylist = [] > > Why are (1) and (2) preferred? I think the first two are changing the > list in-place, but why is that better? Isn't the end result the same? No. Consider this simple example: class Foo(object): def __init__(self, all_my_thingies): self.all_my_thingies = all_my_thingies things = [1,2,3,4,5] f = Foo(things) things = [] # I've been robbed print f.all_my_thingies # or not? The reason is that l = [] just rebinds a new object (a list, but it could be anything) to a name, while l[:] = [] will alter the object _referred_ to by l. That is a HUGE difference! Diez From peter at engcorp.com Tue Jan 3 21:25:11 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Jan 2006 21:25:11 -0500 Subject: Calling GPL code from a Python application In-Reply-To: <86irt0g3fz.fsf@bhuda.mired.org> References: <86irt0g3fz.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > What I *can't* do is distribute it (or work derived from it, etc.) > unless the entire work being distributed is under the GPL (unless the > license has changed recently, *not* a GPL-compatible license, but the > GPL itself), and meets the requirements of the that license. In > particular, if I distribute an application that has to be dynamically > linked with a GPL'ed library to run, I need to distribute my > application under the terms of the GPL. Is that really true, precisely as written? It should be possible to distribute code which does have to be dynamically linked with a GPL'ed library in order to run *without* having to distribute under the GPL, provided your distribution *does not include* the GPL'ed library. Am I totally misremembering that the terms of the GPL talk only about *distributing* GPLed code, not about using it, and certainly not about writing other applications which might require it but which might have entirely non-compatible licenses. (Depending on one's definition of "application", you could still be right because what I describe -- a program that can't run without adding something else to it first -- might not be considered an application by some people. I wonder what they'd call it though.) -Peter From reply.in.the.newsgroup at my.address.is.invalid Wed Jan 25 07:14:05 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 25 Jan 2006 13:14:05 +0100 Subject: Trying to understand logging.Filter Message-ID: <98qet1tuql7ar7pkkskodqd88f3prs2gdl@4ax.com> I'd expect the program below to put only one line with "Eat me" in the log file. However, I get this with Python 2.4.2 in WingIDE on Windows XP: Eat me Ignore me My understanding is: 1. Event "Ignore me" is logged to logger 'spam'. 2. Logger 'spam' has no handler associated with it, so this logger doesn't do anything with the event. 3. The event is dispatched to the root logger as well, since this is an ancestor of 'spam'. This works as expected, since the event "Eat me" is logged by the root logger. 4. The root logger has a Filter, which requires the logger of the event to be 'ham', or offspring thereof. 'spam' is not offspring of 'ham' in the dotted name hierarchy, so the event should be ignored. So why does "Ignore me" end up in the logfile? What am I missing? import logging rootLogger = logging.getLogger() rootLogger.addHandler(logging.FileHandler(r'C:\Scratch\SiteChecker\Sitechecker.log')) rootLogger.addFilter(logging.Filter('ham')) rootLogger.setLevel(logging.DEBUG) logging.getLogger('ham.eggs').info("Eat me") logging.getLogger('spam').info("Ignore me") logging.getLogger().info("Ignore me too") logging.shutdown() -- Ren? Pijlman Wat wil jij worden? http://www.carrieretijger.nl From mwm at mired.org Sun Jan 15 03:11:27 2006 From: mwm at mired.org (Mike Meyer) Date: Sun, 15 Jan 2006 03:11:27 -0500 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1137111113.310683.178770@o13g2000cwo.googlegroups.com> <86r77av1am.fsf@bhuda.mired.org> <86slrqt8u7.fsf@bhuda.mired.org> Message-ID: <868xthud00.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 14 Jan 2006 23:26:40 -0500, Mike Meyer wrote: >>> I have no problem with that. Some objects are mutable and can change >>> their value >> If the object *is* the value, how can it change to be a different value >> without also changing to be a diffent object? > Because that's what they do. > Think of it this way: objects are the memory location, the value is the > particular pattern of bits at that memory location. Just because you flip > a couple of bits at location N, changing the value, the location doesn't > change. Ok. So when you say "the object is the value", you're *really* saying "the memory location is the pattern of bits it holds." Except that a memory location is an address, which is a pattern of bits. In general, this won't be the same pattern of bits as the memory location holds. So you're actually claiming that an object is two different patterns of bits at the same time. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From theller at python.net Tue Jan 10 11:06:18 2006 From: theller at python.net (Thomas Heller) Date: Tue, 10 Jan 2006 17:06:18 +0100 Subject: AW: Calling foreign functions from Python? ctypes? References: Message-ID: <8xto83ut.fsf@python.net> "Gerald Klix" writes: > I read the whol email thread carefully and could not find any sentence by > Guido, which states that he does not accept ctypes for the standard library. > He just declined to rewrite winreg. Did I miss something? Maybe I misinterpreted what he wrote myself. Ok, I'll propose on python-dev to include ctypes into core python. Thomas From peter at engcorp.com Thu Jan 26 19:30:09 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Jan 2006 19:30:09 -0500 Subject: generating method names 'dynamically' In-Reply-To: <5f56302b0601261620i78103beex76838a8311844b63@mail.gmail.com> References: <5f56302b0601261608v2920ebb4y64af75696f35fc33@mail.gmail.com> <5f56302b0601261620i78103beex76838a8311844b63@mail.gmail.com> Message-ID: Daniel Nogradi wrote: > Thanks for all the replies, it became clear that I need to look into > getattr, __getattr__ and __call__. I'll do that, but since you asked, > here is the thing I would like to do in a little more detail: > > My database has 1 table with 2 fields, one called 'name' and the other > one called 'age', let's suppose it has the following content, but this > content keeps changing: > > Alice 25 > Bob 24 > > ----------- program1.py ---------------- > > class klass: > > # do the stuff with getattr using the database > # but in a way that after the database changes > # I don't need to rewrite this part > > > inst = klass() > > ---------- program2.py ------------------ > > import program1 > > # This should print 'Hello, my name is Bob and I'm 24' > program1.inst.Bob() Where is the code that should print that? The code has to be defined, and is presumably outside your database, so *that* is the method you need to call, not something generated dynamically at runtime. > # This should print 'Hi, I'm 25 and I'm Alice' > program1.inst.Alice() That actually prints something different... did you intentionally change the order? In other words, is the code that generates that output for Alice() actually different than the code for Bob() (and if so, where would you define it?) or did you just write the example imprecisely? Ultimately, I think the question here is "why do you want to do that"? Normally you would just make Bob and Alice parameters, as in: program1.inst.output("Alice") # prints whatever you wanted above program1.inst.output("Bob") # prints whatever you wanted above, assuming the differences in the two outputs was inadvertent program1.inst.output("John") # raise exception -Peter From fredrik at pythonware.com Tue Jan 17 16:42:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Jan 2006 22:42:47 +0100 Subject: magical expanding hash References: <1137478291.342584.83030@g47g2000cwa.googlegroups.com><1137523154.114949.69610@f14g2000cwb.googlegroups.com><7xk6cyvd94.fsf@ruckus.brouhaha.com><1137528218.895388.112560@g49g2000cwa.googlegroups.com><7x1wz6wq1n.fsf@ruckus.brouhaha.com> <1137533023.895288.277950@z14g2000cwz.googlegroups.com> Message-ID: "braver" wrote > Exactly, << as in C++/ruby streams. But notice the extra checks needed > to see whether we want a new leaf which is an array or a number, or we > create an intermediate hash level. Would the checks look the same in > python? we? trust me, the number of people who think it's a good idea to write perl- inspired ruby and run that code in a python interpreter is very limited. and even if you succeed in persuading someone else to write the code for you, don't you think your users will find out pretty quickly that python's not ruby ? From aleax at mail.comcast.net Sun Jan 29 17:59:12 2006 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 29 Jan 2006 14:59:12 -0800 Subject: StringIO proposal: add __iadd__ References: <7xvew2btmj.fsf_-_@ruckus.brouhaha.com> <1h9xi9t.1hoitag1slka55N%aleax@mail.comcast.net> <7xslr6ofk0.fsf@ruckus.brouhaha.com> <1h9xjhz.11a72vh123sfyxN%aleax@mail.comcast.net> <7xoe1uoehx.fsf@ruckus.brouhaha.com> Message-ID: <1h9xkyn.10k76gs1r5sd16N%aleax@mail.comcast.net> Paul Rubin wrote: > aleax at mail.comcast.net (Alex Martelli) writes: > > But why can't I have perfectly polymorphic "append a bunch of strings > > together", just like I can now (with ''.join of a list of strings, or > > StringIO), without caring whether the strings are Unicode or > > bytestrings? > > I see that 'a' + u'b' = u'ab', which makes sense. I don't use Unicode > much so haven't paid much attention to such things. Is there some > sound reason cStringIO acts differently from StringIO? I'd expect > them to both do the same thing. I believe that cStringIO tries to optimize, while StringIO doesn't and is thereby more general. > > As for extending cStringIO.write I guess that's > > possible, but not without breaking compatibility ... you'd > > need instead to add another couple of methods, or wait for Py3k. > > We're already discussing adding another method, namely __iadd__. > Maybe that's the place to put it. Still need another method to 'getvalue' which can return a Unicode string (currently, cStringIO.getvalue returns plain strings only, and it might break something if that guarantee was removed). That being said, if the only way to use a StringIO was to call += or __iadd__ on it, I would switch my recommendation away from it and towards "just join the sequence of strings". Taking your example: temp_buf = StringIO() for x in various_pieces_of_output(): v = go_figure_out_some_string() temp_buf += v final_string = temp_buf.getvalue() it's just more readable to me to express it final_string = ''.join(go_figure_out_some_string() for x in various_pieces_of_output()) Being able to use temp_buf.write(v) [like today, but with StringIO, not cStringIO] would still have me recommending it to newbies, but having to explain that extra += just tips the didactical balance. It's already hard enough to jump ahead to a standard library module in the middle of an explanation of strings, just to explain how to concatenate a bunch... Yes, I do understand your performance issues: Nimue:~/pynut alex$ python2.4 -mtimeit -s'from StringIO import StringIO' 's=StringIO(); s.writelines(str(i) for i in range(33)); x=s.getvalue()' 1000 loops, best of 3: 337 usec per loop Nimue:~/pynut alex$ python2.4 -mtimeit -s'from cStringIO import StringIO' 's=StringIO(); s.writelines(str(i) for i in range(33)); x=s.getvalue()' 10000 loops, best of 3: 98.1 usec per loop Nimue:~/pynut alex$ python2.4 -mtimeit 's=list(); s.extend(str(i) for i in range(33)); x="".join(s)' 10000 loops, best of 3: 99 usec per loop but using += instead of writelines [[actually, how WOULD you express the writelines equivalent???]] or abrogating plain-Python StringIO would not speed up the cStringIO use (which is already just as fast as the ''.join use). Alex From __peter__ at web.de Wed Jan 25 14:59:35 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Jan 2006 20:59:35 +0100 Subject: float formatting References: <1138217547.670044.29970@g43g2000cwa.googlegroups.com> Message-ID: Brian wrote: > I am a bit stuck with a float formatting issue. What I want to do is > print a float to the screen with each line showing one more decimal > place. Here is a code snip that may explain it better: > > #!/usr/bin/env python > > num1 = 32 > num2 = 42.98765 > > for i in range(2,7): > print "|" + "%10.3f" % num2 + "|" > > In the for loop, is the line with my difficulty. In a perfect world it > would read something like this: > > for i in range(2,7): > print "|" + "%10.if" % num2 + "|" #where i would be the iteration > and the num of decimal places > > However, if I do that I get errors saying that all args were not > converted during string formatting. An escaped 'i' does not work > either. In the http://en.wikipedia.org/wiki/Best_of_all_possible_worlds you have to use a '*' instead of the 'i': >>> for i in range(2, 7): ... print "|%10.*f|" % (i, 42.98765) ... | 42.99| | 42.988| | 42.9877| | 42.98765| | 42.987650| You can replace the width constant with a star, too: >>> "|%*.*f|" % (10, 3, 1.23456) '| 1.235|' See http://docs.python.org/lib/typesseq-strings.html for the full story. Peter From pmaupin at gmail.com Thu Jan 5 11:15:10 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 5 Jan 2006 08:15:10 -0800 Subject: Occasional OSError: [Errno 13] Permission denied on Windows In-Reply-To: <1136476700.356482.319110@g44g2000cwa.googlegroups.com> References: <1136476700.356482.319110@g44g2000cwa.googlegroups.com> Message-ID: <1136477710.335625.98040@z14g2000cwz.googlegroups.com> Alec Wysoker wrote: > Using Python 2.3.5 on Windows XP, I occasionally get OSError: > [Errno 13] Permission denied when calling os.remove(). This can > occur with a file that is not used by any other process on the > machine, and is created by the python.exe invocation that is > trying to delete it. It can happen with various pieces of my > system - almost anywhere I try to delete a file. The previous company I worked for had a real-time virus scanner that would cause problems like this. Drove me nuts because I never could get them to shut the dang thing off. Regards, Pat From raNOsky at deveSPAMler.com Mon Jan 16 14:37:45 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Mon, 16 Jan 2006 20:37:45 +0100 Subject: Shrinky-dink Python (also, non-Unicode Python build is broken) References: <1137435559.804230.11820@g44g2000cwa.googlegroups.com> Message-ID: Larry Hastings wrote: > First and foremost: turning off Py_USING_UNICODE *breaks the build* > on Windows. Probably nobody does that nowadays. My own feeling (but I don't have numbers for backing it up) is that the biggest size in the .DLL is represented by things like the CJK codecs (which are about 800k). I don't think you're gaining that much by trying to remove unicode support at all, especially since (as you noticed) it's going to be maintenance headhache. > Second of all, the dumb-as-a-bag-of-rocks Windows linker (at least > the one used by VC++ under MSVS .Net 2003) *links in unused static > symbols*. If I want to excise the code for a module, it is not > sufficient to comment-out the relevant _inittab line in config.c. > Nor does it help if I comment out the "extern" prototype for the > init function. As far as I can tell, the only way to *really* get > rid of a module, including all its static functions and static data, > is to actually *remove all the code* (with comments, or #if, or > whatnot). What a nosebleed, huh? This is off-topic here, but MSVC linker *can* strip unused symbols, of course. Look into /OPT:NOREF. > So in order to build my *really* minimal python24.dll, I have to hack > up the source something fierce. It would be pleasant if the Python > source code provided an easy facility for turning off modules at > compile-time. I would be happy to propose something / write a PEP > / submit patches to do such a thing, if there is a chance that such > a thing could make it into the official Python source. However, I > realize that this has terribly limited appeal; that, and the fact > that Python releases are infrequent, makes me think it's not a > terrible hardship if I had to re-hack up each new Python release > by hand. You're not the only one complaining about the size of Python .DLL: also people developing self-contained programs with tools like PyInstaller or py2exe (that is, programs which are supposed to run without Python installed) are affected by the lack of a clear policy. I myself complained before, especially after Python 2.4 got those ginormous CJK codecs within its standard DLL, you can look for the thread in Google. The bottom line of that discussion was: - The policy about what must be linked within python .dll and what must be kept outside should be proposed as a PEP, and it should provide guidelines to be applied also for future modules. - There will be some opposition to the obvious policy of "keeping the bare minimum inside the DLL" because of inefficiencies in the Python build system. Specifically, I was told that maintaining modules outside the DLL instead of inside the DLL is more burdesome for some reason (which I have not investigated), but surely, with a good build system, switching either configuration setting should be the matter of changing a single word in a single place, with no code changes required. Personally, I could find some time to write up a PEP, but surely not to pick up a lengthy discussion nor to improve the build system myself. Hence, I mostly decided to give up for now and stick with recompiling Python myself. The policy I'd propose is that the DLL should contain the minimum set of modules needed to run the following Python program: ------------------- print "hello world" ------------------- There's probably some specific exception I'm not aware of, but you get the big picture. -- Giovanni Bajo From fredrik at pythonware.com Tue Jan 31 07:29:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Jan 2006 13:29:20 +0100 Subject: backreference in regexp References: Message-ID: Sch?le Daniel wrote: > Hello @all, > > >>> p = re.compile(r"(\d+) = \1 + 0") > >>> p.search("123 = 123 + 0") > > 'search' returns None but I would expect it to > find 123 in group(1) > > Am I using something that is not supported by Python > RegExp engine or what is the problem with my regexp? plus matches one or more instances of the previous item. to make it match a plug sign, you have to escape it: p = re.compile(r"(\d+) = \1 \+ 0") From robert.kern at gmail.com Fri Jan 20 18:45:21 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Jan 2006 17:45:21 -0600 Subject: saxutils.XMLGenerator and CDATA In-Reply-To: <1137798889.054921.82480@g49g2000cwa.googlegroups.com> References: <1137798889.054921.82480@g49g2000cwa.googlegroups.com> Message-ID: chris wrote: > Confused somewhat xml newbie. I'm trying to output xml with a CDATA > section, using saxutils.XMLGenerator, but the output contains escaped > '<' and '>' and '&' from the CDATA element. Shouldn't it be spit out > intact? > > Here's code and output: > > from xml.sax import saxutils > import sys > handler = saxutils.XMLGenerator(sys.stdout) > handler.startDocument() > handler.startElement('sometag', {}) > handler.characters('xxx]]>') > handler.endElement('sometag') > handler.endDocument() > > Produces: > > <![CDATA[x&<>xxx]]> > > I was expecting to see > > xxx]]> > > What am I doing wrong here? The crud is markup, not character data. You are passing it in as characters (hence the method's name "characters"), so saxutils.XMLGenerator is treating it as such. sections are intended for human authoring, not computer authoring. If you want to keep your sanity, just don't do it. -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From __peter__ at web.de Tue Jan 10 04:25:32 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Jan 2006 10:25:32 +0100 Subject: Failing unittest Test cases References: <43c2a204$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > There has been a bit of discussion about a way of providing test cases > in a test suite that should work but don't.??One?of?the?rules?has?been > the test suite should be runnable and silent at every checkin.??Recently > there was a checkin of a test that should work but doesn't.??The > discussion got around to means of indicating such tests (because the > effort of creating a test should be captured) without disturbing the > development flow. > > The following code demonstrates a decorator that might be used to > aid this process.??Any?comments,?additions,?deletions? Marking a unittest as "should fail" in the test suite seems just wrong to me, whatever the implementation details may be. If at all, I would apply a "I know these tests to fail, don't bother me with the messages for now" filter further down the chain, in the TestRunner maybe. Perhaps the code for platform-specific failures could be generalized? Peter From peter at engcorp.com Tue Jan 17 19:12:22 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 17 Jan 2006 19:12:22 -0500 Subject: Running DOS App on win32 via python over ssh In-Reply-To: References: Message-ID: James Stroud wrote: > The program in question, in case anyone doesn't understand this problem, > is lem: > > http://spitswww.uvt.nl/web/fsw/mto/lem/lemdos.zip Well, LEM.EXE calls RTM.EXE and RTM.exe contains signs of not being a pure DOS program. It contains references to USER.EXE and KERNEL.EXE (probably some old Windows 95 thing? ... LEM dates from 1997), and the following string: ''' You have attempted to run Windows in enhanced mode while running in a shell under a protected mode program. This is not a compatible configuration. Run Windows in standard mode instead (win /S). ''' Possibly what you are trying to do is not going to be feasible... -Peter From steve at REMOVETHIScyber.com.au Fri Jan 13 20:49:10 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 14 Jan 2006 12:49:10 +1100 Subject: Why can't I "from module import *" except at module level? References: <1137176252.350535.162200@g49g2000cwa.googlegroups.com> Message-ID: On Fri, 13 Jan 2006 10:17:32 -0800, Mudcat wrote: > I have a directory structure that contains different modules that run > depending on what the user selects. They are identical in name and > structure, but what varies is the content of the functions. They will > only need to be run once per execution. ... > So if the user selects Sys1 during execution, I want to import the > modules using "from *" and the run the content of those files. > > Now the way my program is set up, it is very important that I be able > to "from Sys1 import *" and not "import Sys1". Then change the way your program is set up :-) Seriously, "from module import *" is generally a bad idea. Not always, but generally, and in this specific instance I'm not sure that your use case is one of those exceptions. However, be that as it may be, on to solving your problem: When you "import foo" or "from module import foo", the name foo is bound in the local scope, not global. In other words, the name foo will then only exist inside the function. So this does not work: >>> def local_import(): ... import string ... >>> local_import() >>> string.whitespace Traceback (most recent call last): File "", line 1, in ? NameError: name 'string' is not defined However this does work as you would expect: >>> def func_import(): ... global math ... import math ... >>> func_import() >>> math.sin See http://docs.python.org/ref/import.html for more detail on what happens when you import. Keep in mind that it states that "from module import *" in function blocks is explicitly stated to be an error, and in Python 2.3 a warning is raised: >>> def wild_import(): ... from math import * ... :1: SyntaxWarning: import * only allowed at module level > The names of the > functions inside are passed in from somewhere else and the program > requires those function names to be globally scoped. > > So I have a function that looks like this: > > def importModules( type ): > cwd = os.getcwd() > path = cwd + "\\" + type > sys.path.append(path) > > from security import * > > Obviously this is not working and I get a syntax error at runtime. Should security be defined somewhere? > So > without this functionality, how do I target modules to import in other > directories after program execution has begun? I'd consider putting your import logic into a module of its own, at the module-level and not inside a function. Then just call "from importer import *" in the top level of your code and I think that should meet your needs. -- Steven. From paddy3118 at netscape.net Tue Jan 24 13:53:08 2006 From: paddy3118 at netscape.net (Paddy) Date: 24 Jan 2006 10:53:08 -0800 Subject: list comprehention In-Reply-To: References: <1137703821.688635.156100@g47g2000cwa.googlegroups.com> Message-ID: <1138128788.436432.234930@o13g2000cwo.googlegroups.com> Umm, My answer is not correct, but for a different reason; it seems you need the length of my previous answer, thus: PythonWin 2.4 (#60, Feb 9 2005, 19:03:27) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> ref = [3, 3, 1, 1, 3] >>> lst=[5, 1, 4, 5, 3] >>> answer = len([ val for val in set(ref) for x in range(min(lst.count(val), ref.count(val)))]) >>> answer 2 >>> - Paddy. From fredrik at pythonware.com Wed Jan 18 11:07:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Jan 2006 17:07:02 +0100 Subject: Addressing the modem via pyserial References: Message-ID: Doru-Catalin Togea wrote: > In the HyperTerminal which comes with Win XP Pro, I can set up a > connection to COM3 and there type the 'atdt1234' command. It works (I get > a call since I have the modem connected to a device with a phone on it). even without pressing enter? > My question is actually: will an at-command like 'atdt1234' translate to > ser.write('atdt1234')? try ser.write('atdt1234\r\n') or just ser.write('atdt1234\n') From xivulon at gmail.com Tue Jan 17 08:04:46 2006 From: xivulon at gmail.com (ago) Date: 17 Jan 2006 05:04:46 -0800 Subject: Sudoku solver: reduction + brute force In-Reply-To: <1137249051.163980.162970@g14g2000cwa.googlegroups.com> References: <1137196845.482476.217160@f14g2000cwb.googlegroups.com> <1137249051.163980.162970@g14g2000cwa.googlegroups.com> Message-ID: <1137503086.552665.209810@g43g2000cwa.googlegroups.com> > But to inflate my ego beyond the known universe, here is my solver > (that solves the avove mentioned grid reasonably fast). I suppose the > only difference is that is uses 3, rather than 2, rules to simplify > before starting tree-like search. Thanks for the nice problem and the nice post. The issue with my code was not due to the reduction algorithms used. In fact we used exactly the same set of rules, my Cell.solve was equivalent to your Clean1 method and my Cell.skim was equivalent to your Clean3 method (except that my algorithm was only doing "for (o1, o2) in ((out1,out2),)", but it did not make any difference in most cases). The real problem was due to an external loop inside my solveByBruteForce which was absolutely useless. I fixed that and now everything seems ok. It can solve the mentioned grid in about half the time. You can see my amended code in the link above. From claudio.grondi at freenet.de Tue Jan 3 11:07:20 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 03 Jan 2006 17:07:20 +0100 Subject: [OT] - Requesting Comments for Process Definition and Presentation In-Reply-To: References: Message-ID: Ilias Lazaridis wrote: > comp.lang.python / comp.lang.ruby > > - > > I would like to ask for feedback on the Process Definition and > Presentation. > > Essentially this is exactly what I've myself specialized to do. > > But I cannot apply the process to my own system. > > I ask here, as I have criticized those 2 groups publically - and would > like to give the possibility to reverse the criticism - again publically. > > - > > Please simply visit > > http//:lazaridis.com > > what do you like? > > what do you dislike? > > are there points that you do not understand? What is the goal of your posting and the intended purpose of http://lazaridis.com ??? I can't see anything at this site what would make sense to me. Claudio > > do you have any suggestions for terminology changes? > > do you have any other suggestion (marketing, presentation, etc.)? > > - > > You can use private email, the anonymous contact-form on the website and > of course this medium here (c.l.p / c.l.r). > > Your feedback is _very_ important to me. > > Greetings! > > .. > From mjteigen at gmail.com Tue Jan 17 10:56:16 2006 From: mjteigen at gmail.com (mjteigen) Date: 17 Jan 2006 07:56:16 -0800 Subject: forced spaces when inserting a variable between strings Message-ID: <1137513376.740667.102040@f14g2000cwb.googlegroups.com> I'm very new at Python, but have been trying it in conjunction with CGI. I've encountered a problem that I'm pretty sure is a trivial one, but I don't know enough Python to work it out. Here's an example. Imagine that I have a file named "5.jpg" in the same directory as this Python script: print "content-type: text/html\n" number = 5 print "" My goal is print out ''. However, when I view the source on the generated html page, I see this: In other words, that "5" has a space tacked on either side of it, and of course a browser can't find the file. Is there a way I can avoid the tacking of spaces on either side of a variable inserted between two strings? TIA :-) -- m j teigen From modelnine at bit-bukket.org Wed Jan 4 04:31:35 2006 From: modelnine at bit-bukket.org (Heiko Wundram) Date: Wed, 04 Jan 2006 10:31:35 +0100 Subject: How to generate (enumerate) 2**N tuples representing all vertices of unit hypercube in N-dimensional hyperspace ? References: <1136337708.410196.263220@o13g2000cwo.googlegroups.com> <7x1wzolq93.fsf@ruckus.brouhaha.com> Message-ID: Claudio Grondi wrote: > Heiko Wundram wrote: >> def perm(n): >> return (tuple(((1,-1)[(t>>i)%2] for i in xrange(n))) >> for t in xrange(2L**n)) > > Isn't this kind of coding beeing the result of suffering from the > post-pyContest illness syndrom? I don't think what Paul Rubin posted is the sign of pyContest illness, as I use two-level generator expressions such as this quite often in my code. Why I didn't give this as the reponse to the OP was because it seems that he's not that familiar with Python to be able to read this efficiently and grap the concept behind the implementation immediately, that's why I thought an explicit loop was in order. But for any sufficiently advanced Python coder, I don't think this is unreadable in the least. --- Heiko. From iapain at gmail.com Fri Jan 13 14:14:02 2006 From: iapain at gmail.com (iapain) Date: 13 Jan 2006 11:14:02 -0800 Subject: timeout a process Message-ID: <1137179642.630869.3170@z14g2000cwz.googlegroups.com> Hello, I am trying to build and infinite loop handler in python 2.4 on windows platform. The problem is that i want to create a process and forcely kill/timeout after 2 sec to handle infinite loop in a gcc complied exe on cygwin. something like below os.system("mycpp.exe") # this exe is compiled with g++ and having an infinite loop I wish to terminate this after 2 sec. I've tried Watchdog and deamon thread.. but nothing seem to work here. From steve at REMOVETHIScyber.com.au Mon Jan 23 05:25:17 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 23 Jan 2006 21:25:17 +1100 Subject: OT: excellent book on information theory References: <7xr777j17s.fsf@ruckus.brouhaha.com> <1137669604.810904.277480@g47g2000cwa.googlegroups.com> <7xu0byo0ml.fsf@ruckus.brouhaha.com> <1137837201.668700.55340@o13g2000cwo.googlegroups.com> <7x64odz6rw.fsf@ruckus.brouhaha.com> <1137933236.390342.249140@z14g2000cwz.googlegroups.com> <43iefuF1nrvgdU1@individual.net> Message-ID: On Sun, 22 Jan 2006 17:15:21 -0500, val bykoski wrote: > The existing (formal) language, being helpful, was created > hundreds years ago and of course needs an update. How does this follow? Why does something need to be updated *just* because it was created hundreds of years ago? Isn't it more likely that having passed the test of time, something that old is going to be better than some untested, untried new invention? -- Steven. From markus_REMOVEwankusALL_CAPS at hotmail.com Wed Jan 18 09:10:14 2006 From: markus_REMOVEwankusALL_CAPS at hotmail.com (Markus Wankus) Date: Wed, 18 Jan 2006 14:10:14 GMT Subject: New Python.org website ? In-Reply-To: References: Message-ID: Well I think the new site is definitely a step in the right direction. The old site is definitely "utilitarian" and is quite functional, but not "sexy". And I think the whole point is to (hopefully) have a good first impression of the language and community by "impressing" (if you will) new users with a cool website. So, while I agree that the beta site does have a definite "nineties corporate" feel to it, I think it is better than the old site and would like to throw some kudos to whoever spent the time on it. I'm sure it wasn't a small job. At any rate, opinions will always differ. You are always going to get the people who want a cool flash-based animated site with 3D stereo surround sound, and the other end of the spectrum where you will be flamed if you do anything more than hand-code the html, on Unix machines only, using Vim or Emacs, ensuring it has a gray or neutral beige background, *and* uses the default font giving that classic 1981 "university professor who refuses to use anything except Netscape Navigator" feel. I use Eclipse a lot in my day-job and there are debates like this all the time whenever a change is made in the UI, but usually sanity (and quite nice-looking software, BTW) are the result. FWIW - they have just re-done the L&F of their website as well. I must admit I like it (eclipse.org), but others do not - I'm sure we'll hear from them shortly - ;-). To each his own. I think it would definitely be cool to use a Python-based web app for the site. Plone is alright, but has a definite Plone approach that can be hard to shoe-horn your stuff into (although I think these guys have done an *awesome* job on their site: http://www.schooltool.org/). Zope is flexible but a beast to learn. And, well...there are just so many others. ;o) I'm still looking, myself... Markus. Tim Parkin wrote: > Leeuw van der, Tim wrote: > >> I think that in general, I don't like the fact that links to >> high-profile users are featured so prominently. That row of pictures >> there looks good to me 'as such' but linking there to 'success stories' >> feels, dunno, perhaps a bit cheesy to me. (That might be just my dutch >> upbringing) >> I would certainly want to see such links somewhere on the front page, >> just not so prominently. >> >> > Possibly so... however in my experience, selling python to people is > made a lot easier by being able to say 'look these guys are using it'. > This may not help sell it to programmers, but as a businessman trying to > sell my programming services, it's exceptionally important. > >>> btw do you have a problem with using nasa or astrazeneca as example >>> >>> >> high >> >> >>> profile users? >>> >>> >> As I said, I don't like them. We're not a commercial company trying to >> promote itself to potential buyers. But that's too a large degree a >> matter of taste. >> >> > Well I'd have to disagree with yout on one point.. 'We' may not > be a commercial company (when you talk about python as a singular unit) > but as python developers, we should be in the process of trying to > 'sell' python wherever we can. Because we aren't a commercial company, > our only 'sales' channels are the website and the developers/consultants > that use python. (I'm talking about selling in the terms of 'promoting' > or trying to persuade someone that using python is a good thing). > >> I do actually think, though, that if the Python website *is* going to >> feature such big names with such prominence, some sort of approval from >> these organizations should be requested? That they don't mind being used >> a a Python reference story? >> >> > The approval is already there (see pythonology success stories). > >> About what could be there... Link to the even calender, or >> recent/upcoming event.. That is one to stay, I think. >> I think it would be good to have a link there too development >> environments that can be used for Python: editors, debuggers, IDEs / IDE >> extenstions, etc >> >> >> > It's difficult to summarise this in a single image. The XP image was > intended as a 'catch all' for the development environment. A different > image and title would probably achieve better results but coming up with > one or two words to sumarise that list is quite difficult. > >> A third item could perhaps be a link to the Python Package Index -- >> another thing that Python developers are likely to need. >> >> >> > The home page isn't intended to target existing python users.. and the > home page photos are mostly targetted at the sort of people that respond > well to photos. It's a dilemma that the home page has to serve two > masters, however if we have a 'developer home page' which can be > dedicated to development issues, news, planetpython links, package > libraries etc, we would have a single page that developers could bookmark. > > The only alternative was to create a separate 'marketing python' website > but it would just get ignored, especially by the people we really need > to see the 'marketing' content. > >> These things are, of course, rather developer-centered (well, >> Python-user centered...) >> Being a software developer that uses Python, I wouldn't really know what >> else to put there ;-) >> But many people might have other things they wish to put in the centre >> of atte >> > Yep, > > Thats probably why a dedicated page for developers would make more sense. > > Tim > > p.s. thanks for the comments btw.. From fuzzyman at gmail.com Wed Jan 18 11:01:35 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 18 Jan 2006 08:01:35 -0800 Subject: Can a simple a==b 'hang' in and endless loop? In-Reply-To: <1137599762.791479.26680@g47g2000cwa.googlegroups.com> References: <1137596782.678344.136630@g43g2000cwa.googlegroups.com> <1137598435.628966.266820@g47g2000cwa.googlegroups.com> <1137598595.031617.69240@f14g2000cwb.googlegroups.com> <1137599762.791479.26680@g47g2000cwa.googlegroups.com> Message-ID: <1137600095.235420.22750@g43g2000cwa.googlegroups.com> Ok... so I'm now assuming that the information about '==' provided by the above gentleman *and* that I understand it correctly. The only confusion in C (which doesn't have classes) is that two list (like) objects can't be tested by value - only identity. In Java, comparing strings using '==' compares for identity not equality (IIUC), giving *plenty* of room for confusion. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From steve at REMOVETHIScyber.com.au Fri Jan 13 21:48:57 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 14 Jan 2006 13:48:57 +1100 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1137111113.310683.178770@o13g2000cwo.googlegroups.com> Message-ID: On Thu, 12 Jan 2006 16:11:53 -0800, rurpy wrote: > It would help if you or someone would answer these > five questions (with something more than "yes" or "no" :-) > > 1. Do all objects have values? All objects ARE values. Some values themselves are complex objects which in turn contain other values, e.g. if I execute: L = [None, 1, "hello"] I have created a name 'L' which is bound to ("has the value of") a list with three items. The first item has the value of ("is the object") None, the second has the value of ("is the object") 1, and the third is the string "hello". > 2. What is the value of object()? These seems complicated because we are using the same word ("object") for both the generic programming term, the class (strictly type, although the difference is not important), and the instance itself. Let's make it less confusing by using a case where the three things are different: class Foo: pass Foo is a class. Classes are (generic programming term) objects. Foo() returns an instance of the Foo class. Instances are (generic programming term) objects. The value of Foo() is the instance. Why? int(data) returns an instance of int, and str(data) returns an instance of str. It makes sense to say that the value of the int instance 1 is one, the value of str instance "abc" is the string "abc", and so forth. So we'd like to talk the same way about more complex objects: the value of an instance is itself. Hence the value of Foo() is the Foo instance at some particular memory location. In this specific case, Foo() creates an object with very little behaviour and and no distinguishing characteristics except their location in memory, where as ints like 1 2 and 7 are easily distinguished. Now let's return to (non-generic) object(). object is (as well as the generic programming term) a class (strictly type, but the difference is unimportant). object() returns an instance of class object: >>> object() So the value of object() is some particular instance (of type object). > 3. If two objects are equal with "==", does that > mean their values are the same? Intuitively yes, but not necessarily: >>> 3.0 == 3 True (We want the float 3.0 to be equal to the int 3, but we can distinguish between them by something more than their location in memory.) You can define a custom class: class EqualAll: def __eq__(self, other): return True but that's a pathological case. > 4. Are object attributes part of an object's type > or it's value, or something else? (I think the first.) The type/class defines what attributes (generic) objects have. The value of the attribute lives with the instance itself (that's why fred.attribute and barney.attribute can be different). Whether you want to say the attribute itself is part of the class or part of the instance value is, in my opinion, not a useful question. The answer depends on which way you want to look at it. > 5. The (only?) way to get an object's value is to > evaluate something (a name or a "reference"(*) > that refers to the object. I can't think of any other way to get at an object except by accessing that object, or even what it would mean if there was such a way. -- Steven. From uval at rz.uni-karlsruhe.de Fri Jan 6 15:29:11 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Fri, 06 Jan 2006 21:29:11 +0100 Subject: Copy an Object (Again?) In-Reply-To: References: <1136565555.267031.85570@o13g2000cwo.googlegroups.com> Message-ID: I was not very clear about it > or even if you "could" copy instances > > class X: > def __init__(self, filename = "/path/file") > self.file = file(filename, "w+") > def modifyByteAt(offset): > self.file.tell(offset) > self.file.write("X") > > this is untested pseudocode, it should only give you an idea even when x=X() and y=copyItSomehowFrom(x) what is supposed to be copied? the whole file? but where? in your case .. what is supposed to happen with the mirrored image? should it be mirrored inplace if I recall properly in "import PIL.Image as image" if you image.open an image and want to mirror it you can create a real copy and then "save as " it into a file my 2 cents From marijuanated at gmail.com Sun Jan 15 01:37:39 2006 From: marijuanated at gmail.com (marijuanated at gmail.com) Date: 14 Jan 2006 22:37:39 -0800 Subject: Dynamically changing button text in python References: <1137254753.025111.281520@f14g2000cwb.googlegroups.com> <7xslrqxz9q.fsf@ruckus.brouhaha.com> Message-ID: <1137307059.814602.45200@f14g2000cwb.googlegroups.com> The problem is once i set the textvariable property of the button,i cannot change the text.For example, curButton = Button(root,text="Stop Server",textvariable="this") curButton.bind("",self.StopServer) def StopServer(self,event): curButton["text"] = "Start Server" #this does not work From q at q.q Thu Jan 19 11:06:55 2006 From: q at q.q (Mathijs) Date: 19 Jan 2006 16:06:55 GMT Subject: list comprehention Message-ID: Hi, Python beginner here and very much enjoying it. I'm looking for a pythonic way to find how many listmembers are also present in a reference list. Don't count duplicates (eg. if you already found a matching member in the ref list, you can't use the ref member anymore). Example1: ref=[2, 2, 4, 1, 1] list=[2, 3, 4, 5, 3] solution: 2 Example2: ref=[2, 2, 4, 1, 1] list=[2, 2, 5, 2, 4] solution: 3 (note that only the first two 2's count, the third 2 in the list should not be counted) Any suggestions or comments? Thanks. M. #my failing effort: sum([min(r.count(n)-l[:i].count(n),l.count(n)) for i,n in enumerate(l)]) #test lists import random #reference list r=[random.randint(1,5) for n in range(5)] #list l=[random.randint(1,5) for n in range(5)] From tdwdotnet at gmail.com Tue Jan 3 06:16:10 2006 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 3 Jan 2006 11:16:10 +0000 Subject: compare dictionary values In-Reply-To: References: Message-ID: <9afea2ac0601030316u7578b78r@mail.gmail.com> On 30/12/05, rbt wrote: > > What's a good way to compare values in dictionaries? I want to find > [snip] > My key-values pairs are filepaths and their modify times. I want to > identify files that have been updated or added since the script last ran. You don't need to store each file's updated time, you only need to store the last time you ran the script and to compare each file's modified time against that last-run time. Dictionaries aren't required eg: # to get files changed (added/modified) since a given date import time, os last_run = time.time() - (60*60*24*30*12) # for testing, set to one year ago changed = [x for x in os.listdir('c:/python24') if os.path.getmtime( os.path.join('c:/python24' , x)) > last_run] # script end >From your previous posts, I believe you are storing details of *every* file within a dictionary that is pickled to your hard disk, then periodically creating a new dict of *every* file and comparing it against the original dict. Then you must be updating the original dict with the new times and storing it back to disk. The above list comprehension will give the same result for files/dirs in a single directory, you just need to store the time of the last script run to disk instead. if you are walking several directories, the principle is the same, >>> last_run = time.time() - (60*60*24*30) # 1 month ago >>> for root, dirs, files in os.walk('c:/python24'): ... for name in files: ... if os.path.getmtime(os.path.join(root , name)) > last_run: ... print os.path.join(root , name) ... c:/python24\Lib\asynchat.pyc c:/python24\Lib\calendar.pyc c:/python24\Lib\gzip.pyc c:/python24\Lib\imghdr.pyc c:/python24\Lib\SimpleHTTPServer.pyc c:/python24\Lib\sndhdr.pyc c:/python24\Lib\webbrowser.pyc c:/python24\Lib\_strptime.pyc c:/python24\Lib\email\MIMEAudio.pyc c:/python24\Lib\email\MIMEImage.pyc c:/python24\Lib\email\MIMEMessage.pyc c:/python24\Lib\email\MIMEMultipart.pyc >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From enleverlesX.XmcX at XmclaveauX.com Sat Jan 28 16:24:44 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Sat, 28 Jan 2006 22:24:44 +0100 Subject: Checking free disk space on Win32 ? References: <1138434532.215444.138510@g43g2000cwa.googlegroups.com> <43db8973$0$20178$8fcfb975@news.wanadoo.fr> <1138479793.294426.159350@g49g2000cwa.googlegroups.com> Message-ID: <43dbe1a9$0$21294$8fcfb975@news.wanadoo.fr> Hi! Fun. Slow, but fun. Thanks. @-salutations Michel Claveau From pmaupin at gmail.com Mon Jan 23 18:10:13 2006 From: pmaupin at gmail.com (Patrick Maupin) Date: 23 Jan 2006 15:10:13 -0800 Subject: list comprehention References: Message-ID: <1138057813.705293.124060@o13g2000cwo.googlegroups.com> Duncan Booth showed how to solve a problem posed by Mathijs. This is very similar to Duncan's solution, except I (ab)use setdefault on a regular basis... >>> def occurrences(t): ... res = {} ... for item in t: ... res.setdefault(item,[0])[0] += 1 ... return res ... >>> ref = [2,2,4,1,1] >>> lst = [2,2,5,2,4] >>> oref = occurrences(ref) >>> sum(min(v[0],oref.get(k,[0])[0]) for (k,v) in occurrences(lst).iteritems()) 3 >>> Actually, this brings up an interesting point: >>> {}.setdefault('foo',0) += 1 SyntaxError: can't assign to function call I understand why this doesn't work, but it would sure be nice if it did. I think somebody was mentioning "mutable ints" at one point, which is basically what I abuse [0] to provide. If I were doing a lot of this in one place, I would code a mutable integer class, and then the rest of the code would get simpler. Regards, Pat From mwm at mired.org Sun Jan 8 22:12:45 2006 From: mwm at mired.org (Mike Meyer) Date: Sun, 08 Jan 2006 22:12:45 -0500 Subject: Try Python update References: <863bk87wsi.fsf@bhuda.mired.org> <86u0cisd4g.fsf@bhuda.mired.org> <1h8sii5.u2xzj21x0bk9sN%aleax@mail.comcast.net> <86fynz7qgt.fsf@bhuda.mired.org> <1h8tee4.5fe8eesbrk2wN%aleax@mail.comcast.net> <86u0cfi1u1.fsf@bhuda.mired.org> <1h8u9l1.vvry21gxrtv8N%aleax@mail.comcast.net> Message-ID: <86ace6hz6a.fsf@bhuda.mired.org> aleax at mail.comcast.net (Alex Martelli) writes: > I'm finding it hard to arrange my own experiments with Safari (I'm using > a loaner machine since my normal one[s] are all having problems and > under repair) but I'm told the solution for cursor positioning is to set > the caretPos attribute of the textarea, like for example at > ... caretPos is apparently an MS extension; it's not supported by Safari or the Gecko browsers. setSelectionRange is the standards-compliant version. It's not supported by Safari either :-(. Thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From hancock at anansispaceworks.com Thu Jan 26 10:44:52 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 26 Jan 2006 09:44:52 -0600 Subject: Using non-ascii symbols In-Reply-To: <5af1b8bc0601252312r3a71348fu23b6cfd2f61937ae@mail.gmail.com> References: <5af1b8bc0601252312r3a71348fu23b6cfd2f61937ae@mail.gmail.com> Message-ID: <20060126094452.1a09f3ca@samwise.anansi> On Thu, 26 Jan 2006 01:12:10 -0600 Runsun Pan wrote: > For the tests that I tried earlier, using han characters > as the variable names doesn't seem to be possible (Syntax > Error) in python. I'd love to see if I can use han char > for all those keywords like import, but it doesn't work. Yeah, I'm pretty sure we're talking about the future here. :-) > That depends. People with ages in the middle or older > probably have very rare experience of typing han > characters. But with the popularity of computer > as well as the development of excellent input packages, > and most importantly, > the online-chats that many teenagers hooking to, next > several geneartions can type han char easily and > comfortably. That's interesting. I think many people in the West tend to imagine han/kanji characters as archaisms that will disappear (because to most Westerners they seem impossibly complex to learn and use, "not suited for the modern world"). I used to think this was likely, although I always thought the characters were beautiful, so it would be a shame. After taking a couple of semesters of Japanese, though, I've come to appreciate why they are preferred. Getting rid of them would be like convincing English people to kunvurt to pur fonetik spelin'. Which isn't happening either, I can assure you. ;-) > One thing that is lack in other languages is the "phrase > input"---- almost every > han input package provides this customizable feature. With > all these combined, > many of youngesters can type as fast as they talk. I > believe many of them input > han characters much faster than inputting English. I guess this is like Canna/SKK server for typing Japanese. I've never tried to localize my desktop to Japanese (and I don't think I want to -- I can't read it all that well!), but I've used kanji input in Yudit and a kanji-enabled terminal. I'm not sure I understand how this works, but surely if Python can provide readline support in the interactive shell, it ought to be able to handle "phrase input"/"kanji input." Come to think of it, you probably can do this by running the interpreter in a kanji terminal -- but Python just doesn't know what to do with the characters yet. > The "side effect" of this technology advance might be that > in the future the > simplified chinese characters might deprecate, 'cos > there's no need to simplify > any more. Heh. I must say the traditional characters are easier for *me* to read. But that's probably because the Japanese kanji are based on them, and that's what I learned. I never could get the hang of "grass hand" or the "cursive" Chinese han character style. I would like to point out also, that as long as Chinese programmers don't go "hog wild" and use obscure characters, I suspect that I would have much better luck reading their programs with han characters, than with, say, the Chinese phonetic names! Possibly even better than what they thought were the correct English words, if their English isn't that good. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From bearophileHUGS at lycos.com Fri Jan 6 21:35:46 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Jan 2006 18:35:46 -0800 Subject: python speed References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133358884.407477.219560@g47g2000cwa.googlegroups.com> <438db382$0$67257$157c6196@dreader2.cybercity.dk> <_eqdnYiZUra9XxDenZ2dnUVZ_sadnZ2d@comcast.com> Message-ID: <1136601346.814687.238920@z14g2000cwz.googlegroups.com> It seems that Java JDK 1.4 (-server) HotSpot compiler sometimes (in this test, on this computer, etc.) can produce programs faster than C and Fortran ones in n-body simulations and similar stuff: http://shootout.alioth.debian.org/gp4/benchmark.php?test=nbody&lang=all http://shootout.alioth.debian.org/gp4/benchmark.php?test=spectralnorm&lang=all So maybe PyPy can become quite fast too. Bye, bearophile From http Thu Jan 19 17:15:43 2006 From: http (Paul Rubin) Date: 19 Jan 2006 14:15:43 -0800 Subject: Python on an embedded platform References: <1137704549.220864.157590@z14g2000cwz.googlegroups.com> <11t00oba2cr7g02@corp.supernews.com> <1137708406.996473.21930@g14g2000cwa.googlegroups.com> Message-ID: <7xy81beueo.fsf@ruckus.brouhaha.com> "Kay Schluehr" writes: > Yes, definitely. The smallest JVM I've seen was dedicated for an 8-Bit > AVR with 8 KByte EEPROM ( or was it Flash? ) and a 768 byte sized heap. That sounds like Javacard, which is a subset of a JVM (e.g. a minimal Javacard implementation doesn't need garbage collection). JVM's can be quite small, but not THAT small. Actually you might mean this: http://www.harbaum.org/till/nanovm/ From steve at REMOVETHIScyber.com.au Wed Jan 25 07:02:11 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 25 Jan 2006 23:02:11 +1100 Subject: file_name_fixer.py References: <1138064443.217593.29640@g44g2000cwa.googlegroups.com> <43D73680.1000000@REMOVEMEcyber.com.au> <43D73E31.6040303@REMOVEMEcyber.com.au> Message-ID: On Wed, 25 Jan 2006 10:37:12 +0000, Richie Hindle wrote: > > [Fredrik] >> so re.sub("([_.])\\1+", "\\1", newname) replaces runs consisting >> of either a . or an _ followed by one or more copies of itself, with >> a single instance of itself. > > ...and this: > >>>> def isprime(n): >>>> return n > 1 and not re.match(r'(xx+)\1+$', 'x'*n) > > finds prime numbers. > > I'll get me coat. See, now that's exactly the sort of thing that makes me wake screaming in the night. That's just deeply, deeply wrong -- I don't know what's worse, that it *works*, or that somebody thought of it. :-) Thank you to Fredrik for trying to teach me something, but it is 11pm on the night before a public holiday (Australia Day), my house feels like an oven, and in the last three hours I've suddenly started coming down with a cold -- in the middle of our summer. So this is not the time for me to try to learn anything new. -- Steven. From vivsar_guve at yahoo.co.uk Tue Jan 31 04:53:58 2006 From: vivsar_guve at yahoo.co.uk (Vivek Kumar) Date: Tue, 31 Jan 2006 01:53:58 -0800 (PST) Subject: Request for suggesstions and comments Message-ID: <20060131095358.26261.qmail@web26306.mail.ukl.yahoo.com> Hi all, I have to write a network server (sort of) and I am looking for your valuable comments. Currently I have written a prototype in VB6 but it can only handle up to 30 or so clients. I need to upgrade the application so that it can handle up to 1000-1500 clients at a time (later if every thing works fine then hoping for 5000-6000 client). The scenario is as follows. 1. An server application (above mentioned app) will be listening on a particular port for client connection. The client will be connecting to it using TCP protocol. 2. The server will be continuously sending a trigger pulse to all the clients connected on this port (say every 3 sec). 3. Each client (in my case another app written in VB6) will be sending a string of approx. 70-75 chars every 1 sec. 4. Each string will contain a start and an end char. 5. Each string will contain some data eg. first 4 char acc. id, next 10 char user name etc. 6. As the data may come in small chunks (due to the nature of network and buffering), it will be the server's responsibility to buffer incoming data and look for valid strings in buffer. 7. Once the server software find a valid string in buffer, it should extract the valid string from the buffer and parse it (extract the data in the string) and insert into a database server with timestamps (in my case SQL Server 2k). 8. The server will also have to send the valid string to two other ports (one for showing status in GUI) and second to a remote client which will further parse the data and do some processing on the data (currently written in VB). There can be around 20-30 such clients. For GUI there will be around 5-10 clients. 9. The remote clients to whom the valid string is being sent can also send some data to be sent back to the clients from whom we are receiving data per sec. For this the remote client will send data to the server and the servers responsibility will be again to parse this data and send it to the appropriate client on the other side. This string can also be intended for broadcasting, in that case we may need to send data to all the clients on other side. This is a general view for the application. Now here are the issues on which I am requesting your comments and suggestions. Q. Is it possible to write an application for this kind of server activity in Python? I mean whether Python will be suitable for this kind of high activity load, real time app? Q. How much time it can take (approx.) to develop such kind of server? Q. Do we need multi threading? If so, then whether the Socket modules will be safe to use with multi threading? Q. What modules for networking (socket ?), database access etc should I use? Currently as I am just planning about the solutions so I don't have much of questions in my mind. But if it is possible to write this kind of app in Python easily (relative to C family of language ;) , then surely I will have some more questions for experts out there ;) . As for me, I have written some small scripts in Python. I have used Tk for GUI, PostgreSQL and Mysql for my Database, some CGI programming with apache, reporting using reportlab. But that was a long time back (some 2 yrs back). After that I joined one organization working on M$ platforms. So, since then I am working in VB6 only. But I am confident that after 7-10 days of study I can again start working with Python (Which is of course my favorite language :) . Eagerly waiting for your comments and suggestions. TIA, Vivek Kumar __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rurpy at yahoo.com Wed Jan 4 01:11:11 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 3 Jan 2006 22:11:11 -0800 Subject: itertools.izip brokeness In-Reply-To: <1136347652.750432.11980@g14g2000cwa.googlegroups.com> References: <1136283553.577340.232330@z14g2000cwz.googlegroups.com> <1136347652.750432.11980@g14g2000cwa.googlegroups.com> Message-ID: <1136355071.207151.41120@f14g2000cwb.googlegroups.com> wrote: > But here is my real question... > Why isn't something like this in itertools, or why shouldn't > it go into itertools? Never mind... I just read this in the source code for itertools.imap: 1) Itertools are designed to be easily combined and chained together. Having all tools stop with the shortest input is a unifying principle that makes it easier to combine finite iterators (supplying data) with infinite iterators like count() and repeat() (for supplying sequential or constant arguments to a function). 2) In typical use cases for combining itertools, having one finite data supplier run out before another is likely to be an error condition which should not pass silently by automatically supplying None. 3) The use cases for automatic None fill-in are rare -- not many functions do something useful when a parameter suddenly switches type and becomes None. 4) If a need does arise, it can be met by __builtins__.map() or by writing: chain(iterable, repeat(None)). 5) Similar toolsets in Haskell and SML do not have automatic None fill-in. I know I shouldn't post this but... Jezuz Freekin' Cripes!! This is the crap that drives me up a wall using Python. I spent 10 hours writing the original non-working code, finding the probllem, posting to c.l.p, writing working replacement code. Why? Because some pythonic devdude sitting in his god throne declared that I don't need to do what I needed to do!! 1) Itertools are designed to be easily combined and chained together. Having all tools stop with the shortest input is a unifying principle that makes it easier to combine finite iterators (supplying data) with infinite iterators like count() and repeat() (for supplying sequential or constant arguments to a function). There is not a count or a repeat to be seen anywhere in my code. So let's see... I am prevented from using a tool I need to use so that I will have the ability to use some tools which I don't need. Wow, that makes a lot of f'ing sense. 2) In typical use cases for combining itertools, having one finite data supplier run out before another is likely to be an error condition which should not pass silently by automatically supplying None. Just plain wrong. Files are very commonly used iterators, and the ttypical case with them is that they are of different lengths. And I have run into plenty of non-file iterators of differing lengths. Declaring by fiat that these are all error cases and shouldn't be permitted is bullshit. 3) The use cases for automatic None fill-in are rare -- not many functions do something useful when a parameter suddenly switches type and becomes None. So allow a caller-specified fill. Not rocket science. 4) If a need does arise, it can be met by __builtins__.map() or by writing: chain(iterable, repeat(None)). Yes, if youre a python guru. I don't even understand the code presented in this thread that uses chain/repeat, let alone have any chance of writing it in less than a week. For the average python user, having a tool to iterate to the longest input is about 4 orders of magnitude simpler. 5) Similar toolsets in Haskell and SML do not have automatic None fill-in. What the hell does this have to do with anything? Maybe there are other reasons like they have alternate, better ways of doing the same thing? Does the fact the C++ lack some feature justify leaving it out of Python? Python is basically a pretty good language but there are these big time holes in it. I spend WAY too much time trying to figure out how to do something that should be easy, but isn't because someone thought that it might hurt the "purity" of the language or violate some "principle". pissed-offedly-yr's, rurpy From continium at gmail.com Sun Jan 29 19:59:27 2006 From: continium at gmail.com (continium at gmail.com) Date: 29 Jan 2006 16:59:27 -0800 Subject: Help saving output onto a text file In-Reply-To: <43dd6085$1@nntp0.pdx.net> References: <1138578429.949295.251670@g43g2000cwa.googlegroups.com> <43dd6085$1@nntp0.pdx.net> Message-ID: <1138582767.552539.127830@g49g2000cwa.googlegroups.com> I tried using the sys.stdout method and it worked. It seems pretty simple but I dont understand the simple method you posted. Thanks for the help, I'll mess around with it and keep on learning. From greg.kujawa at gmail.com Mon Jan 9 00:47:36 2006 From: greg.kujawa at gmail.com (gregarican) Date: 8 Jan 2006 21:47:36 -0800 Subject: PyQt Access Violations References: <1136639214.049776.239010@g14g2000cwa.googlegroups.com> Message-ID: <1136654446.750847.67050@g47g2000cwa.googlegroups.com> Phil Thompson wrote: > What version of Qt? > > Phil It's version 2.3.0 non-commerical for Windows. My OS is Windows 2000 Professional SP4. Using this same version of Qt for a Ruby-based implementation of a similar app I didn't experience the access violation crashes when invoking the setCentralWidget() method. It's sporadic, as the crashes sometimes take 2-3 widget opens/closes to happen. Other times it takes more. Trying to debug the crashes the script never makes it past this method. Here's an excerpt from the Dr. Watson error log: function: QGList::findRef 39d2dd42 807c240800 cmp byte ptr [esp+0x8],0x0 ss:00c09513=00 39d2dd47 7407 jz QString::fromUtf8+0x8a (39d36850) FAULT ->39d2dd49 8b4108 mov eax,[ecx+0x8] ds:00cd9f51=48001500 39d2dd4c 33d2 xor edx,edx 39d2dd4e eb06 jmp QString::fromUtf8+0x90 (39d36856) 39d2dd50 8b4110 mov eax,[ecx+0x10] ds:00cd9f51=48001500 39d2dd53 8b5114 mov edx,[ecx+0x14] ds:00cd9f51=48001500 39d2dd56 56 push esi 39d2dd57 85c0 test eax,eax 39d2dd59 740e jz QString::fromLatin1+0xb (39d36869) 39d2dd5b 8b30 mov esi,[eax] ds:007ad4d8=00858340 39d2dd5d 3b742408 cmp esi,[esp+0x8] ss:00c09513=00000000 39d2dd61 7406 jz QString::fromLatin1+0xb (39d36869) 39d2dd63 8b4008 mov eax,[eax+0x8] ds:012873be=00000000 *----> Stack Back Trace <----* FramePtr ReturnAd Param#1 Param#2 Param#3 Param#4 Function Name 0012F664 1E057D56 089FE908 00857948 00000001 088FAAD0 !QGList::findRef 0012F6C8 00000001 00000000 00000000 007A5234 00779288 !PyCFunction_Call From plahey at alumni.caltech.edu Mon Jan 30 21:55:13 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 30 Jan 2006 18:55:13 -0800 Subject: Deterministic destruction and RAII idioms in Python References: <1138652299.351951.36780@z14g2000cwz.googlegroups.com> <1138669303.907322.272550@g47g2000cwa.googlegroups.com> <7xoe1tmcnd.fsf@ruckus.brouhaha.com> Message-ID: <1138676113.401636.188290@z14g2000cwz.googlegroups.com> Hi Paul, >> I looked at pep-0343, it looks interesting. It is not what I really >> want (deterministic destruction) > >I think it's better. Is there something specific you have in mind that makes you say that? I am not a python expert, so I probably do not understand all the implications of the proposal. What I got out of it is summarized by: with EXPR as VAR: BLOCK The translation of the above statement is: abc = (EXPR).__context__() exc = (None, None, None) VAR = abc.__enter__() try: try: BLOCK except: exc = sys.exc_info() raise finally: abc.__exit__(*exc) Which, looks like you have a constructor (__enter__) and a destructor (__exit__), which you can always count on being called. I am not sure how that is better than C++-style RAII. Now, in the interest of full disclosure, there is this __context__ method which I don't really follow... maybe there is something important there I should know about? At first glance, it seems to me that the syntax gets slightly ackward as you encapsulate more resources. From the proposal: with opened(filename, "w") as f: with stdout_redirected(f): print "Hello world" which is not as nice as simply creating two objects and having them destroyed in the reverse order that they were created in when they go out of scope. Is it big deal... no. I am definitely going to have to play with this stuff a while before I really know its strengths and weakness relative to C++-style RAII. If you have some examples, however, to support your feeling that it is better than C++-style RAII, I would love to see them. I am always eager to learn new stuff! Again, I am not criticizing Python or the proposal. I like Python and I like the capabilities that the proposal implies (to the extent that I understand them :-) ). As far as PyPy goes, thanks for reminding me of that. I had forgotten about that one. Cheers! From mwm at mired.org Wed Jan 4 17:55:22 2006 From: mwm at mired.org (Mike Meyer) Date: Wed, 04 Jan 2006 17:55:22 -0500 Subject: Worthwhile to reverse a dictionary References: <1134582611.355566.198990@g14g2000cwa.googlegroups.com> Message-ID: <86ek3nd2n9.fsf@bhuda.mired.org> crc writes: > I assume your talking about building a new dictionary with the key and > value pair switched. I have seen no built in function to do this but I > have found a way to create another dictionary that is the inverse of > the first. Note that you can't reliable "reverse" a dictionary. That's because you can put anything in a dictionary, but some things can't be used as keys to a dictionary. > when your redy to build a revers dictionary you semply do the folowing > b={} > for x in a: > temp_idx=a[x] > b[temp_idx]=x You can do it with a single list comprehension: b = dict([(x, y) for y, x in a.iteritems()]) http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From hancock at anansispaceworks.com Wed Jan 4 01:25:46 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 4 Jan 2006 00:25:46 -0600 Subject: check if class really implements api? In-Reply-To: <1136321818.063009.224660@o13g2000cwo.googlegroups.com> References: <1136321818.063009.224660@o13g2000cwo.googlegroups.com> Message-ID: <20060104002546.0a786219@samwise.anansi> On 3 Jan 2006 12:56:58 -0800 "Karsten W." wrote: > with the zope.interface module I can query if my class > claims to implement my API. This > is what the method implementedBy is for. > > However, I find myself constantly changing the API and I > am looking for a more reliable way > to check my implementation classes. Is there a way to > check if at least all function > names of the API are defined by the class and if their > parameter lists fit the API? A way > to test this would save me a lot of time.. You want: Zope 2.5.1: Interface.verify.verify_class_implementation or Zope 3.x: zope.interface.verify You'll want to read the source modules for documentation and usage, as I don't think these are particularly well documented anywhere else. They are somewhat different in API between the two interface implementations, but both do essentially the same thing -- they check the class against the interface object. This will only tell you whether the methods are there and have the same calling profile -- it obviously can't tell you whether they do what you expect (or indeed do anything at all). But I had the same problem you're having, and I found them useful. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From exarkun at divmod.com Tue Jan 10 18:56:26 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 10 Jan 2006 18:56:26 -0500 Subject: How can I test if an argument is a sequence or a scalar? In-Reply-To: <1136935102.587013.67160@o13g2000cwo.googlegroups.com> Message-ID: <20060110235626.31401.111654377.divmod.quotient.65@ohm> On 10 Jan 2006 15:18:22 -0800, sandravandale at yahoo.com wrote: >I want to be able to pass a sequence (tuple, or list) of objects to a >function, or only one. Generally it's better to keep your API consistent. If you are going to take sequences, only take sequences. Don't try to make the interface more convenient by allowing single values to be passed in by themselves: it just leads to confusion and complexity. > >It's easy enough to do: > >isinstance(var, (tuple, list)) Above you said sequences - what about strings (buffers, unicode and otherwise) or arrays or xrange objects? Those are all sequences too, you know. > >But I would also like to accept generators. How can I do this? Ah, but generators *aren't* sequences. I'm guessing you really want to accept any "iterable", rather than any sequence. The difference is that all you can do with an iterable is loop over it. Sequences are iterable, but you can also index them. I hope you heed my advice above, but in case you're curious, the easiest way to tell an iterable from a non-iterable is by trying to iterate over it. Actually, by doing what iterating over it /would/ have done: >>> iter("hello world") >>> iter([1, 2, 3, 4]) >>> def foo(): ... yield 1 ... yield 2 ... yield 3 ... >>> iter(foo()) This works for anything that is iterable, as you can see. However, it won't work for anything: >>> iter(5) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence This is "duck typing" in action. Hope this helps, Jean-Paul From grante at visi.com Fri Jan 27 16:24:57 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 27 Jan 2006 21:24:57 -0000 Subject: writing large files quickly References: <11tkt7e4ehdo309@corp.supernews.com> <11tkv50bnr2daff@corp.supernews.com> <11tl32lfgj92od9@corp.supernews.com> Message-ID: <11tl3t9dvgmpe90@corp.supernews.com> On 2006-01-27, rbt wrote: > OK I finally get it. It's too good to be true :) Sorry about that. I should have paid closer attention to what you were going to do with the file. > I'm going back to using _real_ files... files that don't look > as if they are there but aren't. BTW, the file 'size' and > 'size on disk' were identical on win 2003. That's a bit > deceptive. What?! Windows lying to the user? I don't believe it! > According to the NTFS docs, they should be drastically > different... 'size on disk' should be like 64K or something. Probably. -- Grant Edwards grante Yow! Where's th' DAFFY at DUCK EXHIBIT?? visi.com From plahey at alumni.caltech.edu Mon Jan 30 15:18:19 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 30 Jan 2006 12:18:19 -0800 Subject: Deterministic destruction and RAII idioms in Python Message-ID: <1138652299.351951.36780@z14g2000cwz.googlegroups.com> I have been dabbling in Python for a while now. One of the things that really appeals to me is that I can seem to be able to use C++-style RAII idioms to deal with resource management issues. For those that have no idea what I am talking about (I learn a lot reading posts on subjects in which I am clueless), consider the following code snippet: for line in file(name): ..print line, This is nice and clean because I don't have to worry about cleaning up after myself. If I can't rely on the destructor for the file object to close the file, I must write the code like this: file_obj = file(name) for line in file_obj: ..print line, file_obj.close() not nearly as nice. Depending on the type of work you do, this can be no problem or a major headache when exceptions are thrown into the mix. Python objects have destructors so it seems that the original intent was to support deterministic destruction (destructors are not very useful in most GC'ed languages since you never know when or even if they will be called). The problem is that other implementations of Python (Jython and IronPython) do not support deterministic destruction. So we are left with a problem: is deterministic destruction an implementation detail of CPython that can go away at anytime, or is it an official property of the language. Giving up deterministic destruction in Python would be a real blow for me, since it is one of its unique features among GC'ed languages. So what's the deal, can I rely on it in "mainstream" Python or am I out of luck here? From peter at engcorp.com Thu Jan 19 23:16:57 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Jan 2006 23:16:57 -0500 Subject: Python code written in 1998, how to improve/change it? In-Reply-To: <43d05ac2@usenet01.boi.hp.com> References: <1137697284.101739.30690@z14g2000cwz.googlegroups.com> <43d00460@usenet01.boi.hp.com> <1137714834.195896.180550@g47g2000cwa.googlegroups.com> <43d0596e@usenet01.boi.hp.com> <43d05ac2@usenet01.boi.hp.com> Message-ID: Carl Cerecke wrote: > Carl Cerecke wrote: >>Ah. Well, my post suggested, as one option, the callables call >>each other directly. > > Doh! No I didn't. And they shouldn't. Otherwise the call stack > gets out of hand. But I did suggest that each callable representing a > state set a global variable, just before it returns, to the callable > representing the next state to be called. Still no map required. Just a > while loop. In any case, the function call/return is wasted cycles. I believe the more modern approach to this is to use generators in some way, yield each other as the next state. This way you avoid all almost all the function call overhead (the part that takes significant time, which is setting up the stack frame) and don't have to resort to bytecode hacks for better performance. Of course, if you have a state machine with many small states each doing a tiny bit of processing and you're still concerned over performance, you probably should be looking into Pysco or Pyrex and avoid making your code really unreadable. -Peter From steve at holdenweb.com Sun Jan 15 02:48:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Jan 2006 07:48:28 +0000 Subject: More than you ever wanted to know about objects [was: Is everything a refrence or isn't it] In-Reply-To: References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <8664ozd1bm.fsf@bhuda.mired.org> <43BC806A.1040201@REMOVEMEcyber.com.au> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1137111113.310683.178770@o13g2000cwo.googlegroups.com> <1h969v1.e4u2nb1yrmevfN%aleax@mail.comcast.net> Message-ID: Steven D'Aprano wrote: > On Sun, 15 Jan 2006 06:08:43 +0000, Steve Holden wrote: > > >>I just wish Mike Meyer and Steven D'Aprano were close enough that you >>could bang their heads together. In the same playground, perhaps? :-) > > > Well, after such a deeply-reasoned, well-explained refutation of my > position, what can I do but admit that everything I said was clearly wrong > and Steve Holden is right? > > I wasn't trying to refute your position, nor Mike's, but to imply that I wished you would both take what appeared to have become an essentially private disagreement to a private channel. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From timr at probo.com Tue Jan 10 03:09:14 2006 From: timr at probo.com (Tim Roberts) Date: Tue, 10 Jan 2006 08:09:14 GMT Subject: string to datetime parser? References: <1136665908.546504.131800@z14g2000cwz.googlegroups.com> Message-ID: "beza1e1" wrote: >Is there a library which can parse strings and output a datetime >object? It should be as magical as possible and allow things like: >12:30 >tomorrow >10.10.2005 >02-28-00 >28/03/95 And given 10/03/95, is that a date in mid-March, or in early October? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From w.damen at gmail.com Mon Jan 30 06:16:02 2006 From: w.damen at gmail.com (Rinzwind) Date: 30 Jan 2006 03:16:02 -0800 Subject: Mouse manipulation In-Reply-To: <1138597094.598261.322620@g14g2000cwa.googlegroups.com> References: <1138597094.598261.322620@g14g2000cwa.googlegroups.com> Message-ID: <1138619762.424707.87380@g43g2000cwa.googlegroups.com> arkestra schreef: > I am writing a script that interacts with the computer screen. > > Is there a module (either built in or add on) that would allow the > script to manipulate the mouse pointer ? -- eg right click, move two > pixels to the right, left click etc? > > thank you. pygame is able to do that. From __peter__ at web.de Wed Jan 11 14:05:29 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Jan 2006 20:05:29 +0100 Subject: how to improve this simple block of code References: <1136987885.792305.119640@f14g2000cwb.googlegroups.com> <1136988971.868299.91480@g14g2000cwa.googlegroups.com> <1136989149.626734.88040@g44g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Of?all?the ideas posted, I believe only Mark Hammond's would correctly > pass the basic obvious test cases Too bad he didn't post at all :-) Peter From roy at panix.com Wed Jan 18 09:21:52 2006 From: roy at panix.com (Roy Smith) Date: Wed, 18 Jan 2006 09:21:52 -0500 Subject: Is there a maximum length of a regular expression in python? References: <1137591911.333364.221990@z14g2000cwz.googlegroups.com> Message-ID: In article <1137591911.333364.221990 at z14g2000cwz.googlegroups.com>, olekristianvillabo at gmail.com wrote: > I have a regular expression that is approximately 100k bytes. (It is > basically a list of all known norwegian postal numbers and the > corresponding place with | in between. I know this is not the intended > use for regular expressions, but it should nonetheless work. > > the pattern is > ur'(N-|NO-)?(5259 HJELLESTAD|4026 STAVANGER|4027 STAVANGER........|8305 > SVOLV?R)' > > The error message I get is: > RuntimeError: internal error in regular expression engine I don't know of any stated maximum length, but I'm not at all surprised this causes the regex compiler to blow up. This is clearly a case of regex being the wrong tool for the job. I'm guessing a dictionary, with the numeric codes as keys and the city names as values (or perhaps the other way around) is what you want. From mwm at mired.org Thu Jan 12 10:30:41 2006 From: mwm at mired.org (Mike Meyer) Date: Thu, 12 Jan 2006 10:30:41 -0500 Subject: Why keep identity-based equality comparison? References: <1136846444.954839.58960@g47g2000cwa.googlegroups.com> <8664oshoqb.fsf@bhuda.mired.org> <86y81ofh07.fsf@bhuda.mired.org> <86u0ccf3pw.fsf@bhuda.mired.org> <86lkxm4xwl.fsf@bhuda.mired.org> <864q4a4qyd.fsf@bhuda.mired.org> Message-ID: <86zmm1h3a6.fsf@bhuda.mired.org> Antoon Pardon writes: > Op 2006-01-11, Mike Meyer schreef : >> Antoon Pardon writes: >>> Op 2006-01-11, Mike Meyer schreef : >>>> Antoon Pardon writes: >>>>> Op 2006-01-10, Mike Meyer schreef : >>>>>>> Now you can take the practical option and decide that programmatically >>>>>>> it make no sense to compare a specific couple of values and throw an >>>>>>> exception in this case, but it doesn't matter much which test you are >>>>>>> conducting at that point. >>>>>> Can you provide a case where having a test for equality throw an >>>>>> exception is actually useful? >>>>> I'm not going to bother with that. >>>> Since you're being vague about what you want, >>> I would like some consistency. Either all comparisons between objects >>> of different types throw an exception by default or none does. >> That's a very silly thing to ask for. It presumes that all types are >> the same. They aren't. > It doesn't presume anything like that. Yes it does. It presumes that all operators of all types either always make sense, or there are always situations where they don't >> It also presumes that all comparisons are the same. They aren't. > It doesn't presume that either. Yes it does. It presumes that all operators either always make sesne, or there are always situations where they don't. >> To use an overworked analogy, you might as well ask >> that you either have to peel all fruit, or that you never have to peel >> a fruit. > Bad analogy since a fruit is not a relationship. I suggest you look up the meaning of the word "analogy". >> In any case, the proposeed behavior *is* consistent. The behavior for >> all builtin types will be that comparisons that don't make sense will >> throw exceptions. > It is only consistent if you start from an inconsistent view and then > check for how consistently this view is followed. There is nothing > consistent in telling that 1 == (1,3) makes sense and 1 < (1,3) > doesn't make sense. Set theoretically both 1 and (1,3) are sets. Of course there are types for which the given behaviors don't make sense. However, we're not talking about user-defined relations on user-defined types with syntax that isn't supported by the language. We're talking about the builtin relationships defined on the builtin types. > There is a use case for things like 1 < (1,3) making sense and denoting > a total order. When you have a hetergenous list, having a total order > makes it possible to sort the list which will make it easier to > weed out duplicates. So why don't you demand a use case for the > new behaviour to counter this use case? Yes, there is. And you are perfectly free to implement a type that behaves that way if you want to. I don't need a use case to "counter" this one; I just need to show that this use case can be reasonably covered by the proposed mechanism. > IMO it would be better if it was possible to associate some kind > of order function with the container. Because the order most usefull > for comparing between two instances doesn't need to be the most usefull > order in finding an element from a container. No, it wouldn't. Order relationships are a property of the type, not the container. The order relationships are right where they belong - attached to the type. That notwithstanding, it's often practical to be able to override the order function for some specific method (and would be even if the order function were associated with the container instead of the type), so some of the methods that use order allow you to provide a function to use for them. If you really want a container type that has an order function associated with it, you can write one. If you want it made part of the language, you'll have to provide a use case. > I could impose a total order on sets, so that I can use a bisection > algorithm on a container of them, but such an order is in general > less usefull than the superset ordering when you are manipulating > sets. And you're free to implement a subclass of sets that does that. If you want to argue that the builtin sets should do that, you can - but that's unrelated to the question of how the comparison operators behave for the rest of the bulitin types. At least, it doesn't matter unless you try and force all the types and operators to be the same. >> Since we're talking about Py3K here, there is no >> "default" behavior. User-defined classes all inherit from builtin >> types, and will get the behavior of their comparison operators from >> those types. In particular, those that inherit from object will get >> objects behavior, which means they'll get equality as identity. > But if this makes any behaviour defined on objects consistent by > definition, because the only criteria you seem to have for consistency > is the inherited behaviour from object. If object would use a > random function to decide that would be consistent too, because it > would be the behaviour inherited by other classes. I don't find this > a usefull way to measure consistency. But you can use a random function to decide no matter *how* the bulitin relationships behave. That's part of the powero of Python - it doesn't impose arbitrary constraints on what you can do. You seem to think we should either disallow comparison operators from throwing exceptions, or force them to throw exceptions under some unstated conditions. But not all types are the same; some may not *have* conditions under which all relational operators need to throw an exception. And not all comparisons are the same; some may not *have* conditions under which they need to throw an exception. >>>> and won't provide >>>> examples to show why you want things to behave whatever way you want, >>>> I can't really say much else about it. >>> Did you see examples that show why Guido wants things to behave whatever >>> Guido's idea is a change from current behaviour. Each time I saw some >>> argue a change here, people seem to expect a use case from that person. >>> So why ask a use case of me and just accepy Guido's idea. >> For one thing, Guido has a long history of doing excellent Python >> design work. For another, this issue was thrashout out at length in >> comp.lang.python some years ago. What Guido proposed is inline with >> the conclusions of those discussions. > Then it should be easy to come up with the use cases and arguments pro > this idea presented then. If this idea of Guido was the result of his > briliance in language design, surely there should be arguments and > use cases to confirm that. It's no easier for me to find them than for you to find them. And I'm not guido - if you want his thoughts, you'll have to ask him. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dwelch91 at gmail.com Sun Jan 22 13:27:15 2006 From: dwelch91 at gmail.com (dwelch91 at gmail.com) Date: 22 Jan 2006 10:27:15 -0800 Subject: Concatinating PDF files In-Reply-To: <1137944561.490854.282440@g44g2000cwa.googlegroups.com> References: <1137944561.490854.282440@g44g2000cwa.googlegroups.com> Message-ID: <1137954435.164427.223540@z14g2000cwz.googlegroups.com> ReportLab maybe? http://www.reportlab.org/rl_toolkit.html From iddw at hotmail.com Wed Jan 4 18:52:25 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 04 Jan 2006 17:52:25 -0600 Subject: What's wrong with this code snippet? References: Message-ID: You've received good answers to your original question. Just a side issue... On Wed, 4 Jan 2006 22:19:27 +0000 (UTC) in comp.lang.python, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: [...] > def GenerateRandomColour(): > rn.seed() > colour = rn.choice(['C', 'P', 'Z']) > return colour I'm not sure what rn is, but it looks like a standard library random.Random object. If so, I don't think you want to seed your PRNG each time you use it -- your numbers might be much less random that way. If it is the standard library object, the PRNG is seeded when the module is first imported, so you may not need to seed it at all. Regards, -=Dave -- Change is inevitable, progress is not. From simon at brunningonline.net Wed Jan 18 07:05:10 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 18 Jan 2006 12:05:10 +0000 Subject: making objects unassignable "read-only" (especially when extending) In-Reply-To: References: Message-ID: <8c7f10c60601180405q4e9be16cp80ca121608cb9a0d@mail.gmail.com> On 18 Jan 2006 11:59:23 GMT, Johannes Zellner wrote: > Hi, > > can I make an object read-only, so that > > x = new_value > > fails (and x keeps it's orginal value)? This works for me: http://groups.google.com/group/comp.lang.python/msg/2b1785397358ff90 -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ray_usenet at yahoo.com Wed Jan 4 20:26:10 2006 From: ray_usenet at yahoo.com (Ray) Date: 4 Jan 2006 17:26:10 -0800 Subject: Microsoft IronPython? In-Reply-To: <1136408036.966014.286530@f14g2000cwb.googlegroups.com> References: <1136320500.246753.245010@f14g2000cwb.googlegroups.com> <1136326700.831585.34410@g14g2000cwa.googlegroups.com> <1136340334.938977.146050@g47g2000cwa.googlegroups.com> <1136342512.032169.285020@f14g2000cwb.googlegroups.com> <1136356109.506719.154390@o13g2000cwo.googlegroups.com> <1136408036.966014.286530@f14g2000cwb.googlegroups.com> Message-ID: <1136424370.768801.172610@g44g2000cwa.googlegroups.com> Luis M. Gonz?lez wrote: > I'm not en expert on the subject, but I guess that any language > implementation running on .Net should be able to at least "understand" > generics or any other feature available on this framework, because > languages are supposed to interact and use all kinds of classes and > assemblies regardless of the language they were written in. > As for using generics, I think this is not very important in python, I > guess, because it is dyamic and you don't declare types. > So writing x =List[str](), for example, doesn't buy you anything. > You're better off using a regular list: x = []. Yes, in this List example I agree with you. I think it is better to use the regular one. But, say, since C# has generic now, somebody may write a generic class, so you have to have a way to use it (unless it's like Java when you can still do raw types--correct me if I'm wrong). But then again, once you start using .NET class you're tied to .NET anyway so this is not a big problem, I think--although the more perfectionist among us might like to isolate parts of Python code that are .NET/IP specific to make porting easier if it ever comes to that... > > Someone more knowledgeable please kindly correct me... > > Luis From nirvana117 at gmail.com Mon Jan 23 06:05:27 2006 From: nirvana117 at gmail.com (Pan Menghan) Date: Mon, 23 Jan 2006 19:05:27 +0800 Subject: Redirecting standard out in a single namespace In-Reply-To: <1137771435.682063.178150@g14g2000cwa.googlegroups.com> References: <1137771435.682063.178150@g14g2000cwa.googlegroups.com> Message-ID: <19b355330601230305r3b978925tf3ada3f64785f854@mail.gmail.com> Maybe you can use __name__ to determine which module the print statement is in: class out: def write(s,a): if __name__ =="myModule": mylog.write(a) else: sys.__stdout__.write(a) sys.stdout = out() -------------- next part -------------- An HTML attachment was scrubbed... URL: From nephish at xit.net Tue Jan 17 21:51:44 2006 From: nephish at xit.net (nephish at xit.net) Date: 17 Jan 2006 18:51:44 -0800 Subject: check to see if value can be an integer instead of string In-Reply-To: References: <1137549772.543188.69240@g44g2000cwa.googlegroups.com> Message-ID: <1137552704.262742.219700@o13g2000cwo.googlegroups.com> thanks for the reply, but wont python fail out if you try to make an integer out of what cant be an integer? like this : var = int(abc) wont this crash ? From fuzzyman at gmail.com Wed Jan 25 08:54:48 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2006 05:54:48 -0800 Subject: append to the end of a dictionary In-Reply-To: References: <43D63B93.5000705@sitasoftware.lu> Message-ID: <1138197288.927953.216630@o13g2000cwo.googlegroups.com> Tim Chase wrote: > > I seem to be unable to find a way to appends more keys/values to the end > > of a dictionary... how can I do that? > > > > E.g: > > > > mydict = {'a':'1'} > > > > I need to append 'b':'2' to it to have: > > > > mydict = {'a':'1','b':'2'} > > my understanding is that the order of a dictionary should never > be relied upon. To do what you want, you'd use > > mydict['b'] = '2' > > However, you're just as liable to get > > >>> mydict > {'a':'1','b':'2'} > > as you are to get > > >>> mydict > {'b':'2','a':'1'} > > To get them in a key-order, my understanding is that you have to > use something like > > keys = mydict.keys() > sort(keys) > orderedDict = [(k, mydict[k]) for k in keys] > > unless you have a way of doing an in-line sort, in which you > would be able to do something like > > orderedDict = [(k,mydict[k]) for k in mydict.keys().sort()] > You can do all this and more from the OrderedDict in pythonutils : http://www.voidspace.org.uk/python/odict.html http://www.voidspace.org.uk/python/pythonutils.html from odict import OrderedDict our_dict = OrderedDict(some_dict.items()) our_dict.sort() All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Unfortunately, the version I've got here doesn't seem to support > a sort() method for the list returned by keys(). :( > > -tim From aldo at nullcube.com Mon Jan 23 21:40:42 2006 From: aldo at nullcube.com (Aldo Cortesi) Date: Tue, 24 Jan 2006 13:40:42 +1100 Subject: Loop exception catching In-Reply-To: <17d4ae400601231403h4f67067ev22abd86179ba0fbc@mail.gmail.com> References: <17d4ae400601231403h4f67067ev22abd86179ba0fbc@mail.gmail.com> Message-ID: <20060124024042.GA21167@nullcube.com> Thus spake Ivan Shevanski (darkpaladin79 at gmail.com): > Alright this is kind of a continuation of a past conversation. . .But not > really. Anyway, heres the problem. Say I had this: > > try: > x = input("> ") > except SyntaxError: > print "explain the problem here" > x = input("> ") > > That's to catch when people just press enter by mistake without selecting > something from the menu. But the thing is how would I make that loop? I > want it to keep catching the user pressing enter if they did it over and > over [there are some weird people out there ;)] I tryed this but to no > avail: > > try: > x = input("> ") > except SyntaxError: > while SyntaxError: > print "Please enter only the number beside your choice" > print > x = input("> ") Well, leaving aside the merits of using "input" (which should be avoided at all costs), here's one way to do what you want: while 1: try: x = input("> ") break except SyntaxError: print "explain the problem here" Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Mob: 0419 492 863 From http Sun Jan 1 18:33:51 2006 From: http (Paul Rubin) Date: 01 Jan 2006 15:33:51 -0800 Subject: Hypergeometric distribution References: <1135628335.580063.179200@z14g2000cwz.googlegroups.com> <1h871o5.4kfq9m1ueam9zN%aleax@mail.comcast.net> <1136075042.504604.122680@g14g2000cwa.googlegroups.com> <1136154279.355940.182310@g49g2000cwa.googlegroups.com> Message-ID: <7xy81zcylc.fsf@ruckus.brouhaha.com> "Raven" writes: > Yes I am calculating hundreds of hypergeometric probabilities so I need > fast calculations Can you use Stirling's approximation to get the logs of the factorials? From emile at fenx.com Mon Jan 30 21:33:43 2006 From: emile at fenx.com (Emile van Sebille) Date: Mon, 30 Jan 2006 18:33:43 -0800 Subject: Collecting IP range References: Message-ID: "yawgmoth7" wrote in message news:cef393a0601301710g1d508568gcafa30ffb2e91091 at mail.gmail.com... > for ips in range(startip,endip): > > Here's one way: def iterIPs(startip,endip): import socket, struct sip = struct.unpack('>L',socket.inet_aton(startip))[0] eip = struct.unpack('>L',socket.inet_aton(endip))[0] while sip <= eip: yield socket.inet_ntoa(struct.pack('>L',sip)) sip += 1 for ii in iterIPs ('1.2.3.0','1.2.3.127'): ii Emile From mikael at isy.liu.se Tue Jan 31 02:56:23 2006 From: mikael at isy.liu.se (Mikael Olofsson) Date: Tue, 31 Jan 2006 08:56:23 +0100 Subject: Tk.quit() now working! In-Reply-To: <1138688291.815216.95040@g47g2000cwa.googlegroups.com> References: <1138545212.575347.280920@f14g2000cwb.googlegroups.com> <1138688291.815216.95040@g47g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: >>how do you run your Tkinter program ? al pacino wrote: > like? i was testing it in windows (interactive interpreter) What Fredrik probably means is: Did you by any chance start it from IDLE? In that case it will not work. It doesn't for me. The reason - I've been told - is that IDLE itself is a tkinter application. If you instead start it by simply double-clicking on its icon, as you would start anything else in Windows, it should work as expected. It does for me, on Win XP Pro. HTH /MiO From wrongbad at gmail.com Sun Jan 22 18:06:19 2006 From: wrongbad at gmail.com (wrongbad at gmail.com) Date: 22 Jan 2006 15:06:19 -0800 Subject: Making dir's In-Reply-To: References: Message-ID: <1137971179.759544.195820@g47g2000cwa.googlegroups.com> yawgmoth7 wrote: > And so on. That is not very practical, and I wish to change it. I was > wondering if there were any other methods to which I could do this, I > was thinking maybe I could put the dir names in a dictionary then have > something like: > os.mkdir(thedictname) Why not use a loop? dirs = ['ASM', 'C', 'Python'] for dir in dirs: os.mkdir(dir) From velle at velle.dk Tue Jan 3 10:08:46 2006 From: velle at velle.dk (velle at velle.dk) Date: 3 Jan 2006 07:08:46 -0800 Subject: Getting the encoding of sys.stdout and sys.stdin, and changing it properly Message-ID: <1136300926.623185.144730@o13g2000cwo.googlegroups.com> My headache is growing while playing arround with unicode in Python, please help this novice. I have chosen to divide my problem into a few questions. Python 2.3.4 (#1, Feb 2 2005, 12:11:53) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 1) Does " >>>print 'hello' " simply write to sys.stdout? 2) Exactly what does the following line return? >>> sys.stdout.encoding 'ISO-8859-1' Is it the encoding of the terminal? I think not, because when I change the encoding in my terminal the result is still the same. Is it the encoding of the string python "hands over" to the terminal? I think not. In the following code i am pretty confident that the second command changes that, and still sys.stdout.encoding is the same value. >>> import sys,codecs >>> sys.stdout.encoding 'ISO-8859-1' >>> sys.stdout = codecs.getwriter('utf-8')(sys.stdout) >>> sys.stdout.encoding 'ISO-8859-1' Then what? 3) Does raw_input() come from sys.stdin? 4) The following script is not working, can you please tell me how to do it right. >>> import codecs,sys >>> sys.stdout = codecs.getwriter('utf-8')(sys.stdout) >>> sys.stdin = codecs.getreader('utf-8')(sys.stdin) >>> x = raw_input('write this unicode letter, Turkish che, unicode 0x00E7\t') write this unicode letter, Turkish che, unicode 0x00E7 ? Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/codecs.py", line 295, in readline return self.decode(line, self.errors)[0] UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: unexpected end of data When prompted, I simply enter the che with my Turkish keyboard layout. velle, Denmark From __peter__ at web.de Mon Jan 9 04:33:13 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Jan 2006 10:33:13 +0100 Subject: Why it doesn't work? References: <1136651611.938694.244420@f14g2000cwb.googlegroups.com> Message-ID: Lad wrote: > I have a list A dictionary. > L={} > Now I can assign the value > L['a']=1 > and I have > L={'a': 1} > > but I would like to have a dictionary like this > L={'a': {'b':2}} > > so I would expect I can do > L['a']['b']=2 > > but it does not work. Why? D["a"]["b"] = 2 translates to D.__getitem__("a").__setitem__("b", 2) When D doesn't already contain a key/value pair D = {"a": {}} the __getitem__() call fails with a KeyError. If you don't know whether D contains a key "a", use setdefault(key, value) which inserts the value only if key is currently not in the dictionary. E. g. >>> D = {} >>> D.setdefault("a", {})["b"] = 42 >>> D.setdefault("a", {})["c"] = 24 >>> D {'a': {'c': 24, 'b': 42}} Peter From exarkun at divmod.com Tue Jan 17 21:24:28 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 17 Jan 2006 21:24:28 -0500 Subject: magical expanding hash In-Reply-To: Message-ID: <20060118022428.8424.1148208423.divmod.quotient.172@ohm> On Tue, 17 Jan 2006 16:47:15 -0800, James Stroud wrote: >braver wrote: >> Well, I know some python, but since there are powerful and magical >> features in it, I just wonder whether there're some which address this >> issue better than others. >> > >In python, += is short, of course, for > >a = a + 1 > No it's not. It's short for if isinstance(a, object): if hasattr(a.__class__, '__iadd__'): _x = a.__class__.__iadd__(a, b) if _x is NotImplemented: a = b + a else: a = _x else: a = b + a else: if hasattr(a, '__iadd__'): _x = a.__iadd__(b) if _x is NotImplemented: a = b + a else: a = _x else: a = b + a Roughly speaking, anyway. Not that this is relevant to your point. Jean-Paul From grante at visi.com Thu Jan 12 18:15:02 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 12 Jan 2006 23:15:02 -0000 Subject: Converting a string to an array? References: Message-ID: <11sdonmhqj0bk3a@corp.supernews.com> On 2006-01-12, Ron Griswold wrote: >> This lacks the beauty of most python code, and clearly feels like >> there's somethign I'm missing. Is there some method or function >> I've overlooked that would convert a string to an array with less >> song-and-dance? Thanks, > >> import random >> s = "abcdefg" >> a = [] >> a.extend(s) >> random.shuffle(a) >> s = "".join(a) > > Does this do what you are looking for? > >>>> s = 'abcdefg'; >>>> a = []; >>>> a += s; >>>> a; > ['a', 'b', 'c', 'd', 'e', 'f', 'g'] That's a bit round-about: >>> list('abcdefg') ['a', 'b', 'c', 'd', 'e', 'f', 'g'] -- Grant Edwards grante Yow! Yow! Am I cleansed at yet?! visi.com From duncan.booth at invalid.invalid Tue Jan 31 03:26:44 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Jan 2006 08:26:44 GMT Subject: triple quoted strings as comments References: <1138667355.631379.249770@o13g2000cwo.googlegroups.com> Message-ID: dmh2000 wrote: > example > > def fun(self): > """doc comment > comment line 2 > """ > > x = 1 > y = 2 > > """does this triple quoted string used as a comment > cause something to happen at runtime beyond > just skipping over it? Such as allocation of memory for a string > or worse yet garbage collection? or not? > """ > z = x + y > How to find out for yourself: >>> def fun(self): """doc comment comment line 2 """ x = 1 y = 2 """does this triple quoted string used as a comment cause something to happen at runtime beyond just skipping over it? Such as allocation of memory for a string or worse yet garbage collection? or not? """ z = x + y >>> import dis >>> dis.dis(fun) 6 0 LOAD_CONST 1 (1) 3 STORE_FAST 2 (x) 7 6 LOAD_CONST 2 (2) 9 STORE_FAST 1 (y) 14 12 LOAD_FAST 2 (x) 15 LOAD_FAST 1 (y) 18 BINARY_ADD 19 STORE_FAST 3 (z) 22 LOAD_CONST 3 (None) 25 RETURN_VALUE >>> Further inspection shows that it hasn't even saved that second string as a constant: >>> print fun.func_code.co_consts ('doc comment\n comment line 2\n ', 1, 2, None) From maha.murali at gmail.com Thu Jan 26 18:58:54 2006 From: maha.murali at gmail.com (Murali) Date: 26 Jan 2006 15:58:54 -0800 Subject: generating method names 'dynamically' In-Reply-To: References: Message-ID: <1138319934.353261.18160@g43g2000cwa.googlegroups.com> import inspect x = ABC() # create an instance of class ABC print inspect.getmembers(x,inspect.ismethod) -------------------- Most of any introspection stuff can be done using the module "inspect". From skip at pobox.com Wed Jan 11 10:24:04 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 11 Jan 2006 09:24:04 -0600 Subject: Spelling mistakes! In-Reply-To: References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> <20060110170407.131d9650@samwise.anansi> Message-ID: <17349.8980.553233.888635@montanaro.dyndns.org> Steve> I suppose most readers aren't old enough to remember the punch Steve> card days, when you would hand your work in on coding sheets to Steve> the punch room and it would be punched onto cards using huge Steve> machines (anyone remember the 026 and 029 punches?). I do remember the IBM Model 29 punch card machines, though as a student nobody was there to punch my cards or verify them for me... :-( Skip From apardon at forel.vub.ac.be Mon Jan 9 05:50:49 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Jan 2006 10:50:49 GMT Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <8664ozd1bm.fsf@bhuda.mired.org> <43BC806A.1040201@REMOVEMEcyber.com.au> Message-ID: Op 2006-01-06, Steven D'Aprano schreef : > If we say "Python is call be reference" (or call by value, as many people > also say) we *know* the consequence will be newbies writing in saying "I > was told Python is call by reference, so I did this, and it didn't work, > is that a bug in Python? What is wrong?" It is not a bug in Python, it is > a bug in their mental model of how Python works, and we put that bug in > their head. Every time that happens, it is *our* fault, not theirs, for > using language guaranteed to mislead. Well then I would think that the language that misleads is not "reference" but assignment. Because it is not their idea of call by reference that leads to the misconception, but their idea of what an assignment does. -- Antoon Pardon From kent at kentsjohnson.com Sat Jan 7 15:03:10 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 07 Jan 2006 15:03:10 -0500 Subject: Help Please: 'module' object has no attribute 'compile' In-Reply-To: References: <43beeb5d$1_1@newspeer2.tds.net> Message-ID: <43c01ae6$1_3@newspeer2.tds.net> livin wrote: > I beleive so... I cannot know for sure becasue the models are not > separate... they are in the python23.zlib file... I'm no sure how to check > the file, it looks as if it is compiled (I'm new to python so forgive my > ignorance) Yes, there should be an re module in your Python distribution, and it should have a compile attribute. You can check this from the python intepreter easily: >>> import re >>> re.compile What I am suggesting is that YOU may have created a module named re that Python is finding instead of the system module by that name. In this case your module doesn't have a compile attribute. This would cause the error you see. Kent > > > "Kent Johnson" wrote in message > news:43beeb5d$1_1 at newspeer2.tds.net... > >>livin wrote: >> >>>my log... >>> >>>INFO urllib.urlopen('http://192.168.1.11/hact/kitchen.asp', >>>urllib.urlencode({'Action': 'hs.ExecX10ByName+Kitchen+Lights%2C+On >>>%2C+100&x=4&y=6'})) >>>INFO >>> INFO File "Q:\python\python23.zlib\urllib.py", line 78, in urlopen >>>INFO File "Q:\python\python23.zlib\urllib.py", line 159, in open >>>INFO File "Q:\python\python23.zlib\urllib.py", line 957, in splittype >>>INFO AttributeError >>>INFO : >>>INFO 'module' object has no attribute 'compile' >> >>That line reads >> _typeprog = re.compile('^([^/:]+):') >> >>Do you have a module named 're' that is shadowing the library module of >>the same name? >> >>Kent > > > From iladijas at gmail.com Thu Jan 12 14:54:02 2006 From: iladijas at gmail.com (fynali) Date: 12 Jan 2006 11:54:02 -0800 Subject: How to remove subset from a file efficiently? References: <9afea2ac0601120919v679f2653u@mail.gmail.com> Message-ID: <1137095641.343554.284750@g14g2000cwa.googlegroups.com> The code it down to 5 lines! #!/usr/bin/python barred = set(open('/home/sajid/python/wip/CBR0000319.dat')) postpaid_file = open('/home/sajid/python/wip/PSP0000320.dat') outfile = open('/home/sajid/python/wip/PSP-CBR.dat', 'w') outfile.writelines(number for number in postpaid_file if number not in barred) postpaid_file.close(); outfile.close() Awesome! (-: Thanks a ton Fredrik, Steve. $ time ./cleanup.py real 0m11.048s user 0m5.232s sys 0m0.584s But there seem to be that discrepancy; will chk and update back here. Thank you all once again. From tim at pollenation.net Mon Jan 23 17:11:31 2006 From: tim at pollenation.net (Tim Parkin) Date: Mon, 23 Jan 2006 22:11:31 +0000 Subject: converting wiki markup to html (or xml) In-Reply-To: References: Message-ID: <43D55493.5070503@pollenation.net> Jarek Zgoda wrote: > Tim Parkin napisa?(a): > > >>I'm trying to convert fragments of wiki markup into fragments of html >>(specifically using moinmoin markup). I've managed to do this with >>MoinMoin but I've had to create a data directory, config file and >>underlay. Does anybody know if there a sane way of doing this without >>the extra baggage? > > > If you consider docutils, markdown or textile (or whatever markup your > Wiki uses) an "extra baggage", then answer is "no". The extra baggage I was referring to was the config files, data directory, underlay, requestCLI, etc. I've looked in vain for a way to do this >>> from MoinMoin import moinToHtml moinFormattedText =""" == Some Moin Formatted Text == Para One Para Two """ html = moinToHtml(moinFormattedText) <<< I could even live with passing some extra parameters to moinToHtml in order to configure it. I could even live with having to use StringIO to convince it it's writing to files if necessary. Having to install a wiki in order to do this seems excessive. If anybody has done something similar I'd love to know. Tim Parkin From ajones1 at gmail.com Mon Jan 30 20:28:47 2006 From: ajones1 at gmail.com (ajones) Date: 30 Jan 2006 17:28:47 -0800 Subject: Fuzzy Lookups In-Reply-To: <1138635665.956131.130630@f14g2000cwb.googlegroups.com> References: <1138635665.956131.130630@f14g2000cwb.googlegroups.com> Message-ID: <1138670927.377396.78090@g44g2000cwa.googlegroups.com> BBands wrote: > I have some CDs and have been archiving them on a PC. I wrote a Python > script that spans the archive and returns a list of its contents: > [[genre, artist, album, song]...]. I wanted to add a search function to > locate all the versions of a particular song. This is harder than you > might think. For example the Cajun "national anthem" is Jolie Blond, > but it can be spelled several different ways jolie, joli, blon, blond, > etc... In addition the various online services that provide song info > are riddled with typos, so an ordinary string match just doesn't get > you there. What is needed is a fuzzy string match and it turns out that > there is a very good one, the Levenshtein distance, which is the number > of inserts, deletions and substitutions needed to morph one string into > another. In my application I match the desired song title against all > song titles in my list and return the ones with the lowest Levenshtein > distances. This is remarkably, one might even say stunningly, > effective, easily finding all the version of Jolie Blon in the list. > > I am using the following snippet (found on the web, proper attribution > unsure), which calculates the Levenshtein distance. > > def distance(a,b): > c = {} > n = len(a); m = len(b) > > for i in range(0,n+1): > c[i,0] = i > for j in range(0,m+1): > c[0,j] = j > > for i in range(1,n+1): > for j in range(1,m+1): > x = c[i-1,j]+1 > y = c[i,j-1]+1 > if a[i-1] == b[j-1]: > z = c[i-1,j-1] > else: > z = c[i-1,j-1]+1 > c[i,j] = min(x,y,z) > return c[n,m] > > As mentioned above this works quite well and I am happy with it, but I > wonder if there is a more Pythonic way of doing this type of lookup? > > jab Here is my stab at it, didn't fully test it so it may not work correctly. The tuples could be avoided by using len(x), but the extra lookups may cost in execution speed[1]. def distance(a, b): """ Computes the levenshtein distance between two strings """ m, n = (len(a),a), (len(b),b) if(m[0] < n[0]): #ensure that the 'm' tuple holds the longest string m, n = n, m dist = m[0] #assume distance = length of longest string (worst case) for i in range(0, n[0]): # reduce the distance for each char match in shorter string if m[1][i] == n[1][i]: dist = dist - 1 return dist [1] I have no if this is true or not. I can see arguments for both. From john.rhoads at philips.com Thu Jan 12 16:06:50 2006 From: john.rhoads at philips.com (John Rhoads) Date: 12 Jan 2006 21:06:50 GMT Subject: Accessing Windows file metadata? References: <1137019893.211802.231770@o13g2000cwo.googlegroups.com> Message-ID: <3e3f6a7b27668c7e5a954ee2d9a@news-proxy.pus.philips.com> Probably somebody more deeply into this will soon give you a better answer, but I'll try to give a better-than-nothing answer. The Properties metadata that you see in the shell can come from several places. The oldest, commonest source is from Microsoft Office files. These have a compound structure associated with OLE Object Linking and Embedding and the metadata is just one of a lot of things stuck in there besides the Word text or Excel numbers you see in the application. Getting to it from Python is via COM. See Mark Hammond and Andy Robinson's book "Python Programming in Win32" for the general approach. Perhaps the easiest way to get this metadata is using DSOFILE.DLL that was released as an example a long time ago by Microsoft (it's not an OS file, you have to install it yourself). The following article gives a VBScript example that you can use as a template for your Python. http://www.microsoft.com/technet/community/columns/scripts/sg0305.mspx As I said, the OLE metadata has been around for a long time. With Windows 2000, MS extended the idea to any NTFS file so that you have an open-ended ability to associate named attributes like author, title, keywords or custom attributes of your own to any file on an NTFS partition. Unfortunately DSOFILE does not help with this (at least I don't think so!), so you'd need to deal with the OS at a somewhat uglier level. And obviously you need Win2K or better. Look at \win32com\test\testStorage.py in the win32 python package for an example. Hope this helps, John Rhoads > I'm looking for a method by which to access Windows files metadata and > have not been able to find anything in the standard modules or via > Google - what is the standard approach? > > Shamefully I really do not understand Windows file system - e.g. is > properties metadata attached to the file? if I change that metadata > do I change the file's hash? how is the metadata structured? or is > the "properties" metadata simply derived upon access? > > Either way, is there a module or method to access this metadata (I'd > hope there was a metadata dictionary for each file, but that may be a > sign I've been spoiled by Python) ? > > EP > From aleax at mail.comcast.net Mon Jan 16 15:08:14 2006 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 16 Jan 2006 12:08:14 -0800 Subject: Arithmetic sequences in Python References: <1137402099.920352.275350@o13g2000cwo.googlegroups.com> <7xmzhw1lsw.fsf@ruckus.brouhaha.com> <1h990zq.djbog8snj0xhN%aleax@mail.comcast.net> Message-ID: <1h998xn.1vqzm4e1brtqsoN%aleax@mail.comcast.net> Roy Smith wrote: > Alex Martelli wrote: > >Agreed. *IF* we truly needed an occasional "up to X *INCLUDED*" > >sequence, it should be in a syntax that can't FAIL to be noticed, such > >as range(X, endincluded=True). > > How about... > > for i in (0..x]: > blah The difference between a round parenthesis and a square bracket can EASILY be overlooked, depending partly on what font you're using. Alex From kent at kentsjohnson.com Fri Jan 20 08:24:41 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 20 Jan 2006 08:24:41 -0500 Subject: Finding the relative path of a file from a dir In-Reply-To: References: Message-ID: <43d0e0be$1_3@newspeer2.tds.net> Suresh Jeevanandam wrote: > Hi, > a = '/home/suresh/doc/html/a1/' > b = '/home/suresh/doc/' > > I am looking for a standard function which will return the location of b > relative to a i.e. '../..' Jason Orendorff's path module has a method for this (relpathto()). http://www.jorendorff.com/articles/python/path/index.html Kent From steven.bethard at gmail.com Thu Jan 26 16:41:52 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 26 Jan 2006 14:41:52 -0700 Subject: How to handle two-level option processing with optparse In-Reply-To: References: <59%Bf.63160$eD5.1054688@twister2.libero.it> Message-ID: R. Bernstein wrote: > Magnus Lycka informs: >> [in response to my comment]: >>> I see how I missed this. Neither disable_.. or enable_.. have document >>> strings. And neither seem to described in the optparser section (6.21) >>> of the Python Library (http://docs.python.org/lib/module-optparse.html). >> http://docs.python.org/lib/optparse-other-methods.html > > Hmmm. A couple things are a little odd about this. First "Other > methods" seems to be a grab-bag category. A place to put something > when you don't know where-else to put it. The section called: > "Querying and manipulating your option parser" seems closer. Better I > think if the title were changed slightly to > > Querying, manipulating, and changing the default behavior of your > option parse > > Second, oddly I can't find this section "Other Methods" in the current > Python SVN source Doc/lib/liboptparse.tex. Best as I can tell, that > file does seem to be the section documenting optparse. Sounds like you should submit a documentation bug: http://sourceforge.net/tracker/?group_id=5470&atid=105470 Plain text is fine -- just explain what needs to be changed. Thanks! STeVe From kxroberto at googlemail.com Thu Jan 12 03:35:46 2006 From: kxroberto at googlemail.com (Robert) Date: 12 Jan 2006 00:35:46 -0800 Subject: Unicode style in win32/PythonWin In-Reply-To: References: <1136921287.127575.143670@o13g2000cwo.googlegroups.com> <1136921965.284698.19170@g49g2000cwa.googlegroups.com> <1136923757.375103.306370@o13g2000cwo.googlegroups.com> <1136989316.179566.98110@g44g2000cwa.googlegroups.com> Message-ID: <1137054946.429896.207320@g47g2000cwa.googlegroups.com> Neil Hodgson wrote: > Robert: > > > After "is_platform_unicode = ", scintilla displays some unicode > > as you showed. but the win32-functions (e.g. MessageBox) still do not > > pass through wide unicode. > > Win32 issues are better discussed on the python-win32 mailing list > which is read by more of the people interested in working on this library. > http://mail.python.org/mailman/listinfo/python-win32 > Patches that improve MessageBox in particular or larger sets of > functions in a general way are likely to be welcomed. ok. I have no patches so far as of now - maybe later. Played with Heller's ctypes for my urgent needs. That works correct with unicode like this: >>> import ctypes >>> ctypes.windll.user32.MessageBoxW(0,u'\u041f\u043e\u0448\u0443\u043a.txt',0,0) 1 My recommendation for the general style of unicode integration in win32 in future: * output-functions should dispatch auto on unicode paramams in order to use the apropriate xxxW-functions * input-functions (which are used much more infrequent in apps!) should accept an additional unicode=1 parameter (e.g.: SetWindowText(unicode=1); please not extra xxxW -functions! thus one can easily virtualize apps with something like xyfunc(...,unicode=ucflag) * or: input-functions should also auto-run unicode when a significant string calling parameter is unicode - same as with filesystem-functions in normal python. Example: win32api.FindFiles(u"*") is same as FindFiles("*",unicode=1) and is better as FindFilesW("*") Thus existing ansi apps can be converted to unicode aware apps with minimum extra efforts. Robert From tim.peters at gmail.com Fri Jan 20 18:59:56 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 20 Jan 2006 18:59:56 -0500 Subject: Strange python behavior with modules on an emt64 box In-Reply-To: <4CAF5E6682A9AE4C992F5ED5082704250310493C@EXCL01.exelixis.com> References: <4CAF5E6682A9AE4C992F5ED5082704250310493C@EXCL01.exelixis.com> Message-ID: <1f7befae0601201559g397e75b2r7c9cf5bafff5a1ee@mail.gmail.com> [Joshua Luben] > I thought I would post this here first before seeking more experienced ears > for this particular strangness. > > I have Python 2.4.2 installed from source on a dual processor dell server. > These are x86_64 processors (verified by /bin/arch) (aka emt64 extensions). > > uname -a gives > Linux eps-linuxserv3 2.6.5-7.244-smp #1 SMP Mon Dec 12 18:32:25 UTC 2005 x86_64 x86_64 x86_64 GNU/Linux > > The flavor of Linux is 64 bit SUSE SLES 9 with the latest updates. > > > Now for the strangeness. I'm using DCOracle2 (can't use anything else, as > this is the corporate standard) also compiled from source. When calling > executemany() when any parameter is of type int, I get a OverflowError. I > turned on debug traces in DCOracle2; this indicated that PyArg_ParseTuple() > was returning sizeof(int) = 4 bytes. Sounds right to me. I don't know of any platform other than old Cray Research boxes where sizeof(int) > 4. > DCOracle2 is compiled such that sizeof(int) = 8 bytes. Sounds wrong to me. > Python itself gives, > > python -c "import sys; print sys.maxint" > 9223372036854775807 > > Therefore, indicating that the size of int is 8 bytes. No, it does not. A Python `int` is a C `long`, and sizeof(long) = 8 on most 64-bit boxes (Win64 is an exception). The size of a platform C long can be deduced from the value of Python's sys.maxint, but nothing about the size of a platform C int. > So I'll go out on a limb here and assume that this is a python problem...but > I don't know where to take it... I'd start with this part, which sounds crazy: DCOracle2 is compiled such that sizeof(int) = 8 bytes. From seberino at spawar.navy.mil Wed Jan 11 13:58:04 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 11 Jan 2006 10:58:04 -0800 Subject: How do initial login/password before can download web file with urllib? Message-ID: <1137005884.646187.132640@g43g2000cwa.googlegroups.com> I finally figured out how to use the wonderful module urllib to download files. What if web page requires you to fill out a form with login and password first? Is this just like any other FORM? Can login/password from a GET method form be handled by appending something like "?login=foo,password=bar" to URL? Is that right way? Chris From apardon at forel.vub.ac.be Wed Jan 18 03:35:12 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2006 08:35:12 GMT Subject: Arithmetic sequences in Python References: <1137402099.920352.275350@o13g2000cwo.googlegroups.com> <7xmzhw1lsw.fsf@ruckus.brouhaha.com> <1h990vk.jlcdv91knr7aaN%aleax@mail.comcast.net> Message-ID: Op 2006-01-18, Tom Anderson schreef : > On Tue, 17 Jan 2006, Antoon Pardon wrote: > >> Op 2006-01-16, Alex Martelli schreef : >>> Paul Rubin wrote: >>> >>>> Steven D'Aprano writes: >>>>> For finite sequences, your proposal adds nothing new to existing >>>>> solutions like range and xrange. >>>> >>>> Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1). >>> >>> But not easier than reversed(range(6)) [[the 5 in one of the two >>> expressions in your sentence has to be an offbyone;-)]] >> >> Why don't we give slices more functionality and use them. >> These are a number of ideas I had. (These are python3k ideas) >> >> 1) Make slices iterables. (No more need for (x)range) >> >> 2) Use a bottom and stop variable as default for the start and >> stop attribute. top would be a value that is greater than >> any other value, bottom would be a value smaller than any >> other value. >> >> 3) Allow slice notation to be used anywhere a value can be >> used. >> >> 4) Provide a number of extra operators on slices. >> __neg__ (reverses the slice) >> __and__ gives the intersection of two slices >> __or__ gives the union of two slices >> >> 5) Provide sequences with a range (or slice) method. >> This would provide an iterator that iterates over >> the indexes of the sequences. A slice could be >> provided > > +5 > >> for i, el in enumerate(sequence): >> >> would become >> >> for i in sequence.range(): >> el = sequence[i] > > That one, i'm not so happy with - i quite like enumerate; it communicates > intention very clearly. I believe enumerate is implemented with iterators, > meaning it's potentially more efficient than your approach, too. And since > enumerate works on iterators, which yours doesn't, you have to keep it > anyway. Still, both would be possible, and it's a matter of taste. > >> But the advantage is that this would still work when someone subclasses >> a list so that it start index is an other number but 0. > > It would be possible to patch enumerate to do the right thing in those > situations - it could look for a range method on the enumerand, and if it > found one, use it to generate the indices. Like this: > > def enumerate(thing): > if (hasattr(thing, "range")): > indices = thing.range() > else: > indices = itertools.count() > return itertools.izip(indices, thing) Fine by me. I'm not against enumerate. >> If you only wanted every other index one could do the following >> >> for i in sequence.range(::2): >> >> which would be equivallent to >> >> for i in sequence.range() & (::2): > > Oh, that is nice. Still, you could also extend enumerate to take a range > as an optional second parameter and do this with it. Six of one, half a > dozen of the other, i suppose. Yes you could probably do so and I'm not against it, I just think that range would be a better base on which you can build enumerate and other things than that enumenrate can be a base. e.g. __len__ could be eliminated and len would be defined as: def len(seq): rng = seq.range() return rng.stop - rng.start From RGriswold at Rioting.com Tue Jan 17 12:41:47 2006 From: RGriswold at Rioting.com (Ron Griswold) Date: Tue, 17 Jan 2006 09:41:47 -0800 Subject: HTML library Message-ID: Hi Cliff, Looks like xist is exactly what I'm looking for. Thank you, Ron Griswold Character TD R!OT Pictures rgriswold at rioting.com -----Original Message----- From: Cliff Wells [mailto:cliff at develix.com] Sent: Tuesday, January 17, 2006 9:33 AM To: Ron Griswold Cc: python-list at python.org Subject: Re: HTML library On Tue, 2006-01-17 at 09:28 -0800, Ron Griswold wrote: > Hi Folks, > > > > Can someone point me in the direction of an html library that > generates html text for you. For example, if I had a tuple of tuples, > I'd like a function that would create a table for me. I've looked > through the standard library and it only seems to have html parsers. I > need to go the other way ;) > The two best things I know of are Nevow's Stan and XIST. Since I started using Stan, I've vowed to never write another line of XML. http://divmod.org/trac/wiki/DivmodNevow http://www.livinglogic.de/Python/xist/ Regards, Cliff From mwm at mired.org Sat Jan 14 16:20:31 2006 From: mwm at mired.org (Mike Meyer) Date: Sat, 14 Jan 2006 16:20:31 -0500 Subject: Why keep identity-based equality comparison? References: <1136846444.954839.58960@g47g2000cwa.googlegroups.com> <8664oshoqb.fsf@bhuda.mired.org> <86y81ofh07.fsf@bhuda.mired.org> <86u0ccf3pw.fsf@bhuda.mired.org> <86lkxm4xwl.fsf@bhuda.mired.org> <864q4a4qyd.fsf@bhuda.mired.org> <86zmm1h3a6.fsf@bhuda.mired.org> Message-ID: <861wzay09s.fsf@bhuda.mired.org> Antoon Pardon writes: >> If you >> want to argue that the builtin sets should do that, you can - but >> that's unrelated to the question of how the comparison operators >> behave for the rest of the bulitin types. > What I argue is that there is no single order for a specific type. I think that depends on your definition of type, but let it go. > There can be an order that is most usefull in general but which order > is usefull at a specific point depends on the context. Yes. So what? Does this fact suggest some change to Python that would improve it? If so, you need to mention it. If not, why bring it up at all? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mwm at mired.org Sat Jan 14 20:12:48 2006 From: mwm at mired.org (Mike Meyer) Date: Sat, 14 Jan 2006 20:12:48 -0500 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1136792417.696119@jetspin.drizzle.com> <1136858652.907049.120600@o13g2000cwo.googlegroups.com> <86ek3cfu8a.fsf@bhuda.mired.org> <868xtiwiim.fsf@bhuda.mired.org> <7xoe2es9xe.fsf@ruckus.brouhaha.com> <86vewmv1jb.fsf@bhuda.mired.org> Message-ID: <86ek3auwdr.fsf@bhuda.mired.org> Steven D'Aprano writes: >>>> distance_in_feet = 5 >>>> weight_in_milligrams = 5 >>>> distance_in_feet == weight_in_milligrams > True > Since when is a distance comparable to a weight, let alone equal? The latest (and most impressive to date) to fix this is frink: The examples section is particularly amusing. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From finite.automaton at gmail.com Fri Jan 27 01:17:23 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 26 Jan 2006 22:17:23 -0800 Subject: any way to customize the is operator? Message-ID: <1138342643.119111.281900@g14g2000cwa.googlegroups.com> There doesn't seem to be any way to customize the behavior of "is" as can be done for other operators... why not? From jacob at cd.chalmers.se Sun Jan 1 14:55:08 2006 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 1 Jan 2006 19:55:08 GMT Subject: python coding contest References: <43AEBD43.7080407@airlangen.de> <65dcde740512271106m122ff3a8mccf918046704048a@mail.gmail.com> <43B1EB2D.9080205@stackless.com> Message-ID: In article , Simon Hengel wrote: >Hello, > >> After all, I'd really love to set up another contest with >> different measures and criteria. > >for future events i will take a close look at other possibilities for >doing a ranking. At the moment the 22c3 and the contest is eating up all >my time. Pleas appreciate that i may not keep up with all mails. Sorry >for that. For whatever it is worth, I enjoyed myself thoroughly thinking about the problem, discussing it and listening to others discuss it. It was FUN! It is built into all requirements for shortest or fastest that the winning solution will be using obscure features and combinations in order to make the absolutely optimal solution. This doesn't really matter unless your goals are to demonstrate the elegance of the programming language. If you want to provide an alternative to solving crossword puzzles or mega-hard Sudoku's for the Christmas holiday, I'd say this is spot on. Jacob Hall?n -- From seb.haase at gmail.com Sun Jan 22 23:05:49 2006 From: seb.haase at gmail.com (seb.haase at gmail.com) Date: 22 Jan 2006 20:05:49 -0800 Subject: OpenGL References: <1137942077.323122.133250@g44g2000cwa.googlegroups.com> <1137945096.146607.314280@g44g2000cwa.googlegroups.com> Message-ID: <1137989149.756954.58240@f14g2000cwb.googlegroups.com> Does that mean PyOpenGL is based on ctypes ? I thought is was using SWIG ? And on that note: I have some (old) SWIG typemaps for numarray arrays that I'm using for many years. I was always wondering how difficult it would be for me to add them into PyOpenGL ? So far I'm just using my own (one !) OpenGL function with that typemap to draw 60000 vertices in a vector linestrip. But I would like to not have to resort to "string conversion" when for example drawing 2D typemaps... Anyway, thanks a lot for PytOpenGL - my program (image analysis platform and microscope control) would not be possible without it. Sebastian Haase From fakeaddress at nowhere.org Fri Jan 13 18:59:59 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 13 Jan 2006 23:59:59 GMT Subject: Subclassing socket In-Reply-To: <1137188974.804502.196260@g47g2000cwa.googlegroups.com> References: <1135136550.937037.84290@f14g2000cwb.googlegroups.com> <1137188974.804502.196260@g47g2000cwa.googlegroups.com> Message-ID: <3aXxf.2173$nT6.618@newssvr27.news.prodigy.net> groups.20.thebriguy at spamgourmet.com wrote: > To your question of why you'd ever [recv(0)]. > > This is very common in any network programming. If you send a packet > of data that has a header and payload, and the header contains the > length (N) of the payload, then at some point you have to receive N > bytes. If N is zero, then you receive 0 bytes. Of course, you CAN > test for N == 0, that's obvious - but why would you if the underlying > layers worked correctly? Its just extra code to handle an special case. We need "extra code" around recv to ensure we get exactly N bytes; 'recv(N)' can return less. The most straightforward code I know to read exactly N bytes never passes zero to recv (untested): def recvall(sock, size): """ Read and return exactly 'size' bytes from socket 'sock'. Kind of the other side of sock.sendall. """ parts = [] while size > 0: data = sock.recv(size) if not data: raise SomeException("Socket closed early.") size -= len(data) parts.append(data) return ''.join(parts) -- --Bryan From mike12mike12 at hotmail.com Sun Jan 15 11:06:48 2006 From: mike12mike12 at hotmail.com (Mike) Date: 15 Jan 2006 08:06:48 -0800 Subject: Marshal Obj is String or Binary? In-Reply-To: References: <1137183910.659813.210550@g47g2000cwa.googlegroups.com> <1137198520.330601.313660@f14g2000cwb.googlegroups.com> <1137200088.444533.313310@g49g2000cwa.googlegroups.com> <1137275424.671972.210140@g49g2000cwa.googlegroups.com> Message-ID: <1137341208.025579.259440@g14g2000cwa.googlegroups.com> > Even faster would be to write your code in assembly, and dump that > ridiculously bloated database and just write everything to raw bytes on > an unformatted disk. Of course, it might take the programmer a thousand > times longer to actually write the program, and there will probably be > hundreds of bugs in it, but the important thing is that you'll save three > or four milliseconds at runtime. > Right? Correct. I didn't quite see the issue as assembly vs. python, having direct translation to programming hours. The structure in mind is meant to act as a dictionary to extend my db with a few table fields that could vary from one record to another and won't be queried for. Considering everytime my record is loaded, it pickle or marshal data has to be decoded, I figured the faster alternative should be better. With the incompatibility issue, I figured the day I upgrade my python, I would write a python script to upgrade the data. I take my word back. > Your database either can handle binary data, or it can't. It can. It's my web framework that doesn't. > If it can, then just use pickle with a binary protocol and be done with it. That I will do. > Either way, you have to find a way to translate your Python data > structures into something that you can feed to the database. Your database > can't automatically suck data structures out of Python's working memory! > So why re-invent the wheel? marshal is not recommended, but if you can > live with the limitations of marshal then it might do the job. But trying > to optimise code that hasn't even been written yet is a sure way to > trouble. Thanks. Will do. Regards, Mike From steve at REMOVETHIScyber.com.au Fri Jan 20 22:17:45 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 21 Jan 2006 14:17:45 +1100 Subject: why is my hash being weird?? References: <1137649610.117757.31830@g14g2000cwa.googlegroups.com> <43CF50A3.3080101@REMOVEMEcyber.com.au> <1137677484.929233.273350@o13g2000cwo.googlegroups.com> <1137725951.521840.176000@g49g2000cwa.googlegroups.com> Message-ID: On Thu, 19 Jan 2006 18:59:11 -0800, pycraze wrote: > Surely adopting the above method is much better than what i have > approached earlier . The main reason i did adopt this exercise was when > i have to marshal a 20 - 40 MB above test.py file to the disk , the > simple load of the test.py will sky rocket my virtual memory > consumption. Why do you have to marshal a 20MB test.py file? That's just crazy. The entire standard Python language, object files and source files combined, is about 90MB. There are 185 *.py modules just in the top level of the directory, that's less than half a megabyte per module (and in reality, much less than that). If your source file is more than 100K in size, you really should be breaking it into separate modules. If any one function is more than one page when printed out, you probably should be splitting it into two or more functions. -- Steven. From uche.ogbuji at gmail.com Mon Jan 2 01:26:27 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 1 Jan 2006 22:26:27 -0800 Subject: Rss/xml namespaces sgmllib, sax, minidom In-Reply-To: <1135734216.088226.168990@o13g2000cwo.googlegroups.com> References: <1135734216.088226.168990@o13g2000cwo.googlegroups.com> Message-ID: <1136183187.038612.240390@g49g2000cwa.googlegroups.com> Sakcee wrote: > I want to build a simple validator for rss2 feeds, that checks basic > structure and reports channels , items , and their attributes etc. > > I have been reading Mark Pilgrims articles on xml.com, diveintopython > and someother stuff on sgmllib, sax.handlers and content handlers, > xml.dom.minidom > > why is all of this necessary, what is the difference between all these > libraries, it seems to me that I can parse the rss2 feed with any of > these libraries.!! ? > > what is the difference between namespaces and non-namspaces functions > in sax.handlers.contenthandler , is the namespace defined like domain > names on some website? Based on this question, I tend to think you might want to leave the XML processing to someone else's code. How about using Pilgrim's feedparser? http://feedparser.org/ -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From grante at visi.com Wed Jan 18 10:17:18 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 18 Jan 2006 15:17:18 -0000 Subject: Nit: please don't user "it's" unless you can substitute "it is" without changing your inteded meaning. References: <43ce2072.1408100020@news.oz.net> <1137586777.158342.297230@g44g2000cwa.googlegroups.com> Message-ID: <11ssmvuoapku76a@corp.supernews.com> On 2006-01-18, Fuzzyman wrote: > > Bengt Richter wrote: >> Typos happen to all of us, but in case you hadn't realized what "it's" >> is a contraction for ("it is"), now you do, and you can save yourself further >> embarrassment (assuming you care ;-). >> If your friends won't tell you, who will ;-) > > Making grammatical errors in the subject of a post on gramamtical > errors must be embarrasing. ;-) Not really. It's one of the basic laws of Usenet. All complaints about grammar/spelling will contain grammar/spelling mistakes. Nothing you can do about it. -- Grant Edwards grante Yow! Yow! I want to mail at a bronzed artichoke to visi.com Nicaragua! From mwm at mired.org Sun Jan 1 19:46:20 2006 From: mwm at mired.org (Mike Meyer) Date: Sun, 01 Jan 2006 19:46:20 -0500 Subject: Python as a Server vs Running Under Apache References: <1136155447.031234.78410@g43g2000cwa.googlegroups.com> Message-ID: <86oe2v78yr.fsf@bhuda.mired.org> "mojosam" writes: > Is this advice accurate? Are there other things to consider? Isn't > there just some way (short of running something like Zope) that would > keep Python resident in the server's RAM? This is a shared server, so > the web host probably doesn't like stuff sitting around in RAM. Jean-Paul Calderone has already answered most of these, so I'll get the last one. Stuff "sitting around in RAM" unusued on a busy server leaves RAM pretty quickly on a modern system. The executable pages will just be tossed, and reloaded from the executable file when they are needed again. Data pages will be written out to disk in the swap area, and read back in when they are needed. Unless your program's behavior is very strange, this will generally be quicker than recreating the program state from scratch. The end result is that your program loads faster, and the real RAM used to support this is negligible. > Right now, I only need small programs to run. E.g., I'm thinking of > embedding a Live Journal blog in my web page. Live Journal gives you > several ways of doing this, one of which is three lines of Python code. Trying to make your dynamic HTML content "fast" before you need to is a premature optimization. Yes, CGI is slow compared to some of the alternatives. But forks on Unix are still cheap, and you can handle quite a bit of traffic with it on a modern system before you run into a wall. Do it with CGI first, and fix it later if you need to. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Mon Jan 9 19:43:58 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Jan 2006 00:43:58 +0000 Subject: How login & download file from remote web site? Passwords a problem? In-Reply-To: <1136844539.641096.248180@g49g2000cwa.googlegroups.com> References: <1136829288.042780.112350@g14g2000cwa.googlegroups.com> <1136834335.576981.102590@g14g2000cwa.googlegroups.com> <1136844539.641096.248180@g49g2000cwa.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > Gene > > Thanks for links but I'm not sure what to do with them! The links were > about testing > frameworks. I just want to write a script to grab stuff from a remote > site (kinda like automatic ftp). > > Perhaps those tests you were referring to have code to do what I'm > looking for?\ > I think the implication was that you'd need to do the appropriate research to answer the question. However, if you want your software to log into a web site on the user's behalf I don't really see that you have much alternative than to ask them for the required information. If you suspect they'll sue you for abuse of the data they enter, go find another set of users ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From rbt at athop1.ath.vt.edu Mon Jan 23 21:56:17 2006 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 23 Jan 2006 21:56:17 -0500 Subject: os.unlink() AND win32api.DeleteFile() Message-ID: Can someone detail the differences between these two? On Windows which is preferred? Also, is it true that win32api.DeleteFile() can remove the 'special' files located in the 'special' folders only accessible by the shell object such as Temporary Internet Files, etc. Thanks! From claudio.grondi at freenet.de Tue Jan 24 07:07:32 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 24 Jan 2006 13:07:32 +0100 Subject: Using non-ascii symbols In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > On the page http://wiki.python.org/moin/Python3%2e0Suggestions > I noticed an interesting suggestion: > > "These operators ? ? ? should be added to the language having the > following meaning: > > <= >= != > > this should improve readibility (and make language more accessible to > beginners). > > This should be an evolution similar to the digraphe and trigraph > (digramme et trigramme) from C and C++ languages." > > How do people on this group feel about this suggestion? > > The symbols above are not even latin-1, you need utf-8. > > (There are not many usefuls symbols in latin-1. Maybe one could use ? > for cartesian products...) > > And while they are better readable, they are not better typable (at > least with most current editors). > > Is this idea absurd or will one day our children think that restricting > to 7-bit ascii was absurd? > > Are there similar attempts in other languages? I can only think of APL, > but that was a long time ago. > > Once you open your mind for using non-ascii symbols, I'm sure one can > find a bunch of useful applications. Variable names could be allowed to > be non-ascii, as in XML. Think class names in Arabian... Or you could > use Greek letters if you run out of one-letter variable names, just as > Mathematicians do. Would this be desirable or rather a horror scenario? > Opinions? > > -- Christoph One of issues in Python is cross-platform portability. Limiting the range of symbols to lower ASCII and with specification of a code table to ASCII is a good deal here. I think, that Unicode is not yet everywhere and as long it is that way it makes not much sense to go for it in Python. Claudio From bradfordh at gmail.com Sun Jan 29 18:13:36 2006 From: bradfordh at gmail.com (bradfordh at gmail.com) Date: 29 Jan 2006 15:13:36 -0800 Subject: Storing lines from a text file In-Reply-To: References: <1138575627.078312.276040@z14g2000cwz.googlegroups.com> Message-ID: <1138576416.253011.210570@f14g2000cwb.googlegroups.com> so this: a, b, c, d, e =f.readlines() ..this will put the first line in a, second in b, etc? How do I accomplish this when I'm not sure how many lines there are going to be every time? Thanks. From benji at benjiyork.com Sun Jan 15 21:51:07 2006 From: benji at benjiyork.com (Benji York) Date: Sun, 15 Jan 2006 21:51:07 -0500 Subject: proposal: another file iterator In-Reply-To: <20060116022059.26200.910215487.divmod.quotient.1080@ohm> References: <20060116022059.26200.910215487.divmod.quotient.1080@ohm> Message-ID: <43CB0A1B.8020004@benjiyork.com> Jean-Paul Calderone wrote: > When I just want the dumb version, I tend to write this: > > for chunk in iter(lambda: f.read(blocksize), ''): ... > > Which is only very slightly longer than your version. I would like it > even more if iter() had been written with the impending doom of lambda > in mind, so that this would work: > > for chunk in iter('', f.read, blocksize): ... > > But it's a bit late now. How about this instead (will work in 2.5): for chunk in iter(partial(f.read, blocksize), ''): ... -- Benji York From other at cazabon.com Sun Jan 15 09:32:37 2006 From: other at cazabon.com (Kevin) Date: Sun, 15 Jan 2006 15:32:37 +0100 Subject: Placing graphics & text on printed page - jan06call.jpg (0/1) References: Message-ID: <43ca5ce0$0$14118$ba620e4c@news.skynet.be> One option is to create your page as an image file using PIL (which can handle your text and drawing requirements, as well as any pictures/graphics), then print it to a windows printer using my ImagePrintWin module. ImagePrintWin can print to any normal windows printer, and includes an optional GUI for doing a "Printer Setup" type dialog (including preview). It can even handle ICC profiles for your printer if you want color accuracy. You can download ImagePrintWin (GPL'd) from my site at: http://www.cazabon.com/python/downloads/ImagePrintWin.py The pyCMS module for doing ICC is available also on my site at: http://www.cazabon.com/pyCMS/ Kevin Cazabon. "Michael Galvin" wrote in message news:qj1ds1d5msb9l6di4oobqsc458kcl31fv2 at 4ax.com... > I am trying to use Python to send to the printer a calender filled > with a mix of text and simple graphics. I want to draw on the printed > page something like a table with 6 rows and 7 columns to represent a > calendar. I want to place text precisely within those boxes on the > printed page. I am using Python 2.4 on Windows XP > > I was in the past able to do this within Visual Basic using its > printer object. Visual Basic's printer object uses a coordinate > system to allow you to draw lines and to place text on the printed > page precisely. I have attached a file "jan06call.jpg" to this message > to illustrate what I am trying to do. > > Does Python have a module which would help me do this? > > To put it another way, can Python control the placement of text and > graphics precisely on the printed page? > > I have scoured my Python programming texts, python.org, and this > usenet group without success. Mark Lutz's wonderful book "Programming > Python" has not one reference to the word "printer" in its index. > Surely, I must be overlooking something or thinking about this wrong. > > Michael Galvin > Muskegon, MI > From bokr at oz.net Sun Jan 8 17:36:24 2006 From: bokr at oz.net (Bengt Richter) Date: Sun, 08 Jan 2006 22:36:24 GMT Subject: What is the slickest way to transpose a square list of lists (tuple of tuples)? References: <43C167BB.5010008@andrew.cmu.edu> Message-ID: <43c1921a.585228484@news.oz.net> On Sun, 08 Jan 2006 15:21:59 -0600, Brian van den Broek wrote: >Gerard Brunick said unto the world upon 08/01/06 01:27 PM: >> My way is ugly. These has to be a better way. >> >> Thanks, >> Gerard > >If you'd posted your way, I might well have seen if I could do it in a >nicer fashion. But, since for all I know, my best efforts would result >in the approach you already have, I'm unlikely to put the effort in. > >I suspect I'm not alone. You might do well to show the approach you >are unhappy with. > OTOH, he's probably just trying to get someone to remember zip-abuse for him. Hope it's not homework ;-) >>> sq = [[r+c for c in 'abc'] for r in '123'] >>> for r in sq: print r ... ['1a', '1b', '1c'] ['2a', '2b', '2c'] ['3a', '3b', '3c'] >>> for r in (zip(*sq)): print r ... ('1a', '2a', '3a') ('1b', '2b', '3b') ('1c', '2c', '3c') Regards, Bengt Richter From ray_usenet at yahoo.com Wed Jan 4 10:17:53 2006 From: ray_usenet at yahoo.com (Ray) Date: 4 Jan 2006 07:17:53 -0800 Subject: Microsoft IronPython? In-Reply-To: <43bbcf8f$1_2@newspeer2.tds.net> References: <1136320500.246753.245010@f14g2000cwb.googlegroups.com> <1136326700.831585.34410@g14g2000cwa.googlegroups.com> <1136361554.020865.11460@g43g2000cwa.googlegroups.com> <1136368960.887598.290270@o13g2000cwo.googlegroups.com> <43bbcf8f$1_2@newspeer2.tds.net> Message-ID: <1136387873.588415.46640@g47g2000cwa.googlegroups.com> Kent Johnson wrote: > That's a hoot! Of course you can choose what language you like, but to > choose Groovy over Jython because it is more developed is mind-boggling! > > Jython 2.1 has been released, stable and suitable for production use for > many years. The Groovy community was still working on the *language > definition* in November 2005 and has yet to deliver a stable final release. Yeah, I know, I know... but I'm not the only voice in the team, mind. If it were up to me it'd be Jython for sure... Ray From Tommy.Ryding at gmail.com Tue Jan 17 04:32:20 2006 From: Tommy.Ryding at gmail.com (Tommy Ryding) Date: 17 Jan 2006 01:32:20 -0800 Subject: exec a string in an embedded environment In-Reply-To: <1137029577.338391.276250@g14g2000cwa.googlegroups.com> References: <1136982572.826349.298340@g43g2000cwa.googlegroups.com> <1137028218.224780.296720@g49g2000cwa.googlegroups.com> <1137029577.338391.276250@g14g2000cwa.googlegroups.com> Message-ID: <1137490340.431423.102840@g43g2000cwa.googlegroups.com> I can't post that much of what I have done but some questions might answer if you e-mail me the question to my gmail.com address. tommy.ryding at ... //Tommy From markus_REMOVEwankusALL_CAPS at hotmail.com Thu Jan 19 09:16:39 2006 From: markus_REMOVEwankusALL_CAPS at hotmail.com (Markus Wankus) Date: Thu, 19 Jan 2006 14:16:39 GMT Subject: New Python.org website ? In-Reply-To: References: <43C4E198.2080107@holdenweb.com> <43CE35E5.8000604@pollenation.net> <43CF5FBF.5090901@pollenation.net> Message-ID: Fredrik Lundh wrote: > Tim Parkin wrote: > >> How about designing a website and showing us what you think would be a >> good idea? Or suggesting some way of managing all of the content and >> building the system. > > I think I just did that: > > the easiest way to get there would be to use a MoinMoin instance to main- > tain the content, and a separate renderer to generate static pages for the > main site (possibly using Cheetah or Kid as template languages). > > to which you responded > > A wiki is not a website and to try to shoehorn a wiki into a content manage- > ment system is not a good final goal. > > which is an interesting thing to say at a time when "wikipedia" has > joined "google" and "blog" as the internet things that everyone has > heard about... > Well I happen to agree whole-heartedly with Tim on that one. I can't stand trying to navigate some of these Wiki-trying-to-be-website pages. It is impossible to find anything on most of them (notice I didn't say all..there are exceptions). It seems like they cater to people who: a) Get some sort of sick pleasure out of searching webpages by manually constructing regular expressions. b) Love the fact that every other word is a link and end up in a 3 hour link-clinking session until they have visited every link. Navigating a Wiki to me feels more like trying to find the proverbial needle in a haystack, or perhaps it is more like painting a wall by flinging paint at it with a spoon. But maybe that's just me. I sometimes have a compulsion for methodically checking everything in a sane order. That's probably just my code review skills, or dungeon-crawling instincts kicking in. ;o) M. From mnations at gmail.com Fri Jan 13 13:17:32 2006 From: mnations at gmail.com (Mudcat) Date: 13 Jan 2006 10:17:32 -0800 Subject: Why can't I "from module import *" except at module level? Message-ID: <1137176252.350535.162200@g49g2000cwa.googlegroups.com> I have a directory structure that contains different modules that run depending on what the user selects. They are identical in name and structure, but what varies is the content of the functions. They will only need to be run once per execution. Example (directory level): Sys1: A B C Sys2: A B C Sys3: A B C Sys4: A B C So if the user selects Sys1 during execution, I want to import the modules using "from *" and the run the content of those files. Now the way my program is set up, it is very important that I be able to "from Sys1 import *" and not "import Sys1". The names of the functions inside are passed in from somewhere else and the program requires those function names to be globally scoped. So I have a function that looks like this: def importModules( type ): cwd = os.getcwd() path = cwd + "\\" + type sys.path.append(path) from security import * Obviously this is not working and I get a syntax error at runtime. So without this functionality, how do I target modules to import in other directories after program execution has begun? Thanks From fuzzyman at gmail.com Thu Jan 19 06:15:09 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 19 Jan 2006 03:15:09 -0800 Subject: Efficient implementation of deeply nested lists In-Reply-To: <1137662346.819766.149310@g43g2000cwa.googlegroups.com> References: <1137662346.819766.149310@g43g2000cwa.googlegroups.com> Message-ID: <1137669309.844998.204930@g14g2000cwa.googlegroups.com> Kay Schluehr wrote: > I want to manipulate a deeply nested list in a generic way at a > determined place. Given a sequence of constant objects a1, a2, ..., aN > and a variable x. Now construct a list from them recursively: > > L = [a1, [a2, [....[aN, [x]]...]] > > The value of x is the only one to be changed. With each value of x a > new instance of L is needed so that we actually have a function: > > L = lambda x: [a1, [a2, [....[aN, [x]]...]] > > I'm seeking for an efficient implementation that does not recompute the > whole list each time. Any ideas? > Is the sequence of a1 to aN fixed ? I assume you want a new list each time ? You can create a reference list once but keep a reference to the most deeply nested part that contains x. Each time you need a new copy, insert hte new value of x and use copy.deepcopy to produce your new list. ***WARNING UNTESTED**** def listmaker(consts, x): global finalref out = [] if not consts: finalref = [x] return finalref entry = consts.pop() out.append(entry) out.append(listmaker(consts, x)) return out listmaker recursively builds the list structure and creates a global reference to the list holding x. You can build this once as a 'generic' list. When you need a copy do : del finalref[0] finalref.append(newx) newlist = copy.deepcopy(reference_list) I hope that helps, it may need debugging. :-) Because lists are mutable, you can't avoid the copy operation - but it is *probably* quicker than recomputing hte list. You should test this - as it might not be the case. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Kay From casevh at comcast.net Fri Jan 27 14:33:10 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 27 Jan 2006 11:33:10 -0800 Subject: writing large files quickly In-Reply-To: References: <1138389584.746734.324540@f14g2000cwb.googlegroups.com> Message-ID: <1138390390.583294.63460@g47g2000cwa.googlegroups.com> Oops. I did mean fd.write(block) The only limit is available memory. I've used 1MB block sizes when I did read/write tests. I was comparing NFS vs. local disk performance. I know Python can do at least 100MB/sec. From anton.vredegoor at gmail.com Sun Jan 8 08:38:00 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 8 Jan 2006 05:38:00 -0800 Subject: - E04 - Leadership! Google, Guido van Rossum, PSF References: <43b15d36$0$82640$ed2619ec@ptn-nntp-reader03.plus.net> <1135782518.053020.14730@g43g2000cwa.googlegroups.com> <1135784723.379971.131020@g47g2000cwa.googlegroups.com> <1136385474.032677.125670@z14g2000cwz.googlegroups.com> <1h8sgcn.hx53zc1p9d4qoN%aleax@mail.comcast.net> Message-ID: <1136727480.574785.25530@g44g2000cwa.googlegroups.com> Alex Martelli wrote: > Anton Vredegoor wrote: > > > However I still maintain that I was never able to meet these fine > > people you speak about and which you seem to know because the cost > > involved (a few hundred euro to visit pycon for example) was too high > > compared to my food budget. > > Europython is cheap to attend, and has been held twice in Charleroi, > Belgium, for example -- if you're in the Netherlands, you could have > bycicled there, crashed with somebody (I've seen lots of impecunious > people offered hospitality that way), and not spent more on food than > you would by staying in the Netherlands. You'll have to invent some > better excuse, to explain why you chose not to attend it. I looked it up: 160 euro (early registration). My food budget is about 16 euro a week now, maybe even less if I want to keep feeding myself a bit longer, maybe in 2003 my reserves were a bit higher than now, but I had not yet learned then to be without a regular income, so I was very scared to become pennyless at that time. I am perfectly used to sleeping at other peoples' places, for example I was at many go (baduk) tournaments and if the prices and atmosphere would be anything comparable to that I guarantee you that I would have been present. IIRC I got an offer from Laura Creighton at the time to borrow me the money, so one could say it was a choice, although by that time the price had gone up to 270 euro. But frankly indeed, I just don't even like to participate to events that claim to be open for all but don't even acknowledge that the barriers are extremely high compared to some participants budgets. Your hype about it being cheap has a very chilling effect on my enthousiasm, it's the same way with pypy congresses, which I also would have liked to attend (and this thing even seems to be sponsored by public EU money). Probably I am still a *rich* person, on a global scale, because I live in a place with free internet (from a public library). You *do* realize that even posting to usenet is impossible (or at least very hard) for a lot of people, including me for at least 6 months. I had to find someone to invite me to gmail and also a way to access my previous internet account, which I lost access to when they cut my phone line, to recieve the mail that finally enabled me to post via google. Nowadays it's probably possible to open a hotmail account and get invited to gmail from there, so one can post to usenet. Theoretically I have now yet another option to post (except via google), but IMO it remains true that one needs at least one link to corruption to be able to post to usenet. Anton 'hey, and my laptop doesn't even have a cdrom, needs almost continous electricity, it's keyboard is broken (but it works fine with external keyboard), and it networks via a pcmcia card with a *cable* ' From fperez.net at gmail.com Tue Jan 10 03:57:22 2006 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 10 Jan 2006 01:57:22 -0700 Subject: [ANN] IPython 0.7.0 Message-ID: Hi all, After a long hiatus (0.6.15 was out in June of 2005), I'm glad to announce the release of IPython 0.7.0, with lots of new features. WHAT is IPython? ---------------- 1. An interactive shell superior to Python's default. IPython has many features for object introspection, system shell access, and its own special command system for adding functionality when working interactively. 2. An embeddable, ready to use interpreter for your own programs. IPython can be started with a single call from inside another program, providing access to the current namespace. 3. A flexible framework which can be used as the base environment for other systems with Python as the underlying language. 4. A shell for interactive usage of threaded graphical toolkits. IPython has support for interactive, non-blocking control of GTK, Qt and WX applications via special threading flags. The normal Python shell can only do this for Tkinter applications. WHERE to get it? ---------------- IPython's homepage is at: http://ipython.scipy.org and downloads are at: http://ipython.scipy.org/dist I've provided: - source downloads (.tar.gz) - RPMs (for Python 2.3 and 2.4, built under Fedora Core 3). - Python Eggs (http://peak.telecommunity.com/DevCenter/PythonEggs). - a native win32 installer for both Python 2.3 and 2.4. Fedora users should note that IPython is now officially part of the Extras repository, so they can get the update from there as well (though it may lag by a few days). Debian, Fink and BSD packages for this version should be coming soon, as the respective maintainers (many thanks to Jack Moffit, Norbert Tretkowski, Andrea Riciputi and Dryice Liu) have the time to follow their packaging procedures. A lot of new features have gone into this release, the bulk of which were driven by user feedback and requests, and more importantly by patches from IPython users. I greatly appreciate these contributions, and hope they will continue in the future. In particular, thanks to Vivian de Smedt, Jorgen Stenarsson and Ville Vainio, who contributed large patches with much of the new significant functionality. I've tried to provide credit in the notes below and the project's ChangeLog, please let me know if I've accidentally ommitted you. Many thanks to Enthought for their continued hosting support for IPython. Release notes ------------- *** WARNING: compatibility changes *** - IPython now requires at least Python 2.3. If you can't upgrade from 2.2, you'll need to continue using IPython 0.6.15. *** End warning. As always, the NEWS file can be found at http://ipython.scipy.org/NEWS, and the full ChangeLog at http://ipython.scipy.org/ChangeLog. The highlights of this release follow. - Wildcard patterns in searches, supported by the %psearch magic, as well as the '?' operator. Type psearch? for the full details. Extremely useful, thanks to J?rgen Stenarson. - Major improvements to the pdb mode. It now has tab-completion, syntax highlighting and better stack handling. Thanks to Vivian De Smedt for this work (double-points given that pdb has a well-deserved reputation for being very unpleasant to work with). - Support for input with empty lines. If you have auto-indent on, this means that you need to either hit enter _twice_, or add/remove a space to your last blank line, to indicate you're done entering input. These changes also allow us to provide copy/paste of code with blank lines. - Support for pasting multiline input even with autoindent on. The code will look wrong on screen, but it will be stored and executed correctly internally. - TAB on an otherwise empty line actually inserts a tab. Convenient for indenting (for those who don't use autoindent). - Significant improvements for all multithreaded versions of ipython. Now, if your threaded code raises exceptions, instead of seeing a crash report, a normal (colored, verbose, etc.) exception is printed. Additionally, if you have pdb on, it will activate in your threaded code. Very nice for interactively debugging GUI programs. - Many fixes to embedded ipython, including proper handling of globals and tab completion. - New -t and -o options to %logstart, to respectively put timestamps in your logs, and to also log all output (tagged as #[Out]#). The default log name is now ipython_log.py, to better reflect that logs remain valid Python source. - Lightweight persistence mechanism via %store. IPython had always had %save, to write out a group of input lines directly to a file. Now, its %store companion stores persistently (associated with your profile, and auto-loaded at startup) not just source, but any python variable which can be pickled. Thanks to Matt Wilkie for the request, and ville for the patches. - Macros (created with %macro) can now be edited with %edit (just say '%edit macroname'). This, coupled with the ability to store them persistently, makes the macro system much more useful. - New guarantee that, if you disable autocalling, ipython will never call getattr() on your objects. This solves problems with code that has side-effects on attribute access. Note that TAB-completion inevitably does call getattr(), so not all forms of side-effects can be eliminated. - Unicode support for prompts. - Improvements to path handling under win32. Thanks to Ville and Jorgen for the patches. - Improvements to pager under win32. Contributed by Alexander Belchenko. - Demo class for interactive demos using ipython. - %pycat magic for showing syntax-highlighted python sources - support for download_url in setup.py, so PyPI (and setuptools) work transparently with ipython. - New exit/quit magics to exit, conditionally asking (%Exit/%Quit don't) - Automatically reopen the editor if your file has a syntax error in it (when using the %edit system). - New notation N-M for indicating the range of lines N,...,M (including both endpoints), in magic commands such as %macro, %save and %edit. - The IPython instance has a new attribute, .meta, which is an empty namespace (an instance of 'class Bunch:pass'). This is meant to provide extension writers with a safe namespace to store metadata of any kind, without the risk of name clashes with IPython's internals. - Added tab-completion support for objects with Traits, a sophisticated type definition system for Python: http://code.enthought.com/traits. - Several patches related to Emacs support. Thanks to Alex Schmolck and John Barnard. - New 'smart' autocall mode, which avoids autocalling if a function with no arguments is the input. The old 'full' mode can be obtained by setting the autocall parameter in the ipythonrc to 2, or via the %autocall magic. - A large amount of internal reorganization and cleanup, to allow the code to be more readily moved over to the chainsaw branch (see below). - Many other small fixes and enhancements. The changelog has full details. Enjoy, and as usual please report any problems on the IPython lists. Regards, Fernando. From rurpy at yahoo.com Mon Jan 9 00:55:34 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 8 Jan 2006 21:55:34 -0800 Subject: Is 'everything' a refrence or isn't it? In-Reply-To: References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> Message-ID: <1136664144.464232.289760@g49g2000cwa.googlegroups.com> Fredrik Lundh wrote: ...snip... > afaik, the Python Language Reference never defines the word "reference". > It carefully defines words like "object" and "value", though, and terms like > "call by object" or "call by object reference" are perfectly understandable > if you use the words as they are defined in the language reference. It (sec. 3.1, "Objects, values and types") is not what I would call a good definition . About values it says only - that they are something that all objects have. - they can be mutable or immutable. It then has a few sentences about mutability, so after reading it you will know that, whatever a value is, it can be changed for some objects but not others. But what exactly it is that is being changed is still a mystery. Further down it talks about container objects "containing" references to other objects and of those being part of it's value. Part? What does it mean to contain? Can one determine from reading this, if an attribute value is part of the object's value? (I couldn't). On my list on Python Doc problems that need fixing, is "defintion of object values" and it has been on there for nearly a year. So I don't think referring people to the Language Reference is a good way to help them understand Python. Python badly needs a rewritten Language Reference. From maketo at ukato.freeshell.org Mon Jan 30 15:11:23 2006 From: maketo at ukato.freeshell.org (Ognen Duzlevski) Date: Mon, 30 Jan 2006 20:11:23 +0000 (UTC) Subject: dynamic class instantiation Message-ID: Hi, I have a "language definition" file, something along the lines of: page :: name : simple caption : simple function : complex function :: name : simple code : simple component :: name : simple type : simple dataset : complex etc. On the other hand as input I have .xml files of the type: WebPage Browser Visible Caption Countrylist dropdown $dropdownlist sqlSelect select countries from blah into $dropdownlist I have a parser that will go through the language definition file and produce the following as a separate .py file: class page(object): def __init__(): self.name = None self.caption = None self.functions = [] class function(object): def __init__(): self.name = None self.code = None Now I want to use something like xml.dom.minidom to "parse" the .xml file into a set of classes defined according to the "language definition" file. The parse() method from the xml.dom.minidom package will return a document instance and I can get the node name from it. Say I got "page" as a string. How do I go about instantiating a class from this piece of information? To make it more obvious how do I create the page() class based on the "page" string I have? I want to make this generic so for me the language definition file will contain pages, functions, datasets etc. but for someone else mileage will vary. Thanks, Ognen From mwm at mired.org Wed Jan 11 00:01:45 2006 From: mwm at mired.org (Mike Meyer) Date: Wed, 11 Jan 2006 00:01:45 -0500 Subject: Why keep identity-based equality comparison? References: <1136846444.954839.58960@g47g2000cwa.googlegroups.com> <8664oshoqb.fsf@bhuda.mired.org> Message-ID: <86irsrfjd2.fsf@bhuda.mired.org> Steven Bethard writes: > Not to advocate one way or the other, but how often do you use > heterogeneous containers? Pretty much everything I do has heterogenous containers of some sort or another. SQL queries made to DP API compliant modules return homogenous lists of heterogenous containers. The cgi module turns the request string into a dictionary-like container of objects with values of different types. Higher-level web interfaces go even further in this direction. The last thing I did that was both more than a script and didn't use either a database or a web front end was (IIRC) a media player for multiple media types. It revolved around lists of things to play, and the "things" in question could be any "playable" object - video or audio files, track on a CD, or a DVD, or even a playlist. Come to think of it, recursive data structures of this type - a container that contains a heterogenous list of things, possibly including instances of the container type itself - are pretty common. Pretty much every GUI package has something like it. All processors of SGML-based markup languages I've ever dealt with included something like it. MIME-encoded email does this. Page layout programs do this. Block-structured programming languages do this. And probably lots of others. These are things that in a language that used classes for carrying (and enforcing) type, all of these cases would be heterogenous lists of objects that were subtypes of some type, so maybe they would "really" be heterogenous. But then you're stuck with the interesting question: What's the type relationship between two objects a and b that allows them to be compared. This question is still interesting with duck typing. If anything, it's even more interesting. We have *at least two* different proposals for a different typing system in hand. For one, the answer is obvious. The OP proposed that equality only be allowed when the types explicitly allow it, instead of defaulting to typing by identity. In that one the answer is that all the types on the list have to boilerplate so they play together. Phrasing it that way makes it seem contrary to the spirit of Python, as not needing boilerplat is an oft-touted strength of Python. The other proposal - if I have it right - would not change the behavior of equality comparisons between objects of the same class, but would make comparisons between objects of different classes raise an exception instead of returning false by default. Since I didn't raise this proposal, I'll leave it up to someone else to explain under what conditions two objects that are both instances of some class are "the same type" or not. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From codecraig at gmail.com Mon Jan 23 14:00:03 2006 From: codecraig at gmail.com (py) Date: 23 Jan 2006 11:00:03 -0800 Subject: wxPython layout problem Message-ID: <1138042803.942797.102430@g43g2000cwa.googlegroups.com> I have the following code: [code] class MainFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE |wx.NO_FULL_REPAINT_ON_RESIZE) # build top area topSizer = self.buildTopPanel() # build input area inputSizer = self.buildInputPanel() mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(topSizer, 1, wx.EXPAND | wx.ALL, 5) mainSizer.Add(inputSizer, 1, wx.EXPAND | wx.ALL, 5) p = wx.Panel(self, wx.ID_ANY) p.SetSizer(mainSizer) s = wx.BoxSizer(wx.VERTICAL) s.Add(p, 1, wx.EXPAND) self.SetAutoLayout(True) self.SetSizer(s) self.Layout() def buildTopPanel(self): p = wx.Panel(self, wx.ID_ANY) self.text = wx.TextCtrl(p, wx.ID_ANY, style=wx.TE_MULTILINE | wx.SUNKEN_BORDER) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.text, 1, wx.EXPAND) return sizer def buildInputPanel(self): # the area to enter text self.text2 = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_MULTILINE | wx.SUNKEN_BORDER) # panel to add button to p = wx.Panel(self, wx.ID_ANY) self.buttonClick = wx.Button(p, wx.ID_ANY, "Click") hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self.buttonClick, 0, wx.ALIGN_CENTER) p.SetSizer(hsizer) # add the text control and button panel box = wx.BoxSizer(wx.HORIZONTAL) box.Add(self.text2, 1, wx.EXPAND) box.Add(p, 0, wx.EXPAND) return box if __name__ == "__main__": app = wx.PySimpleApp() frame = MainFrame(None, wx.ID_ANY, "Test") frame.Show() app.MainLoop() [/code] ....there are two problems. 1) i want the sizer (that is returned from buildTopPanel()) to fill the screen wide/tall. now the text control in it is very small in the upper-left corner. 2) the scroll bars and borders on the text controls dont appear until i mouse over them, any ideas? thanks From steve at holdenweb.com Wed Jan 11 01:57:06 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Jan 2006 06:57:06 +0000 Subject: Spelling mistakes! In-Reply-To: <20060110170407.131d9650@samwise.anansi> References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> <20060110170407.131d9650@samwise.anansi> Message-ID: Terry Hancock wrote: [...] > > The ideal of "don't repeat yourself" seems to get > nudged out by "repeat yourself exactly once" when it's > really important to get it right. ;-) > I suppose most readers aren't old enough to remember the punch card days, when you would hand your work in on coding sheets to the punch room and it would be punched onto cards using huge machines (anyone remember the 026 and 029 punches?). Before you got the cards back they were processed twice: one operator would actually punch the cards, and another would re-key the same input on a verifier machine that alerted them to any differences between what was on the card and what was keyed. > It's really just a fancy way to force you to proof-read your > own work carefully enough (which is tricky because you > tend to ignore stuff that's too repetitious). > That's why two different operators would do the punching and the verifying. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From escalation746 at yahoo.com Mon Jan 30 23:02:54 2006 From: escalation746 at yahoo.com (robin) Date: Tue, 31 Jan 2006 04:02:54 +0000 Subject: beta.python.org content References: Message-ID: Steve Holden wrote: >How does > > http://beta.python.org/about/beginners/ > >look? There are several things wrong with the interface. First, I count seven ways of formatting a link. This is approximately five too many and can be fixed as follows. "For Beginners" is italicised, supposedly to indicate it is the page we are currently on. This overloads the normal expected meaning of italics with something unexpected. And what is the point of a link to the current page? This should be plain text. "About" is a top-level menu which has been expanded; to indicate this there is a yellow bar. This is not necessary since the viewer can see the menu is expanded. :-) The menu items underneath an expanded heading should be in the same format, but offset. Same format says "menu"; offset says "child." The last menu items are in different formats yet again (typeface and size). I see no reason for this. Once this has been done there will be but two different ways of formatting a link: a menu and a link in the page body. In terms of page space, the horizontal bar at the top seems wasted. Perhaps the vertical bar is all that is needed? The other elements could be relocated. The menu is structured with a list and formatted with CSS. Good! Given that there is already a hierarchical organisation of the content voa the collapsing menu bar, I do not think that another representation of this is required above the main page text. I would ditch the link trail. Overall, the look is very "safe corporate". I myself would have gone for a funkier (though still elegant) look. The energy of the Python community is not being communicated. The vim of the language is diluted. This is not playing to Python's strengths. Yes, i have been known to do this for a living. Had I been aware earlier, I would have been happy to help with the redesign. How can I now? P.S. I am not averse to the new logo. It is professional, clean, and symbolic. Maybe there are more ideal choices but we have to get beyond little green cartoon snakes eventually. ----- robin noisetheatre.blogspot.com From peter at engcorp.com Mon Jan 30 06:53:13 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 30 Jan 2006 06:53:13 -0500 Subject: webbrowser module + urls ending in .py = a security hole? In-Reply-To: <1138593557.824516.116400@g14g2000cwa.googlegroups.com> References: <1138593557.824516.116400@g14g2000cwa.googlegroups.com> Message-ID: Blair P. Houghton wrote: > I was messing around with the webbrowser module and decided it was > pretty cool to have the browser open a URL from within a python script, > so I wrote a short script to open a local file the same way, using the > script file as an example target: > > # browser-test.py > import webbrowser > import sys > pathname = sys.argv[0] > protocol = 'file://' > url = protocol + pathname > webbrowser.open(url) > > And what I got, instead of a browser window with the text of my script, > was a sequence of DOS windows popping up and disappearing. > > Apparently that's because either Windows (XP SP2) or the browser > (Firefox) was interpreting the .py file extension and running Python to > execute it. > > So is this a known (mis)feature, and will it happen if I chance to use > webbrowser.open() on a remote .py file? What happens when you load a remote .py file using the web browser directly? With Firefox on my machine, it just displays the file, as expected, whether loaded via webbrowser.open() or not. Make sure you're testing with the same browser that webbrowser loads (try a regular HTML file first if you're not sure which that is). > Because if so, it's a king-hell security hole. It might probably worth a warning in the docs, but it's no larger a security hole than the browser itself already has. If your browser is configured to load files of a given type directly into a particular application without first checking with you if you want it to do so, you're potentially screwed already. But is Firefox really your default browser? The webbrowser module could be loading Internet Explorer on your machine, and we all know just how safe *that* is... -Peter From bbands at gmail.com Mon Jan 30 12:56:40 2006 From: bbands at gmail.com (BBands) Date: 30 Jan 2006 09:56:40 -0800 Subject: Fuzzy Lookups References: <1138635665.956131.130630@f14g2000cwb.googlegroups.com> <446r5pFl87rU1@uni-berlin.de> Message-ID: <1138643800.320655.289820@g49g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > I did a levenshtein-fuzzy-search myself, however I enhanced my version by > normalizing the distance the following way: Thanks for the snippet. I agree that normalizing is important. A distance of three is one thing when your strings are long, but quite another when they are short. I'd been thinking about something along these lines myself, but hadn't gotten there yet. It'll be interesting to have a look at the distribution of the normalized numbers, I'd guess that there may be a rough threshold that effectively separates the wheat from the chaff. jab From calfdog at yahoo.com Fri Jan 13 15:00:04 2006 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 13 Jan 2006 12:00:04 -0800 Subject: How login & download file from remote web site? Passwords a problem? References: <1136829288.042780.112350@g14g2000cwa.googlegroups.com> Message-ID: <1137182404.542837.66990@g43g2000cwa.googlegroups.com> ################################ # Quick and dirty script example from win32com.client import DispatchEx import time def wait(ie): while ie.Busy: time.sleep(0.1) while ie.Document.ReadyState != 'complete': time.sleep(0.1) #instaniate a new ie object so you can call it's methods and properties...etc.. ie = DispatchEx('InternetExplorer.Application') # You need to make it Visible ie.Visible = 1 # Navigate to the page ie.Navigate('mail.yahoo.com') wait(ie) # important to wait for the doc to load # Enter User info and submit the form since it uses submit # If the button had a name attribute # You could also use ie.Document.login_form.buttonName.Click # ieObject.Document.FormName.TexboxName.value ="??" ie.Document.login_form.username.value="MyName" ie.Document.login_form.passwd.value="Mypasswd" ie.Document.login_form.submit() Enjoy Rob M http://pamie.sourceforge.net From deets at nospam.web.de Sat Jan 21 15:46:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 21 Jan 2006 21:46:14 +0100 Subject: "Dynamic" website content In-Reply-To: <1137872523.362604.187800@g47g2000cwa.googlegroups.com> References: <1137865920.640479.106600@g43g2000cwa.googlegroups.com> <43fcqlF1n7dfsU1@uni-berlin.de> <1137872523.362604.187800@g47g2000cwa.googlegroups.com> Message-ID: <43fksnF1nc40mU1@uni-berlin.de> sophie_newbie schrieb: > To give you a better explaination of what I want, you could visit > www.pat2pdf.org. > > Type in 123456 as the patent number, you see what it does? It tells the > user that it is requesting the various TIFF images and then displays > the link to the PDF file that it has created. > > This is exactly what I want to do, so if anyone has any idea how it is > done I would be greatful. > > I'm not asking how to get the TIFF files of create the PDF etc, that is > grand, just how it updates the screen with its progress like that... It seems that they just fetch the tiff and then write "Fetched %i
\n" into the page. The important thing then is to flush the stdout, so that the data is actually transmitted over the network. And I guess you have to provide a header that accounts for the number of bytes you want to write (the total bytes of the html-page that is), by specifying something equals or maybe greater than the overall page. Regards, Diez From raims at dot.com Sat Jan 14 03:39:12 2006 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 14 Jan 2006 09:39:12 +0100 Subject: Pythonic wrappers for SQL? References: Message-ID: Il 2006-01-14, Kenneth McDonald ha scritto: > I need to do some data manipulation, and SQLite is a nice little > product for it, except of course that I'd need to write SQL. Are > there any good libraries out there that let one write (basic) queries > in a Pythonic syntax, rather than directly in SQL? You need an ORM Try SQLAlchemy - http://sqlalchemy.org Have fun -- Lawrence - http://www.oluyede.org/blog "Anyone can freely use whatever he wants but the light at the end of the tunnel for most of his problems is Python" From fredrik at pythonware.com Tue Jan 17 16:48:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Jan 2006 22:48:24 +0100 Subject: Can't compile References: <43c6ed02$0$22794$9b622d9e@news.freenet.de> <1137522158.831467.233930@g14g2000cwa.googlegroups.com> Message-ID: "llothar" wrote: > Here i jump into this thread. > With this option the configure script runs well. > But then i get a compile error in complexobject. so what did the compiler say ? have you tried googling for relevant portions of the error message ? could this be the problem you're seeing ? http://www.python.org/sf/1276509 (see the comments for a workaround) From nyamatongwe+thunder at gmail.com Mon Jan 16 21:04:46 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 17 Jan 2006 02:04:46 GMT Subject: Shrinky-dink Python (also, non-Unicode Python build is broken) In-Reply-To: References: <1137435559.804230.11820@g44g2000cwa.googlegroups.com> Message-ID: <2hYyf.218856$V7.104139@news-server.bigpond.net.au> Giovanni Bajo: > - There will be some opposition to the obvious policy of "keeping the bare > minimum inside the DLL" because of inefficiencies in the Python build > system. It is also non-optimal for those that do want the full set of modules as separate files can add overhead for block sizing (both on disk and in memory, executables pad out each section to some block size), by requiring more load-time inter-module fixups, and by not allowing the linker to perform some optimizations. It'd be worthwhile seeing if the DLL would speed up or shrink if whole program optimization was turned on. Neil From dmh2000 at gmail.com Mon Jan 30 19:29:15 2006 From: dmh2000 at gmail.com (dmh2000) Date: 30 Jan 2006 16:29:15 -0800 Subject: triple quoted strings as comments Message-ID: <1138667355.631379.249770@o13g2000cwo.googlegroups.com> I recently complained elsewhere that Python doesn't have multiline comments. i was told to use triple quoted strings to make multiline comments. My question is that since a triple quoted string is actually a language construct, does it use cause a runtime construction of a string which is then discarded, or is the runtime smart enough to see that it isn't used and so it doesn't construct it? example def fun(self): """doc comment comment line 2 """ x = 1 y = 2 """does this triple quoted string used as a comment cause something to happen at runtime beyond just skipping over it? Such as allocation of memory for a string or worse yet garbage collection? or not? """ z = x + y ... dave howard From maxerickson at gmail.com Sat Jan 14 14:03:25 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sat, 14 Jan 2006 19:03:25 +0000 (UTC) Subject: Recursive tree list from dictionary References: <43C93A6B.3020503@eastlink.ca> Message-ID: David Pratt wrote in news:43C93A6B.3020503 at eastlink.ca: > Hi. I am wanting to create a tree list result structure from a > dictionary to categorize results. The dictionary contains elements > that identify its parent. The levels of categorization is not fixed, > so there is a need for the code to be recursive to drill down to the > lowest level. I have contrived a small source and result list to > illustrate: > >>> imd=dict() >>> for d in source_list: par=d['parent'] v=d['title'] try: imd[par].append(v) except: imd[par]=[v] >>> imd {'Project': ['Geometries', 'Verticals'], 'Geometry': ['Points', 'Layers', 'Water'], 'root': ['Project', 'Geometry', 'Soil'], 'Soil': ['Soiltypes']} >>> And then do whatever you need to do from here... max From roccomoretti at hotpop.com Tue Jan 3 13:09:49 2006 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 03 Jan 2006 12:09:49 -0600 Subject: One-step multiples list generation? In-Reply-To: References: <43bab67c@news.bezeqint.net> <43babb0b$0$15459$636a55ce@news.free.fr> Message-ID: Rocco Moretti wrote: > Damien Wyart wrote: > >> * Efrat Regev in comp.lang.python: >> >>> Suppose I have some non-numerical Foo and would like to create a list >>> of 20 Foo-s. Is there a one-step method (not a loop) of doing so? >> >> >> >> Maybe : >> >> [ Foo ] * 20 >> >> or, more verbose, >> >> [ Foo for _ in range(20) ] >> > > If Foo is mutable, keep this in mind: > > >>> a = [ [] ]*20 # A list of 20 empty lists > >>> print id(a[0]) == id(a[1]) > True > >>> a[0].append(1) > >>> print a > [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], > [1], [1], [1], [1], [1], [1]] > >>> > >>> b = [ [] for _ in range(20) ] # A list of 20 empty lists > >>> print id(b[0]) == id(b[1]) > False > >>> b[0].append(1) > >>> print b > [[1], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], > [], [], []] > Oh, but also: >>> Foo = [] >>> c = [ Foo for _ in range(20) ] # A list of 20 empty lists >>> print id(c[0]) == id(c[1]) True >>> c[0].append(1) >>> print c [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] (The difference with the 'b' case is that a new list is created each "time around", in the other cases, the same list is reused. From dpickles at pacbell.net Thu Jan 12 21:36:33 2006 From: dpickles at pacbell.net (dpickles at pacbell.net) Date: 12 Jan 2006 18:36:33 -0800 Subject: How to get Windows system information? Message-ID: <1137119793.573919.324960@g49g2000cwa.googlegroups.com> Does anybody know how to get the: Free hard disk space Amount of CPU load and Amount of RAM used on windows? I am making an artificial intelligence program that has "moods" based on how much stress the system is under, based on these parameters. I think it could possibly be done via COM. I am not looking for a cross-platform solution- just something that will work on Windows. Thank you for your help! From wgandhi at gmail.com Sat Jan 7 04:08:10 2006 From: wgandhi at gmail.com (Wish) Date: 7 Jan 2006 01:08:10 -0800 Subject: use browser setting for internet Message-ID: <1136624890.578505.323250@f14g2000cwb.googlegroups.com> Hi I have a problem with my script in python which uses xmlrpc. The script loses internet connection when it is used behind a firewall. I realize that the firewall is specified by using the http_proxy environment variable. However, the proxy server is automatically configured. I dont have access to its port or the IP. I have seen applications which have a select box to use the internet connection setting of the browser to connect to the web. I dont know how to access this connection setting in Python. Any help will be much appreciated.. -Wish From deliverable at gmail.com Tue Jan 17 18:35:48 2006 From: deliverable at gmail.com (braver) Date: 17 Jan 2006 15:35:48 -0800 Subject: magical expanding hash References: <1137478291.342584.83030@g47g2000cwa.googlegroups.com> <1137535500.430719.198090@f14g2000cwb.googlegroups.com> <1137538493.408255.293500@z14g2000cwz.googlegroups.com> <7xslrmo3si.fsf@ruckus.brouhaha.com> Message-ID: <1137540948.332979.270440@g49g2000cwa.googlegroups.com> Well, I know some python, but since there are powerful and magical features in it, I just wonder whether there're some which address this issue better than others. From mwm at mired.org Wed Jan 11 09:48:48 2006 From: mwm at mired.org (Mike Meyer) Date: Wed, 11 Jan 2006 09:48:48 -0500 Subject: Spelling mistakes! References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> <20060110170407.131d9650@samwise.anansi> Message-ID: <86psmy4y7j.fsf@bhuda.mired.org> Dennis Lee Bieber writes: > On Wed, 11 Jan 2006 06:57:06 +0000, Steve Holden > declaimed the following in comp.lang.python: >> I suppose most readers aren't old enough to remember the punch card >> days, when you would hand your work in on coding sheets to the punch >> room and it would be punched onto cards using huge machines (anyone >> remember the 026 and 029 punches?). > FORTRAN and COBOL on 029s -- and had to submit the school ID card to > check-out a drum; coding a drum card was actually taught in the COBOL > class. Pretty much everything on the 029. Like you, I had to punch things myself. And had a drum card with one track for FORTRAN and a second for ALGOL. Of course, I was employed to work with them. At one point, I actually "helped" someone do data processing with the card sorter. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From carsten at uniqsys.com Tue Jan 17 11:29:48 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Jan 2006 11:29:48 -0500 Subject: rational numbers In-Reply-To: <7xhd82lt91.fsf@ruckus.brouhaha.com> References: <7xhd82lt91.fsf@ruckus.brouhaha.com> Message-ID: <1137515388.9814.7.camel@dot.uniqsys.com> On Tue, 2006-01-17 at 11:22, Paul Rubin wrote: > Sch?le Daniel writes: > > does anybody know modules which make rational numbers available? > > Try gmpy.mpq (google for gmpy). > > > and are there considerations to add them to the core, like > > complex numbers (maybe in Python 3) > > I don't think it's been discussed much. Somebody must have discussed it. There is a rejected PEP for adding a Rational type to python: http://www.python.org/peps/pep-0239.html -Carsten From fabio.pliger at gmail.com Sat Jan 28 19:28:51 2006 From: fabio.pliger at gmail.com (Mr BigSmoke) Date: 28 Jan 2006 16:28:51 -0800 Subject: Data Crunching and Charting.... In-Reply-To: <1138491779.072003.263680@z14g2000cwz.googlegroups.com> References: <1138491779.072003.263680@z14g2000cwz.googlegroups.com> Message-ID: <1138494531.572240.118070@g47g2000cwa.googlegroups.com> Hi Tom. I had more or less the same problem about 1 year and a half ago... Since then i've tried either Matplotlib and chaco. I've started using matplotlib but for some features reason i've decided to use only chaco. Chaco is really cool but has some neg. points: - documentation is not really detailed and there are really few examples - not supported anymore (at least i've never found any place supporting it.. if anyone know bout any support tell me!!) - sometimes it's really hard to look into it's code to extend some classes... The data i have to plot goes from very few curves and ticks to about 10/12 curves, 15000 ticks and range from -1 to 100000+ in Y axis. Th plotting speed is good... but more data u plot, more problem u get!! Like, zooming feature is not very "solid", and get's worse with tons of data..., some features are missing (or at least i've never found them!! I'd be very happy if someone says that i'm wrong and shoe me them!!), like showing the values of th curvers when i pass the mouse on it, of the highlighting a point in the curve if i clck on it!! Fabio Pliger tbonejo at gmail.com wrote: > Hi all. > > Question: I have a project nearly complete written in VB.Net using > charts from 3rd party vendors...expensive, yes, fast, not really. The > data I am plotting is about 30 columns by 3000-9000 rows, all in a tab > delimited file(43 files total). My question is whether or not I can > accomplish the same in Python utilizing Matplotlib or Chaco for > plotting, at a much faster speed. In my app it takes a while to loop > through all the rows/columns to plot the data. Im just curious whether > there may be a big boost in performance using python. Also I use > spreadsheet style grids for displaying data. I was looking at the grid > control for wxpython and that seems a nice fit. Anyone with experience > with it have any opinions, Id appreciate them. Alot of the programming > I do deals with crunching data and charting it. Sometimes I wonder > whether python would be a much better canidate for this type of work > rather than what Im using now. > > > Thanks. > > > Tom From donn at u.washington.edu Fri Jan 27 15:30:49 2006 From: donn at u.washington.edu (Donn Cave) Date: Fri, 27 Jan 2006 12:30:49 -0800 Subject: writing large files quickly References: <11tkt7e4ehdo309@corp.supernews.com> <11tkv50bnr2daff@corp.supernews.com> Message-ID: In article , rbt wrote: > Won't work!? It's absolutely fabulous! I just need something big, quick > and zeros work great. > > How the heck does that make a 400 MB file that fast? It literally takes > a second or two while every other solution takes at least 2 - 5 minutes. > Awesome... thanks for the tip!!! Because it isn't really writing the zeros. You can make these files all day long and not run out of disk space, because this kind of file doesn't take very many blocks. The blocks that were never written are virtual blocks, inasmuch as read() at that location will cause the filesystem to return a block of NULs. Donn Cave, donn at u.washington.edu From rocky at panix.com Thu Jan 12 06:38:52 2006 From: rocky at panix.com (R. Bernstein) Date: 12 Jan 2006 06:38:52 -0500 Subject: setup.py vs autoconf install/uninstall, Message-ID: In making a release of the recent changes to pdb.py announce here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b4cb720ed359a733/fbd9f8fef9693e58#fbd9f8fef9693e58 I tried using setup.py. I think it's great that setup.py tries to obviate the need for "Make" by just doing everything. (In contrast to Perl's MakeMaker). But alas the problems I was running into was setup.py not doing enough (for just Python). Here were the problems I ran into. Perhaps someone will be able to enlighten me. 1. I didn't find a way to uninstall a package. 2. No overwrite install. When I tried to install a newer version of the pydb.py, setup.py didn't write over the old file even though the files were different and the time on the file installed over was older. I'm assuming it uses the version parameter in the setup call only. This isn't helpful in testing between release numbers. 3. How to get pydb.doc and pydb.py in the same directory? As python 2.2.4 is currently distributed, pdb.doc seems to want to be in the same directory as pdb.py. A little weird, but that's the way it is. After reading docs and trying various things I gave up. (At least for now). I was then pleasantly surprised to find that automake comes with macros for Python! (It doesn't have them for Perl.) But lest I get too elated, in trying one these out, I see that automake had a different notion of where to install python scripts than python uses. But no matter since autotools are sufficiently general (however ugly), I was able to patch around it as I've done so so many times. And again we have the same thing as was a concern about debuggers: there are so many configuration tools, only 3 mentioned above. Sigh. From tim at pollenation.net Wed Jan 18 07:44:31 2006 From: tim at pollenation.net (Tim Parkin) Date: Wed, 18 Jan 2006 12:44:31 +0000 Subject: New Python.org website ? In-Reply-To: <1137577199.871019.269770@g47g2000cwa.googlegroups.com> References: <43C4E198.2080107@holdenweb.com> <1137573186.943743.32150@g47g2000cwa.googlegroups.com> <1137577199.871019.269770@g47g2000cwa.googlegroups.com> Message-ID: <43CE382F.8090806@pollenation.net> Tim N. van der Leeuw wrote: > Steve, > > My apologies if this apppeared to be 'slagging'. I was trying to give > some feedback but I do realize that I don't have anything better to > offer yet to replace the pictures I dislike. > > Perhaps I should have withheld my criticisms until I could offer an > alternative. (Still thinking about what could be there instead of those > 3 pictures. But I'd like there to be some actual real Python content, > or links to events from the Python Events Calender; or perhaps links to > large python projects like Zope -- something that links to the major > parts of Python. Perhaps 1 picture that links to Python Web Development > including things like Zope, Django, etc; another picture that links to > a page giving overview of major IDEs for Python; and 3d picture that > links to page with Python Event calender... Something along those > lines. But I don't have any graphics for you.) > That sounds fine.. I think having a link to a high profile user of python would be very useful though. I agree the XP link is a bit shite. Hopefully we'd get the photos and links to success stories/events/software changing every now and again.. how about 1) High profile user of Python 2) Link to upcoming python event 3) Link to web development uses of python the only problem is 1) people will argue over which user of python to put up 2) This will probably just be pycon and europython.. which is no bad thing.. until we get more than two conferences at similar times.. which one should we show? 3) python isn't just about web development.. Suffice it to say we'll have some content and the example images will change every now and again. btw do you have a problem with using nasa or astrazeneca as example high profile users? Tim From grahn+nntp at snipabacken.dyndns.org Sun Jan 8 05:48:01 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 8 Jan 2006 10:48:01 GMT Subject: Spelling mistakes! References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> <7xr77ku8oz.fsf@ruckus.brouhaha.com> <17343.7834.618161.400185@montanaro.dyndns.org> <20060106234233.3b98d896@samwise.anansi> <1136626891.811811.111320@f14g2000cwb.googlegroups.com> Message-ID: On Sat, 07 Jan 2006 08:57:24 -0500, Peter Hansen wrote: [British/American English] > Hah! Canucks r00l! Most of those words look about equally good to us > most of the time. (And it's not because of the beer!) (But our beer > r00lz too.) And so does "primairy", "secondairy" and similar "frenchifications" of English words, to some of you ... I'll think twice before agreeing to maintain software written by people from Montr?al again. (Fortunately, that software was written in a static programming language.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From maha.murali at gmail.com Fri Jan 27 18:54:30 2006 From: maha.murali at gmail.com (Murali) Date: 27 Jan 2006 15:54:30 -0800 Subject: Python String Substitution In-Reply-To: <43da1dbb.375833790@news.oz.net> References: <1138318847.465117.49040@z14g2000cwz.googlegroups.com> <43da1dbb.375833790@news.oz.net> Message-ID: <1138406070.132291.254440@g14g2000cwa.googlegroups.com> No. I dont have a real life example. I was explaining % substitution to somebody and realized that I have only used it in the form where the keys are strings. Was wondering if there is some special syntax already part of python with which I can lookup the dictionary using a tuple as a key. - Murali From godwinburby at gmail.com Wed Jan 11 02:41:36 2006 From: godwinburby at gmail.com (Godwin Burby) Date: 10 Jan 2006 23:41:36 -0800 Subject: Change Gateway Programmatically In-Reply-To: <1136962324.786875.148980@g44g2000cwa.googlegroups.com> References: <1136955246.375189.82840@g14g2000cwa.googlegroups.com> <1136962324.786875.148980@g44g2000cwa.googlegroups.com> Message-ID: <1136965296.239142.102620@f14g2000cwb.googlegroups.com> Well netsh turned out to be the perfect solution for my problem(even though doing it in python would have given me some kicks). I managed it with two .bat files for toggling the gateway ips. Thank you friend. From michele.simionato at gmail.com Mon Jan 9 05:28:32 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Jan 2006 02:28:32 -0800 Subject: Spelling mistakes! In-Reply-To: References: <1136561441.370723.188280@f14g2000cwb.googlegroups.com> <1136563024.045851.42700@g14g2000cwa.googlegroups.com> Message-ID: <1136802512.352459.87620@g44g2000cwa.googlegroups.com> skip at pobox.com wrote: > The OP sort of seemed like he was pining > for attribute declarations. __slots__ is the closest thing Python has to > them. I don't use them myself (since I've basically avoided new-style > classes so far). > > Skip No, slots are a memory optimization trick and should NOT be used as declarations. You can find a few posts of the Martellibot on the subject. I even wrote a recipe to tell people who want static declarations how to implement them without slots: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 Michele Simionato From cito at online.de Sun Jan 22 18:38:44 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 23 Jan 2006 00:38:44 +0100 Subject: Making dir's In-Reply-To: References: Message-ID: yawgmoth7 wrote: > os.mkdir("C") > os.mkdir("Python") > os.mkdir("ASM") > > And so on. That is not very practical, and I wish to change it. I was > wondering if there were any other methods to which I could do this, I > was thinking maybe I could put the dir names in a dictionary then have > something like: > os.mkdir(thedictname) For what do you need a dictionary? A list or a set should suffice: [os.mkdir(d) for d in "C Python ASM".split()] If some of these directories could already exist, this may be safer: for d in "C Python ASM".split(): try: os.mkdir(d) except OSError: pass Another possibility is the following: os.system("mkdir C Python ASM") -- Chris From pwatson at redlinepy.com Fri Jan 13 14:11:52 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 13 Jan 2006 13:11:52 -0600 Subject: Creating shortcuts? In-Reply-To: References: Message-ID: <43C7FB78.4090604@redlinepy.com> Ron Griswold wrote: > Hi Dennis, > > Yes, I am equating a unix soft link to a windows shortcut. Both act as > links to a file or directory. > > I have found that windows shortcuts do appear in linux dir listings with > a .lnk extension, however the file is meaningless to linux. On the other > hand, a linux soft link does not appear in a windows directory listing, > not that I really want it to. > > As for os.link and os.symlink, these appear to be unix specific. It > would be nice if os.symlink, when run on windows, would create a > shortcut. > > Thanks, > > Ron Griswold > Character TD > R!OT Pictures > rgriswold at rioting.com > > > -----Original Message----- > From: python-list-bounces+rgriswold=rioting.com at python.org > [mailto:python-list-bounces+rgriswold=rioting.com at python.org] On Behalf > Of Dennis Lee Bieber > Sent: Friday, January 13, 2006 12:26 AM > To: python-list at python.org > Subject: Re: Creating shortcuts? > > On Thu, 12 Jan 2006 22:53:42 -0800, "Ron Griswold" > declaimed the following in comp.lang.python: > > >>Is it possible to create a shortcut to a file in Python? I need to do >>this in both win32 and OSX. I've already got it covered in Linux by >>system(ln...). >> > > > Are you equating a Windows "shortcut" to a Unix "link"? Soft > link, > at that, I suspect -- as a hard link can be done using os.link(), though > a soft link can be done with os.symlink(). Lets see if my terminology is > correct: a "hard link" is an additional directory entry pointing to a > pre-existing file (with a count of how many entries exist for the file); > a "soft link" is basically a special file that contains the full path to > the actual file (and hence, could cross file system boundaries). > > I don't think Windows "shortcuts" are the same thing (as my > memory > struggles, I have vague inklings that NTFS actually supports Unix-like > links, but practically nothing uses them). At best, they may be similar > to a soft link, being a particular type of file, being that they are > files with a ".lnk" extension (and hidden by the OS normally) UNIX links and Windows .lnk files are not the same thing. Links on UNIX, both soft and hard, are known by the filesystem. .lnk files on Windows are recognized by the OS as indicating that a different file is to be used. From lycka at carmen.se Thu Jan 26 09:25:49 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 26 Jan 2006 15:25:49 +0100 Subject: Mining strings from a HTML document. In-Reply-To: <1138269295.780765.28650@g43g2000cwa.googlegroups.com> References: <1138181024.289284.65470@g44g2000cwa.googlegroups.com> <1138201452.564308.306370@g47g2000cwa.googlegroups.com> <1138203089.440178.144780@g14g2000cwa.googlegroups.com> <1138262401.530004.241170@g47g2000cwa.googlegroups.com> <1138269295.780765.28650@g43g2000cwa.googlegroups.com> Message-ID: Derick van Niekerk wrote: > Could you/anyone explain the 4 lines of code to me though? A crash > course in Python shorthand? What does it mean when you use two sets of > brackets as in : beg = [1,0][text.startswith(s1)] ? It's not as strange as it looks. [1,0] is a list. If you put [] after a list, it's for indexing, right? (Unless there's one or two ':' somehere, in which case it's slicing.) text.startswith(s1) evaluates to True or False, which is equivalent to 1 or 0 in a numerical context. [1,0][0] is 1, and [1,0][1] is 0, so you could say that it's a somewhat contrieved way of writing "beg = int(not text.startswith(s1))" or "beg = 1 - text.startswith(s1)" From fredrik at pythonware.com Thu Jan 26 03:16:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Jan 2006 09:16:58 +0100 Subject: Problem compiling Tkinter program with bmp images using py2 References: Message-ID: erkidevries at pandora.be wrote: > and put them on the widgets like this: > > Label(win, text=message, background=rgb(150,150,120), image=photo2).pack() > ... > > Now, I want the same program to run as exe file on another computer, > so I compiled it with py2exe. I copied the bmp's to the same folder as > my executable. When I try to run the compiled exe i get: > > Traceback (most recent call last): > File "make_ma2.py", line 461, in ? > File "PIL\Image.pyo", line 1745, in open > IOError: cannot identify image file (did you try googling for the error message?) > Are there specific things to take care of when compiling a tkinter program > with bitmap backgrounds? it's PIL that's complaining, not Tkinter. PIL uses dynamic loading of format drivers, which means that py2exe won't find them. the easiest way to fix this is to import the drivers you need in your main program; see e.g. http://starship.python.net/crew/theller/moin.cgi/PIL_20and_20py2exe From python.list at tim.thechases.com Wed Jan 25 15:01:35 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 25 Jan 2006 14:01:35 -0600 Subject: float formatting In-Reply-To: <1138217547.670044.29970@g43g2000cwa.googlegroups.com> References: <1138217547.670044.29970@g43g2000cwa.googlegroups.com> Message-ID: <43D7D91F.3080107@tim.thechases.com> > for i in range(2,7): > print "|" + "%10.if" % num2 + "|" #where i would be the iteration > and the num of decimal places >>> for places in range(2,7): ... print "|%10.*f|" % (places, num2) ... | 42.99| | 42.988| | 42.9877| | 42.98765| | 42.987654| seems to do the trick. It exploits the "*" operator for specifying the precision as detailed in item #4 at http://docs.python.org/lib/typesseq-strings.html which is the same as in C/C++ formatting strings. -tkc From steve at holdenweb.com Thu Jan 12 13:28:54 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 12 Jan 2006 18:28:54 +0000 Subject: How can I make a dictionary that marks itself when it's modified? In-Reply-To: References: <1137085367.380996.159110@g49g2000cwa.googlegroups.com> Message-ID: garabik-news-2005-05 at kassiopeia.juls.savba.sk wrote: > sandravandale at yahoo.com wrote: > >>It's important that I can read the contents of the dict without >>flagging it as modified, but I want it to set the flag the moment I add >>a new element or alter an existing one (the values in the dict are >>mutable), this is what makes it difficult. Because the values are >>mutable I don't think you can tell the difference between a read and a >>write without making some sort of wrapper around them. >> >>Still, I'd love to hear how you guys would do it. > > > if the dictionary is small and speed not important, you can wrap it > in a class catching __getitem__ and __setitem__ and testing > if repr(self) changes. > > d = {1: [a, b], 2: [b, c]} d[1][0] = 3 How would this work? __getitem__() will be called once, to get a reference to the list, and so there's no opportunity to compare the 'before' and 'after' repr() values. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From twic at urchin.earth.li Tue Jan 17 18:36:57 2006 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 17 Jan 2006 23:36:57 +0000 Subject: Web application design question (long) In-Reply-To: <1137457250.594109.12360@g49g2000cwa.googlegroups.com> References: <1137457250.594109.12360@g49g2000cwa.googlegroups.com> Message-ID: On Tue, 16 Jan 2006, Fried Egg wrote: > I am interested if anyone can shed any light on a web application > problem, I'm not going to help you with that, but i am going to mention the Dada Engine: http://dev.null.org/dadaengine/ And its most famous incarnation, the Postmodernism Generator: http://www.elsewhere.org/pomo tom -- Taking care of business From robert.kern at gmail.com Sat Jan 28 20:25:47 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 28 Jan 2006 19:25:47 -0600 Subject: Data Crunching and Charting.... In-Reply-To: <1138494531.572240.118070@g47g2000cwa.googlegroups.com> References: <1138491779.072003.263680@z14g2000cwz.googlegroups.com> <1138494531.572240.118070@g47g2000cwa.googlegroups.com> Message-ID: Mr BigSmoke wrote: > Hi Tom. > > I had more or less the same problem about 1 year and a half ago... > Since then i've tried either Matplotlib and chaco. I've started using > matplotlib but for some features reason i've decided to use only chaco. > Chaco is really cool but has some neg. points: > - documentation is not really detailed and there are really few > examples > - not supported anymore (at least i've never found any place supporting > it.. if anyone know bout any support tell me!!) http://code.enthought.com/chaco/ You're probably using an extremely old version. -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From paddy3118 at netscape.net Thu Jan 26 15:28:28 2006 From: paddy3118 at netscape.net (Paddy) Date: 26 Jan 2006 12:28:28 -0800 Subject: beta.python.org content In-Reply-To: References: Message-ID: <1138307308.580744.71400@g49g2000cwa.googlegroups.com> I find it much better than the current site, thank you! Whilst reading, http://beta.python.org/about/ I had some slight niggles. What do you think about the following changes? About Python Python is an agile programming language often compared to Tcl, Perl, Ruby, Scheme or Java. While it has much in common with them it also has unique features that set it apart. * remarkable power with very clear syntax * fully modular, with modules in individual files, or packages: a hierarchical arrangement of modules for larger projects. * intuitive object orientation, but also supports a functional style of programming too. * exception-based error handling * very high level dynamic data types that are easy to use. * interfaces to many system calls and libraries * access to multiple GUI toolkits (X11, Motif, Tk, Mac, MFC, wxWidgets) * extensions and modules easily written in C, C++ or Python * embeddable within applications needing a scripting interface - Paddy. From steve at REMOVEMEcyber.com.au Wed Jan 4 21:00:54 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 05 Jan 2006 13:00:54 +1100 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <86acebd1y2.fsf@bhuda.mired.org> Message-ID: <43BC7DD6.9050805@REMOVEMEcyber.com.au> Mike Meyer wrote: > Steven D'Aprano writes: > >>On Wed, 04 Jan 2006 10:54:17 -0800, KraftDiner wrote: >> >>>I was under the assumption that everything in python was a refrence... >>>so if I code this: >>>lst = [1,2,3] >>>for i in lst: >>> if i==2: >>> i = 4 >>>print lst >>>I though the contents of lst would be modified.. (After reading that >>>'everything' is a refrence.) >> >>See, this confusion is precisely why I get the urge to slap people who >>describe Python as "call by reference". It isn't. > > > Except this doesn't have *anything at all* to do with python being (or > not being) call by reference. This is a confusion about name binding > vs. assignment to a variable. The proper people to slap around for > this case are the ones who talk about assignment to a variable. Mike, you are wrong. Not about talk about "assigning to variables" being harmful, I agree with that. But this confusion is *exactly* about the call by reference misunderstanding. How do I know this? Because the Original Poster said so! He said, to paraphrase, "Hey, I thought Python was call by reference, but I tried this, and it didn't work, what gives???" This is not an isolated case either. You can't get any clearer than that. Talk about call by reference leads to confusion and incorrect assumptions about Python's behaviour. End of story. >>It is "call by object" -- you pass around *objects*. Internally, this is >>quite fast, because the entire object doesn't need to be moved, only >>pointers to objects, but you don't get the behaviour of either call by >>reference or call by value. > > > No, you get *exactly* that behavior from call by reference when you > start passing objects around by reference. Who cares what Python does internally? It is strictly irrelevant whether Python internally passes around pointers, or copies values, or sometimes one or the other. > If I declare a C object as > "struct foo bar" and do the C "call-by-reference" hack of passing > &bar, I get the exact same behavior I get when I pass an object > referenced by bar to a Python subroutine. It is not a question of whether Python's behaviour is *sometimes* the same as call by reference. The question whether Python's behaviour is *always* the same as CBR, and it is not. Regardless of the reasons, Python does not behave like CBR in other languages, and it is harmful to imply that it does. Likewise, you shouldn't argue that Python is obviously call by value just because *sometimes* it has the same behaviour as CBV. I mean, come on! A whole bunch of people argue black and blue that Python "obviously" is call by reference, and another vocal bunch argue that it is "obviously" call by value. Isn't that the tiniest hint that Python -- not the underlying C/Java/Python/whatever implementation, but Python the language --- does not fall into either camp, but is doing something that sometimes looks like one and sometimes like the other? Just google on "Python is call by value" and "Python is call by reference" -- including quotes -- to see this argument come up time and time again, year after year after year. And all because of some false dichotomy that CBR and CBV are the only two valid descriptions of a computer language. -- Steven. From kenneth.m.mcdonald at sbcglobal.net Wed Jan 11 15:05:35 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 11 Jan 2006 14:05:35 -0600 Subject: Programming Eclipse plugins in Jython? Message-ID: <7ABC78D1-98BC-403D-8F95-9565D5EA17C8@sbcglobal.net> Is it easy or difficult to implement Eclipse plugins in Jython? And if the former, are there any starter's guides you could recommend? The desire is an editor plugin for a syntactically very simple proprietary language. I'd like to have paren checking, syntax colorization and (to start with at least) a few other small features. Unfortunately, there's quite a hump in learning the Eclipse API well enough to do even simple things (or at least that's what my reading seems to indicate), and I was wondering if I can cheat and use Jython to simplify the process. Thanks, Ken From wegwerp at gmail.com Mon Jan 2 13:07:47 2006 From: wegwerp at gmail.com (Bas) Date: 2 Jan 2006 10:07:47 -0800 Subject: important for me!! References: Message-ID: <1136225267.779645.188880@f14g2000cwb.googlegroups.com> Read this first: http://www.catb.org/~esr/faqs/smart-questions.html and then try again. From mwm at mired.org Sat Jan 14 17:33:07 2006 From: mwm at mired.org (Mike Meyer) Date: Sat, 14 Jan 2006 17:33:07 -0500 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1137111113.310683.178770@o13g2000cwo.googlegroups.com> <1137212572.427212@jetspin.drizzle.com> Message-ID: <864q46wicc.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 14 Jan 2006 04:22:53 +0000, Donn Cave wrote: >> |> 2. What is the value of object()? >> [ I assume you mean, the object returned by object(). ] >> It doesn't really have a value. I can't think of any kind of >> computation that could use this object directly. > Here is one: > obj_inst = object() > def computation(data): > global obj_inst > if data is obj_inst: > print FirstOneThousandPrimes() > else: > print TextOfWarAndPeace() > It isn't a particularly useful computation, but it is a computation. And it doesn't use the value of the object instance, it uses it's identity. Any type that doesn't have hacks to share instances with the same value could be used in this way. > Let's try not to be too deep here, okay? Before asking "what is the value > of foo?", we have to agree on what we mean by "value". It is easy to tie > yourself into knots here. I think you want to settle what we mean by "type" first. Or maybe in parallel. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fuzzyman at gmail.com Thu Jan 19 09:34:12 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 19 Jan 2006 06:34:12 -0800 Subject: Can a simple a==b 'hang' in and endless loop? In-Reply-To: References: <1137596782.678344.136630@g43g2000cwa.googlegroups.com> <6qats11f4ur96qucp2q5p2pudgevm7cjfh@4ax.com> <43CF5118.5030000@REMOVEMEcyber.com.au> Message-ID: <1137681252.101927.323800@g43g2000cwa.googlegroups.com> Claudio Grondi wrote: [snip..] > Wow! I haven't got this evil idea myself yet (even if as I understand > there is no problem to achieve similar thing also in C), so I have > learned a bit more about Python again. Am I right supposing, that this > becomes possible because the .append() goes not that far to try to > generate the actual list (getting trapped in the endless loop) and only > lets the second list element point to the object with the list itself. I think you've got this. a = [] Here a is a reference to a list object. a.append(a) As mentioend previously - you pass around references (names), not values. Here you've put a reference to the list object a as the first member of the list a. > The trouble with it becomes apparent later when working with such bad > defined list as it is the case when applying the '==' operator to it. > Thank you for sharing this with me, but again ... > > this is still _not_ what I am looking for, because Python detects here > the problem and throws an exception. What I am looking for is an endless > loop where there is no any response from Python about a problem. > Loops tend to be caused by function or method calls - so they add frames to the stack and get detected as recursion. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Claudio From larry.bates at websafe.com Tue Jan 17 10:11:24 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Jan 2006 09:11:24 -0600 Subject: ConfigParser: writes a list but reads a string? In-Reply-To: References: Message-ID: <43CD091C.9020902@websafe.com> Terry Carroll wrote: > It looks like ConfigParser will accept a list to be writing to the > *.ini file; but when reading it back in, it treats it as a string. > > Example: > > ############################### > import ConfigParser > def whatzit(thingname, thing): > print thingname, "value:", thing > print thingname, "length:", len(thing) > print thingname, type(thing) > > cfgfile = "cfgtest.ini" > config1 = ConfigParser.ConfigParser() > config1.add_section("test") > > t1 = range(1,11) > config1.set("test", "testlist", t1) > outfile=open(cfgfile,"w") > config1.write(outfile) > outfile.close() > > config2 = ConfigParser.ConfigParser() > config2.read(cfgfile) > t2 = config2.get("test","testlist") > > whatzit("t1", t1) > whatzit("t2", t2) > > ############################### > > Output is: > > t1 value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > t1 length: 10 > t1 > t2 value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > t2 length: 31 > t2 > > That is, t1 is a list of length 10, consisting of: > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > and is written out; but t2 is read back in as a string > "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" > of length 31. > > It took me a while to figure this out, since they looked identical in > print statements. > > Is there a pythonic way to read in a list from a .INI file with > ConfigParser? Is this expected behavior for ConfigParser? I would > not expect this conversion; rather, an exception when trying to write > the list if the list is not supported. > To read lists from .INI files I use following: listvalues=INI.get(section, option).split(',') where INI is an instance of ConfigParser There is the problem of if list items contain commas. -Larry Bates From coriolis_wong at yahoo.com.hk Fri Jan 6 22:48:18 2006 From: coriolis_wong at yahoo.com.hk (Ngai Kin Wong) Date: Sat, 7 Jan 2006 11:48:18 +0800 (CST) Subject: writing to DBase III format Message-ID: <20060107034818.45082.qmail@web50702.mail.yahoo.com> Hi, I want ot create a dbf file, the file is created,it can be opened by Excel but it cannot be opened by Access. Where is the error in my script. My script is as follows: #!/opt/bin/python2.3 import struct, datetime,itertools,time def dbfwriter(f, fieldnames, fieldspecs, records): """ Return a string suitable for writing directly to a binary dbf file. File f should be open for writing in a binary mode. Fieldnames should be no longer than ten characters and not include \x00. Fieldspecs are in the form (type, size, deci) where type is one of: C for ascii character data M for ascii character memo data (real memo fields not supported) D for datetime objects N for ints or decimal objects L for logical values 'T', 'F', or '?' size is the field width deci is the number of decimal places in the provided decimal object Records can be an iterable over the records (sequences of field values). """ # header info ver = 3 now = datetime.datetime.now() yr, mon, day = now.year-1900, now.month, now.day numrec = len(records) numfields = len(fieldspecs) lenheader = numfields * 32 + 33 # lenrecord = sum(field[1] for field in fieldspecs) + 1 num = 0 for field in fieldspecs : num = num + int(field[1]) lenrecord = num + 1 hdr = struct.pack(' From harlinseritt at yahoo.com Fri Jan 6 21:11:44 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 6 Jan 2006 18:11:44 -0800 Subject: Converting milliseconds to human time In-Reply-To: <1136575877.438052.92420@f14g2000cwb.googlegroups.com> References: <1136574769.150648.143290@g49g2000cwa.googlegroups.com> <1136575877.438052.92420@f14g2000cwb.googlegroups.com> Message-ID: <1136599904.550968.120390@g47g2000cwa.googlegroups.com> Thanks Dan, that would be perfect or close enough I should say. :-) Regards, Harlin Seritt From pierre_dot_barbier at _nospam_cirad.fr Mon Jan 16 09:54:22 2006 From: pierre_dot_barbier at _nospam_cirad.fr (Pierre Barbier de Reuille) Date: Mon, 16 Jan 2006 15:54:22 +0100 Subject: boost.python on Debian In-Reply-To: <87oe2c4a1j.fsf@localhost.localdomain> References: <87oe2c4a1j.fsf@localhost.localdomain> Message-ID: <43cbb2a2$0$19431$626a14ce@news.free.fr> Joe bloggs a ?crit : > Can anyone tell me how to get boost.python to work on Debian Sarge? > When I try to build the tutorial hello world example bjam reports: > > /usr/share/doc/libboost-doc/examples/libs/python/example/boost-build.jam > attempted to load the build system by invoking > > 'boost-build ../../../tools/build/v1 ;' > > but we were unable to find "bootstrap.jam" in the specified directory or > in BOOST_BUILD_PATH (searching > /usr/share/doc/libboost-doc/examples/libs/python/example/../../../tools/build/v1, > /usr/share/boost-build). > > I have looked for 'bootstrap.jam' but it doesn't exist on my system. > I suppose that the Debian boost package doesn't have the same structure as > the official one, and is missing some files. > Can anyone tell me how to fix this? Well, is : $ apt-get install libboost-python-dev a valid answer ? Because the Boost project itself maintains the debian packages, they are always very up-to-date ... Pierre From onurb at xiludom.gro Thu Jan 26 08:07:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 26 Jan 2006 14:07:04 +0100 Subject: While loop - print several times but on 1 line. In-Reply-To: <7A2Cf.39243$Kp.10844@southeast.rr.com> References: <7A2Cf.39243$Kp.10844@southeast.rr.com> Message-ID: <43d8c986$0$7361$626a14ce@news.free.fr> Jeffrey Schwab wrote: > Danny wrote: > >> Great! It's been solved. >> >> The line, as Glaudio said has a "," at the end and that makes it go >> onto one line, thanks so much man! >> >> var = 0 >> while <= 5: >> print a[t[var]], >> var = var +1 >> prints perfectly, thanks so much guys. > > > > Looping over indexes is kinda unpythonic in its own right. Is there > something magical about the number 5? > > for e in t: > print a[e], Or if you want to just iterate over a part of t: start = 0 end = 6 # end is not included for e in t[start:end]: print a[e]* -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From stuff at mailzilla.net Sun Jan 29 17:23:47 2006 From: stuff at mailzilla.net (stuff at mailzilla.net) Date: 29 Jan 2006 14:23:47 -0800 Subject: obtain client ip address from SimpleXMLRPCServer ? In-Reply-To: <43dab683$0$15789$14726298@news.sunsite.dk> References: <1138057187.923962.231310@g14g2000cwa.googlegroups.com> <43d6b4e2$0$15789$14726298@news.sunsite.dk> <1138337305.786914.300500@g14g2000cwa.googlegroups.com> <43dab683$0$15789$14726298@news.sunsite.dk> Message-ID: <1138573427.203689.273640@g43g2000cwa.googlegroups.com> Thanks again Peter. I found 2 potential solutions for obtaining the ip address of the incoming connection. The first was to subclass SimpleXMLRPCRequestHandler class and pass it to the SimpleXMLRPCServer constructor. In doing so, I could directly access the client_address via self.client_address. This worked just fine but was a bit overkill. The other solution I noticed was that SimpleXMLRPCServer's (which ultimately subclasses BaseServer) handle_request method invokes get_request (which merely calls self.socket.accept() -- which returns a tuple including the ip address). By re-implementing get_request() as such: def get_request(self): req = self.socket.accept() ip_address = req[1][0] return req I can grab the ip address for internal use and have the get_request method return the expected data for use by hande_request(). Now I just need to find a thread-safe way of passing this data back to the XMLRPC server's registered_instance. From onurb at xiludom.gro Tue Jan 24 08:50:10 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 24 Jan 2006 14:50:10 +0100 Subject: file_name_fixer.py In-Reply-To: <1138064443.217593.29640@g44g2000cwa.googlegroups.com> References: <1138064443.217593.29640@g44g2000cwa.googlegroups.com> Message-ID: <43d6309f$0$15778$636a15ce@news.free.fr> ewaguespack at gmail.com wrote: > i put this together to fix a bunch of files with wierd names, please > gimme feedback, i am a newbie Ok, so let's go... Hope you won't hate me too much !-) > > #!/usr/bin/env python > import os > import sys > import string > import platform > dir = sys.argv[1] This will shadow the builtin 'dir' function. > noworky = sys.argv[2] If the user fails to provide args, the program will crash with an IndexError - which may not be very helpful. Also, a better scheme would be myprog [-opt1 [-opt2=val [-optN]]] arg1 arg2 argN Hint: the optparse module is your friend http://www.python.org/doc/2.4.2/lib/module-optparse.html > if platform.system() == 'Linux': > uglychars = ''.join( set(string.punctuation+' ') - set('/_.') ) > else: > if platform.system() == 'Windows':#this is broken because windows > is gay with case > uglychars = ''.join( set(string.punctuation+' ') - > set(':\\/_.') ) > else: > print "wtf... what platform is this anyway?" May be MacOS Classic, MacOS X or any *n*x or *BSD variant, or any other platform supporting Python - are there are some... > underscore = '_' > underscore = underscore * len(uglychars) You don't need the intermediate value: underscores = '_' * len(uglychars) > chars = string.maketrans(uglychars, underscore) > print "# PHASE I, DIRECTORIES" Why not processing dirs and files in one pass ? > for path, subdirs, files in os.walk(dir, topdown=True): Err... is the 'dir' argument supposed to be an absolute path or a relative path ? And why using the topdown option ? > oldname = path woops ! this may be the absolute path. Are you sure you want to process an absolute path ? I think you'd better process files and dirs in one path, walking bottom up (so you don't process any file twice). > newname = oldname.translate(chars) > newname = string.lower(newname) Use the 'str' object methods instead of functions from the string module: newname = newname.lower() You can also chain method/function calls: newname = oldname.translate(chars).lower() > while string.count(newname, "__") > 0: in the context of a boolean expression, 0 evaluate to False, non-zero to True. So you don't have to be so explicit: while newname.count('__'): > newname = string.replace(newname,"__","_") You don't need to actually *count* the occurrences of '__' - if there's one, that's enough: while '__' in newname: # proceed Also, a regexp may be more effective here. > while string.count(newname, "..") > 0: > newname = string.replace(newname,"..",".") Don't forget the '..' and '.' special directories in unix filesystems... > if oldname != newname: > if os.path.isfile(newname) or os.path.isdir(newname): And if there's a special file (device etc) ? hint : os.path.exists() > print oldname, "-->\n", newname, "\t\t\tERROR: file/dir > exists\n" stdout is for 'normal' program outputs (ie: outputs that may be used as inputs to another program). This kind of output should go to stderr: print >> sys.stdout, "%s --> %s : \t\t\tERROR: " "file/dir exists" % (oldname, newname,) > else: > print oldname, "-->\n", newname, "\t\t\tYAY: file > renamed\n" > if noworky == "doit": > os.renames(oldname, newname) How is the user supposed to know that he has to pass the string "doit" as a second arg ? There are some (more or less agreed upon) conventions about cli options. Like '--dry-run' to express the fact that the program shouldn't actually do more than simulate it's execution. > print "# PHASE II, FILES" > for path, subdirs, files in os.walk(dir, topdown=True): > for oldname in files: > oldname = os.path.join(path, oldname) Are you *sure* you want to operate on the *whole* *absolute* path ? (cf my thoughts about the "first phase" and the whole algorithm) > newname = oldname.translate(chars) > newname = string.lower(newname) Aren't you repeating some code here ? hint : all duplicated code should be factored out into a function. > newname = string.replace(newname,".mpeg",".mpg") > newname = string.replace(newname,".ram",".rm") > newname = string.replace(newname,".jpeg",".jpg") > newname = string.replace(newname,".qt",".mov") # outside the loop, define a dict like: ext_map = {'mpeg': 'mpg', 'ram' : 'rm', 'jpeg' : 'jpg', # etc } # then in the loop: base, ext = os.path.split(newname) if ext in ext_map: newname = "%s.%s" % (base, ext_map[ext]) > while string.count(newname, "__") > 0: > newname = string.replace(newname,"__","_") duplicated code... > while string.count(newname, "..") > 0: > newname = string.replace(newname,"..",".") > newname = string.replace(newname,"._","_") > newname = string.replace(newname,"_.",".") all this is a perfect usecase for regexps... > if oldname != newname: > if os.path.isfile(newname) or os.path.isdir(newname): > print oldname, "-->\n", newname, "\t\t\tERROR: file/dir > exists\n" > else: > print oldname, "-->\n", newname, "\t\t\tYAY: file > renamed\n" > if noworky == "doit": > os.renames(oldname, newname) duplicated code. Still alive ?-) I thing the first step would be to correct your algorithm, then use some more efficient or idiomatic constructs where possible (like using dicts instead of repeated tests, sending messages to stderr etc). Then here are some more hints: - put the processing algorithm in a dedicated function, if possible one that doesn't rely on any global variable, - factor out any duplicated code into helper functions - then add a 'main' function that take cares of options and call the 'processing' function if everything's ok. The main function should return 0 if ok, non-zero if errors (usually 2 for invalid cli options or args, 1 for other errors) - and finally add this at the end of your module: if __name__ == '__main__': sys.exit(main(sys.argv)) This will allow your script to be used either as a program or as a module. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tim at pollenation.net Wed Jan 18 07:46:07 2006 From: tim at pollenation.net (Tim Parkin) Date: Wed, 18 Jan 2006 12:46:07 +0000 Subject: New Python.org website ? In-Reply-To: References: <43C4E198.2080107@holdenweb.com> <1137573186.943743.32150@g47g2000cwa.googlegroups.com> Message-ID: <43CE388F.6040104@pollenation.net> Roel Schroeven wrote: > Tim N. van der Leeuw schreef: > >>Shalabh, >> >>You've managed very well to express the same things I feel about the >>new Python website. > > > FWIW, I don't like the new site at all. It tries to look slick (but > fails to do so in my opinion), and buries the useful information in all > kinds of misplaced eye candy. > > In fact I like the old one better: short, clear and to the point. Can you make some specific comments about which 'eye candy' that you find objectionable and which parts of the navigation structure you find confusing? Tim From steve at REMOVEMEcyber.com.au Mon Jan 16 21:40:08 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 17 Jan 2006 13:40:08 +1100 Subject: On Numbers References: <86zmlyv1or.fsf@bhuda.mired.org> <7xacdx883s.fsf@ruckus.brouhaha.com> <1h981ac.xfh8rs19le55eN%aleax@mail.comcast.net> Message-ID: <43CC5908.2010906@REMOVEMEcyber.com.au> Tom Anderson wrote: > On Sun, 15 Jan 2006, Alex Martelli wrote: > >> Paul Rubin wrote: >> >>> Mike Meyer writes: >>> >>>> I'd like to work on that. The idea would be that all the numeric >>>> types are representations of reals with different properties that >>>> make them appropriate for different uses. >>> >>> >>> 2+3j? >> >> >> Good point, so s/reals/complex numbers/ -- except for this "detail", >> Mike's idea do seem well founded. > > > 1 ** 0.5 ? [scratches head] I'm not sure what point you are making here. The square root of 1 is +1 (the negative root being explicitly rejected). Pure mathematicians, who may be expected to care whether the root is the integer 1 or the real number 1, are unlikely to write 1**0.5, prefering the squareroot symbol. For the rest of us, including applied mathematicians, 1**0.5 implies floating point, which implies the correct answer is 1.0. So I don't really know what point you are making. What solution(s) for 1**0.5 were you expecting? -- Steven. From khaispidey at hotmail.com Sun Jan 15 06:01:45 2006 From: khaispidey at hotmail.com (Kr z) Date: Sun, 15 Jan 2006 11:01:45 +0000 Subject: About socket threading Message-ID: An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Mon Jan 2 20:39:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: 2 Jan 2006 17:39:16 -0800 Subject: multidimensional array of objects in scipy core References: <1136228656.525056.128940@g14g2000cwa.googlegroups.com> Message-ID: <1136252356.293001.64900@o13g2000cwo.googlegroups.com> Stormslayer wrote: > Folks: How do you create a multidimesional array of objects w/ the size > of the array entered at runtime? So basically, for an arbitrary class, > create an array and then *.resize it to be of size NXM, and then > populate the elements of the objects. First, asking on the scipy mailing list will get you a better response. Second, scipy_core does allow arrays of arbitrary Python objects, but it doesn't do any kind of type-checking for those arrays. It is up to you to populate the array with the kind of objects that you want. arr = empty((N, M), object) arr[i, j] = MyClass(i, j) should work (can't check at the moment, though). Please note that object arrays have always been tricky since Numeric, so if you encounter strange behaviour, we would appreciate a report on the scipy mailing list. From jdlists at gmail.com Tue Jan 31 07:52:17 2006 From: jdlists at gmail.com (jdlists at gmail.com) Date: 31 Jan 2006 04:52:17 -0800 Subject: File permissions script vs shell Message-ID: <1138711937.089444.209050@g44g2000cwa.googlegroups.com> I'm running python on windows and have a program that watches a directory and acts on files as they come into the directory. After processing is complete, i delete the file, or in this case attempt to.... In the script version I repeatedly get OSError exceptions stating permission denied when trying to delete or rename My exception print out... Files system said no: [Errno 13] Permission denied: u'D:\\Data\\00-0C-41-DD-87-E5.xml' But i can go into the python shell and execute... fileString = 'D:\\Data\\00-0C-41-DD-87-E5.xml' import os os.unlink(fileString) and the file deletes fine Any ideas? This is on my development windows xp box and i'm the only user. Thanks Jeff From aahz at pythoncraft.com Sun Jan 1 23:29:59 2006 From: aahz at pythoncraft.com (Aahz) Date: 1 Jan 2006 20:29:59 -0800 Subject: New Python.org website ? References: Message-ID: In article , Bugs wrote: > >I thought I read here that a new website design was in the works for >python.org in time for the new year? Is that still true and of so, >anyone know what is it's status? Dunno about "in time for the new year", but there is a new design that is supposedly in final stages of getting implemented. What's your hurry? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From peter at engcorp.com Tue Jan 31 12:55:25 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 31 Jan 2006 12:55:25 -0500 Subject: Python vs C for a mail server In-Reply-To: <1138728303.669646.36940@g49g2000cwa.googlegroups.com> References: <1138728303.669646.36940@g49g2000cwa.googlegroups.com> Message-ID: Randall Parker wrote: > The point of doing compile time and test time checking is the same > reason militaries use layered defenses: More problems get caught. I've > written tons of software tests and architected a testing system for an > entire aircraft. I've also watched lots of errors get by tests. Hmm... with that analogy, I would have to say that most people who strongly advocate static typing and compiler tests are really relying solely on their perimeter guards. They seem to think that provides sufficient defense, and forget to finish the fortress walls. That is, they often don't do adequate tests. Those of us who have really strong fortress walls might sometimes be willing to forego the perimeter guard, perhaps unwisely, but at least we know immediately when we're under attack. > Plus, tests become just another layer that needs testing. They also > become another layer that can get out of synch with the rest of the > software. Not if you are doing test-driven development, at least. In that case by definition if you're out of sync, it's the code which is failing the test because the test defines what the code should be doing. -Peter From noemailspam at comcast.net Sun Jan 8 21:50:11 2006 From: noemailspam at comcast.net (scott_gui) Date: 8 Jan 2006 18:50:11 -0800 Subject: Double Click mouse event problems References: <1136590719.289497.158040@g43g2000cwa.googlegroups.com> <43bff1b6$1@nntp0.pdx.net> Message-ID: <1136664669.110603.76250@f14g2000cwb.googlegroups.com> Thank you very much. Adding in a timer delay is a good fake out. I guess I always considered a double-click to be one distinct behavior aside from the single click. I have rarely seen where a double-click action engaged an object without single clicks to select the object. For example, the Window's file manager allows you to Ctrl-click select two files and double click to launch both files. So I don't expect distinct behaviors from Button-1-Down and Button-1-Up, but I guess I do expect them from a double and single click. No matter, I'll try the delay. This should work reasonably well. From cdc at maxnet.co.nz Tue Jan 24 18:33:17 2006 From: cdc at maxnet.co.nz (Carl Cerecke) Date: Wed, 25 Jan 2006 12:33:17 +1300 Subject: Weird generator id() behaviour (was Re: Python code written in1998, howto improve/change it?) In-Reply-To: <43d6b7ca$1@usenet01.boi.hp.com> References: <1137697284.101739.30690@z14g2000cwz.googlegroups.com><43d00460@usenet01.boi.hp.com> <1137714834.195896.180550@g47g2000cwa.googlegroups.com><43d0596e@usenet01.boi.hp.com> <43d05ac2@usenet01.boi.hp.com><0001HW.BFFC3AEE0008B851F04B8550@news.individual.de> <43d68bd0@usenet01.boi.hp.com> <43d6b290$1@usenet01.boi.hp.com> <43d6b7ca$1@usenet01.boi.hp.com> Message-ID: <43d6b93e$1@usenet01.boi.hp.com> Adding a continue statemtent after the yield statements yields :-) a speed increase. Still not as good as functions though. (about 30% slower) Cheers, Carl Carl Cerecke wrote: > Carl Cerecke wrote: > Generator FSM done properly (well, better anyway). They are still almost > twice as slow as plain function calls, though. > > def g_on(): > > while 1: > action = next_action() > if action == 'lift': > yield s_g_on > elif action == 'push': > yield s_g_off > else: > break > yield None > > def g_off(): > > while 1: > action = next_action() > if action == 'lift': > yield s_g_on > elif action == 'push': > yield s_g_off > else: > break > yield None > > def actions(n): > import random > for i in range(n-1): > yield random.choice(['lift','push']) > yield None > > r = 1000000 > #r = 10 > next_action = actions(r).next > s_g_on = g_on() > s_g_off = g_off() > state = s_g_on > > while state: > state = state.next() > z = time.clock() From martin at v.loewis.de Mon Jan 23 16:31:17 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 23 Jan 2006 22:31:17 +0100 Subject: Some thoughts on garbage collection In-Reply-To: <1138002325.266706.213280@f14g2000cwb.googlegroups.com> References: <1138000638.020856.49450@g47g2000cwa.googlegroups.com> <7xhd7vtni3.fsf@ruckus.brouhaha.com> <1138002325.266706.213280@f14g2000cwb.googlegroups.com> Message-ID: <43d54b26$0$12383$9b622d9e@news.freenet.de> Frank Millman wrote: > In principle I agree. My concern was that I might have inadvertently > done something wrong (e.g. left a reference dangling) which would > prevent gc from removing all objects which I wanted to be removed. Depends on what it really is that you want to know. If you want to know whether gc can release all garbage objects, you should look at gc.garbage, after a gc.collect call immediately before the end of the program. The issue here is that objects implementing __del__ in a cycle will never get collected (but added to gc.garbage); this is something you need to be aware of. If you want to find out if there are objects which you hold onto too long, you can look at len(gc.get_objects()) from time to time. This won't be all objects, but just the container objects. If you see the number growing over time, you have a leak. You could then also categorize this by type, e.g. frequency = {} for o in gc.get_objects(): o = o.__class__.__name__ frequency[o] = frequency.get(o, 0) + 1 print sorted(frequency.iteritems(), key=operator.itemgetter(1), reverse=1) If you are interested in total object counts, you need to run the debug version of Python. HTH, Martin From steve at holdenweb.com Fri Jan 27 08:17:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Jan 2006 13:17:59 +0000 Subject: generating method names 'dynamically' In-Reply-To: <5f56302b0601261732l591a0883lbba0568f71a6e940@mail.gmail.com> References: <5f56302b0601261732l591a0883lbba0568f71a6e940@mail.gmail.com> Message-ID: Daniel Nogradi wrote: >>Here you go: >> >> >>> database = { >> ... "Alice": 24, >> ... "Bob":25} >> ... >> >>> class Lookup(object): >> ... def __catcher(self, name): >> ... try: >> ... print "Hello my name is %s and I'm %s" % (name, >>database[name]) >> ... except KeyError: >> ... print "There was an error" >> ... def __getattr__(self, attr): >> ... return lambda:self.__catcher(attr) >> ... >> >>> inst = Lookup() >> >>> inst.Alice() >> Hello my name is Alice and I'm 24 >> >>> inst.Bob() >> Hello my name is Bob and I'm 25 >> >>> inst.John() >> There was an error >> >>> >> > > > Great, that was exactly what I was asking, thank you very much. While I hesitate to rain on this little parade, I would caution you against adopting this solution as a generic programming tool. If people just need to interact with the database in an ad hoc way then this will let them do it, but it's a very poor recipe for general database search, since the content of your database determines the text of your program. You might well find, on thinking about it a little more, that it mught be more straightforward to adopt a system more like this: name = raw_input("Who do you want to know today: ") inst = Lookup(name) inst.show() regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From __peter__ at web.de Tue Jan 10 04:16:04 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Jan 2006 10:16:04 +0100 Subject: Real-world use cases for map's None fill-in feature? References: <1136803053.214083.26050@z14g2000cwz.googlegroups.com> Message-ID: Raymond Hettinger wrote: > Alternately, the need can be met with existing tools by pre-padding the > iterator with enough extra values to fill any holes: > > it = chain(iterable, repeat('', group_size-1)) > result = izip_longest(*[it]*group_size) > > Both approaches require a certain meaure of inventiveness, rely on > advacned tricks, and forgo readability to gain the raw speed and > conciseness afforded by a clever use of itertools. They are also a > challenge to review, test, modify, read, or explain to others. Is this the author of itertools becoming its most articulate opponent? What use is this collection of small functions sharing an underlying concept if you are not supposed to combine them to your heart's content? You probably cannot pull off some of those tricks until you have good working knowledge of the iterator protocol, but that is becoming increasingly important to understand all Python code. > In contrast, a simple generator is trivially easy to create and read, > albiet less concise and not as speedy: > > it = iter(iterable) > while 1: > row = tuple(islice(it, group_size)) > if len(row) == group_size: > yield row > else: if row: yield row + ('',) * (group_size - len(row)) > break > > The generator version is plain, simple, boring, and uninspirational. I Can't argue with that :-) But nobody spotted the bug within a day; so dumbing down the code didn't pay off. Furthermore, simple code like above is often inlined and therefore harder to test and an impediment to modification. Once you put the logic into a separate function/generator it doesn't really matter which version you use. You can't get the chain/repeat/izip variant to meet your (changing) requirements? Throw it away and just keep the (modified) test suite. A newbie, by the way, would have /written/ neither. The it = iter(iterable) voodoo isn't obvious and the barrier to switch from lst[:group_size] to islice(it, group_size) to /improve/ one's is code high. I expect to see an inlined list-based solution. The two versions are both part of a learning experience and both worth the effort. Regarding the thread's topic, I have no use cases for a map(None, ...)-like izip_longest(), but occasionally I would prefer izip() to throw a ValueError if its iterable arguments do not have the same "length". Peter From josh-post at istedconsulting.com Fri Jan 27 18:48:51 2006 From: josh-post at istedconsulting.com (Josh) Date: Fri, 27 Jan 2006 23:48:51 GMT Subject: VB to Python migration Message-ID: We have a program written in VB6 (over 100,000 lines of code and 230 UI screens) that we want to get out of VB and into a better language. The program is over 10 years old and has already been ported from VB3 to VB6, a job which took over two years. We would like to port it to Python, but we need to continue to offer upgrades and fixes to the current VB6 version. Does anybody know of ways we could go about rewriting this, one screen at a time, in Python, and calling the screens from the existing program? We are also looking for a graphics toolkit to use. IronPython with it's .NET bindings and ability to integrate with Visual Studio looks good, but leaves that bad MS taste in the mouth. We currently use a MS Access back end and need to migrate to a proper SQL server. We need to leave options open for SQL Server (for customers who want to use existing infrastructure) and something like MySQL or PostgreSQL. But in the mean time, we need to be able to access an MSAccess (Jet) database from Python. Any answers/suggestions/pointers are greatly appreciated. Thanks, Josh Isted From fredg at fastmail.fm Thu Jan 26 10:07:25 2006 From: fredg at fastmail.fm (Fred) Date: 26 Jan 2006 07:07:25 -0800 Subject: ImportError: No module name MySQLdb In-Reply-To: References: <1138239687.583593.285680@z14g2000cwz.googlegroups.com> Message-ID: <1138288045.241543.299070@f14g2000cwb.googlegroups.com> Magnus Lycka wrote: > Fred wrote: > > Slackware Linux 10.2 > > Heh, Slackware was my first Linux distro. Version > 2.2 I think. 1993 maybe? I have been using Slackware since 1995, version 3.0 kernel 1.2.13 > Some suggestions: > Finally, the cgitb module is pretty useful. I > suggest that you look it up: > http://docs.python.org/lib/module-cgitb.html Will check it out... I bet this is something really simple and possibly related to my use of Slackware, although hours of searching has not produced an answer.. Fred From fredrik at pythonware.com Sun Jan 29 18:08:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Jan 2006 00:08:06 +0100 Subject: Storing lines from a text file References: <1138575627.078312.276040@z14g2000cwz.googlegroups.com> Message-ID: bradfordh at gmail.com wrote: > I am not sure how hard of a question is, but I do know that I need some > help if you can give it. What I want to do is read the lines in a text > file and store each line into a variable. I believe that I can use > readlines() to read the individual lines, but how would I store each > line into a variable for further analysis? Thanks for any and all > suggestions. any reason you cannot do the analysis on the list you get from readlines ? if you insist on having the lines in individual variables, you can use straight- forward sequence unpacking: a, b, c, d, e = f.readlines() From apardon at forel.vub.ac.be Mon Jan 16 04:21:47 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Jan 2006 09:21:47 GMT Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1137111113.310683.178770@o13g2000cwo.googlegroups.com> <1137212572.427212@jetspin.drizzle.com> <86d5iuwixa.fsf@bhuda.mired.org> Message-ID: Op 2006-01-14, Mike Meyer schreef : > "Donn Cave" writes: >> |> 3. If two objects are equal with "==", does that >> |> mean their values are the same? >> Yes. >> | >>> 3.0 == 3 >> | True >> Evidently the value of 3.0 is the same as the value of 3. > > And they do. They are two different representations of the same > value. More in another thread. I would say they are two different values that are equivallent in a lot of ways. -- Antoon Pardon From zizi2002198 at gmail.com Wed Jan 18 01:36:46 2006 From: zizi2002198 at gmail.com (zizi2002198 at gmail.com) Date: 17 Jan 2006 22:36:46 -0800 Subject: Funny! More offers to select a search engine! Message-ID: <1137566206.415499.187340@g49g2000cwa.googlegroups.com> www.goodugle.com From fuzzyman at gmail.com Mon Jan 23 06:54:30 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Jan 2006 03:54:30 -0800 Subject: Redirecting standard out in a single namespace In-Reply-To: <43d49ea3.15617196@news.oz.net> References: <1137771435.682063.178150@g14g2000cwa.googlegroups.com> <43d49ea3.15617196@news.oz.net> Message-ID: <1138017270.654626.222100@g49g2000cwa.googlegroups.com> Bengt Richter wrote: > On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" wrote: > > >Hello, > > > >I'm trying to redirect standard out in a single namespace. > > > >I can replace sys.stdout with a custom object - but that affects all > >namespaces. > > > >There will be code running simultaneously that could import sys > >afterwards - so I don't want to make the change in the sys module. > > > >I have an idea to redefine __import__ for the relevant namespace - so > >that an attempt to import sys will return a different module with a > >custom object for stdout. As sys is a builtin module this might not > >work for the print statement, which is what I want to redirect. [snip..] > >Is there another way to shadow the sys module from a single namespace ? > > > It wouldn't be shadowing, but I suppose you could replace sys.stdout with > a custom object whose methods check where they were called from. > Then you could give the object initialization parameters as to which namespace > you want to have the effect in, and/or methods to control the action or turn > it on or off etc. BTW, how about stderr? > I've just tried checking __name__ in my custom stdout object. Unfortunately __name__ is always the module in which the new stdout object lives. In theory I could go up (down?) the stack to the previous frame and check __name__ there - but it sounds like a hack. Any other ways of checking where sys.stdout is called from ? All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Regards, > Bengt Richter From volker_grabsch at v.notjusthosting.com Sun Jan 8 20:12:15 2006 From: volker_grabsch at v.notjusthosting.com (Volker Grabsch) Date: Mon, 9 Jan 2006 02:12:15 +0100 Subject: psexec and os.popen help References: <1136578889.612591.73000@g49g2000cwa.googlegroups.com> <1136602435.784894.266680@g47g2000cwa.googlegroups.com> Message-ID: dennis.scales at gmail.com wrote: > popen3 did the trick. Use the modules "subprocess" ... it solves many problems, including the problem of too many similar functions. :-) These functions (execl, execv, popen, popen2, popen3, ...) are relicts from C and very unpythonic. It's IMHO always a better programming style to use "subprocess". Greets, Volker -- Volker Grabsch ---<<(())>>--- \frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt [G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}} From somebody at nowhere.com Sun Jan 1 19:36:20 2006 From: somebody at nowhere.com (Sean Richards) Date: Mon, 02 Jan 2006 13:36:20 +1300 Subject: Numeric RandomArray seed problem References: <1136114337.222486.194030@z14g2000cwz.googlegroups.com> Message-ID: <87ek3rxy7v.fsf@munin.valhalla.net> "ajikoe at gmail.com" writes: > Hello, > > I tried calling RandomArray.seed() > by calling RandomArray.get_seed() I get the seed number (x,y). > My problem is that x is always 113611 any advice? In [1]: from RandomArray import * In [2]: seed? Type: function Base Class: String Form: Namespace: Interactive File: /usr/lib/python2.3/site-packages/Numeric/RandomArray.py Definition: seed(x=0, y=0) Docstring: seed(x, y), set the seed using the integers x, y; Set a random one from clock if y == 0 In [3]: seed(123,456) In [4]: get_seed() Out[4]: (123, 456) Cheers, Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss." From gregpinero at gmail.com Mon Jan 30 23:10:13 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Mon, 30 Jan 2006 23:10:13 -0500 Subject: Fuzzy Lookups In-Reply-To: <1138670927.377396.78090@g44g2000cwa.googlegroups.com> References: <1138635665.956131.130630@f14g2000cwb.googlegroups.com> <1138670927.377396.78090@g44g2000cwa.googlegroups.com> Message-ID: <312cfe2b0601302010j5313ac2ew2f4d82e90aed93d@mail.gmail.com> Ok, ok, I got it! The Pythonic way is to use an existing library ;-) import difflib CloseMatches=difflib.get_close_matches(AFileName,AllFiles,20,.7) I wrote a script to delete duplicate mp3's by filename a few years back with this. If anyone's interested in seeing it, I'll post a blog entry on it. I'm betting it uses a similiar algorithm your functions. -Greg On 30 Jan 2006 17:28:47 -0800, ajones wrote: > > BBands wrote: > > I have some CDs and have been archiving them on a PC. I wrote a Python > > script that spans the archive and returns a list of its contents: > > [[genre, artist, album, song]...]. I wanted to add a search function to > > locate all the versions of a particular song. This is harder than you > > might think. For example the Cajun "national anthem" is Jolie Blond, > > but it can be spelled several different ways jolie, joli, blon, blond, > > etc... In addition the various online services that provide song info > > are riddled with typos, so an ordinary string match just doesn't get > > you there. What is needed is a fuzzy string match and it turns out that > > there is a very good one, the Levenshtein distance, which is the number > > of inserts, deletions and substitutions needed to morph one string into > > another. In my application I match the desired song title against all > > song titles in my list and return the ones with the lowest Levenshtein > > distances. This is remarkably, one might even say stunningly, > > effective, easily finding all the version of Jolie Blon in the list. > > > > I am using the following snippet (found on the web, proper attribution > > unsure), which calculates the Levenshtein distance. > > > > def distance(a,b): > > c = {} > > n = len(a); m = len(b) > > > > for i in range(0,n+1): > > c[i,0] = i > > for j in range(0,m+1): > > c[0,j] = j > > > > for i in range(1,n+1): > > for j in range(1,m+1): > > x = c[i-1,j]+1 > > y = c[i,j-1]+1 > > if a[i-1] == b[j-1]: > > z = c[i-1,j-1] > > else: > > z = c[i-1,j-1]+1 > > c[i,j] = min(x,y,z) > > return c[n,m] > > > > As mentioned above this works quite well and I am happy with it, but I > > wonder if there is a more Pythonic way of doing this type of lookup? > > > > jab > > Here is my stab at it, didn't fully test it so it may not work > correctly. The tuples could be avoided by using len(x), but the extra > lookups may cost in execution speed[1]. > > def distance(a, b): > """ > Computes the levenshtein distance between two strings > """ > m, n = (len(a),a), (len(b),b) > if(m[0] < n[0]): #ensure that the 'm' tuple holds > the longest string > m, n = n, m > dist = m[0] #assume distance = length of > longest string (worst case) > for i in range(0, n[0]): # reduce the distance for each char > match in shorter string > if m[1][i] == n[1][i]: > dist = dist - 1 > return dist > > [1] I have no if this is true or not. I can see arguments for both. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From anton.vredegoor at gmail.com Sun Jan 29 09:48:12 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 29 Jan 2006 06:48:12 -0800 Subject: Fast generation of permutations References: <11tf35qjfeluka1@corp.supernews.com> <43D7B2FB.4040603@sim.no> <7x64o818yq.fsf@ruckus.brouhaha.com> <7x1wyw18s4.fsf@ruckus.brouhaha.com> <7xacdkq96b.fsf@ruckus.brouhaha.com> <1138442593.625059.172790@g44g2000cwa.googlegroups.com> <7xmzhgs5dl.fsf@ruckus.brouhaha.com> <1138545447.573068.111450@g49g2000cwa.googlegroups.com> Message-ID: <1138546092.441873.8010@f14g2000cwb.googlegroups.com> Anton Vredegoor wrote: > Paul Rubin wrote: > > > Cool, I'd still like to know why (13**5)-13 = C(52,5) other than > > by just doing the arithmetic and comparing the results. Maybe your > > tkinter script can show that. > > That seems to be very hard :-) Unless I'm missing something. Like a factor seven, you mentioned that a few posts back. Sorry about that. Anton From shahbazc at gmail.com Sun Jan 29 01:35:22 2006 From: shahbazc at gmail.com (falcon) Date: 28 Jan 2006 22:35:22 -0800 Subject: newbie: working iwth list of tuples References: <1138516270.421626.34530@z14g2000cwz.googlegroups.com> Message-ID: <1138516522.382884.3830@o13g2000cwo.googlegroups.com> I forgot to add that I passing a tuple of functions to the reduce function but apparently that is not allowed. My guess was that a tuple made up of individual (simple) functions might be easier to manipulate programatically than a function which has to know the structure of a list. (My test code) x=[('a',1),('a',1),('a',3),('b',1),('b',2),('c',2),('c',3),('c',4)] reduce((lambda x,y: x+y,lambda x,y: x+y),x) From will.ware at gmail.com Sun Jan 1 21:47:15 2006 From: will.ware at gmail.com (Will Ware) Date: 1 Jan 2006 18:47:15 -0800 Subject: Pyrex on Darwin, gcc 3.3 optimization trouble In-Reply-To: <1135962568.048531.257460@g47g2000cwa.googlegroups.com> References: <1135962568.048531.257460@g47g2000cwa.googlegroups.com> Message-ID: <1136170035.072371.241610@f14g2000cwb.googlegroups.com> In case anybody else has this problem, the solution is to add "-O" in extra_compile_args, which will override the "-O3" normally used. This is done in the setup.py file. From blazebresko at yahoo.com Sun Jan 8 17:35:38 2006 From: blazebresko at yahoo.com (Blaze Bresko) Date: 8 Jan 2006 14:35:38 -0800 Subject: cant get py2exe exe file to work Message-ID: <1136759737.970632.43770@g44g2000cwa.googlegroups.com> heres my log file: Traceback (most recent call last): File "Pong.pyw", line 264, in ? File "Pong.pyw", line 258, in main File "Pong.pyw", line 166, in __init__ File "livewires\games.pyc", line 575, in __init__ File "livewires\games.pyc", line 581, in init_text RuntimeError: default font not found Exception exceptions.AttributeError: "Text instance has no attribute '_gone'" in > ignored im using py2exe V 0.6, python V 2.4, and the newest pygame and livewires and distutils...ill put my setup.py file up if needed. What on earth is wrong? Blaze From jstroud at ucla.edu Sun Jan 22 18:28:56 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 22 Jan 2006 15:28:56 -0800 Subject: Making dir's In-Reply-To: References: Message-ID: yawgmoth7 wrote: > Hello, I am writing a script that will organize all the code in the > given directory. Well, currently I have it make dir's with something > like: > > os.mkdir("C") > os.mkdir("Python") > os.mkdir("ASM") > > And so on. That is not very practical, and I wish to change it. I was > wondering if there were any other methods to which I could do this, I > was thinking maybe I could put the dir names in a dictionary then have > something like: > os.mkdir(thedictname) > > This doesn't sound like it would work, maybe with a bit of tweaking to > my idea. So, anyone that has any idea's on how I could do this...that > would be great... > > Thanks for your help. > -- > gurusnetwork.org > Gurus'Network - Are you a guru? Assuming something in the standard library doesn't do this already (shutils, os, os.path) import os def mkdirs(pths): for pth in pths: os.mkdir(pth) mkdirs(["C","Python, "ASM"]) Is that what you mean? From sybrenUSE at YOURthirdtower.com.imagination Fri Jan 13 11:31:37 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 13 Jan 2006 17:31:37 +0100 Subject: New Python.org website ? References: <1137165407.149259.306470@o13g2000cwo.googlegroups.com> Message-ID: Tim Chase enlightened us with: > In both Mozilla-suite (1.7) and FireFox (1.5), the links on the left > (the grey-backgrounded all-caps with the ">>" at the right) all > intrude into the body text. Looks fine here on Firefox 1.5 and Konqueror 3.4.3. The site looks really nice! I think this is going to make a difference in the amount of people taking Python seriously. Does anybody know what kind of license covers the website? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From lycka at carmen.se Sun Jan 29 11:48:57 2006 From: lycka at carmen.se (Magnus Lycka) Date: Sun, 29 Jan 2006 17:48:57 +0100 Subject: OT: Re: Using non-ascii symbols In-Reply-To: References: <5af1b8bc0601252312r3a71348fu23b6cfd2f61937ae@mail.gmail.com> Message-ID: Runsun Pan wrote: > The simplified chinese exists due to the call for modernization of > language decades ago. That involved the 'upside-down' of almost > entire culture This is in some ways quite the opposite compared to Nynorsk in Norway, which was an attempt to revive the old and pure Norwegian, after being dominated (in politics as well as in grammar) by Denmark from 1387-1814. (I guess it was a complicating factor that the end of the union with Denmark led to a union with Sweden. The Norwegians probably had some difficulties deciding what neighbour they disliked most. When they broke out of the union with Sweden in 1905, they actually elected a Danish prince to be their king.) Anyway, only a fraction of the Norwegians use Nynorsk today, and the majority still speak the Danish-based bokm?l. On the other hand, the spelling of bokm?l has also been modernized a lot, with a series of spelling reforms of both languages. From ivan at ivan-herman.net Sat Jan 21 07:48:14 2006 From: ivan at ivan-herman.net (Ivan Herman) Date: Sat, 21 Jan 2006 13:48:14 +0100 Subject: PyXML: SAX vs. DOM In-Reply-To: References: Message-ID: <43D22D8E.1010805@ivan-herman.net> -------- Original Message -------- From: Matthias Kaeppler To: Subject: Re:PyXML: SAX vs. DOM Date: 20/1/2006 21:26 > Oh and: > Where can I find an API reference for PyXML? Am I supposed to /guess/ > which methods and attributes e.g. Sax2 supplies? :D > > Thanks again, > Matthias Matthias, your question is valid, and I just tell you how *I* do it... - the core of the methods in DOM are described by the W3C recommendations. I think the most relevant ones are: http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html where you can find all objects and methods that are defined by DOM Level 2 and, as far as I could see, all properly implemented by PyXML. The only caveat is that DOM2 defines the interface in abstract (more exactly, in IDL), and one has to know (or guess) how those are mapped onto Python. Having said that, by looking at the PyXML documentation: http://pyxml.sourceforge.net/topics/howto/ mainly http://pyxml.sourceforge.net/topics/howto/section-DOM.html one can do a very good educated guess so it is not sooo bad as it sounds. I know this is not the ideal answer, but maybe it helps... Ivan From nephish at xit.net Tue Jan 17 21:02:52 2006 From: nephish at xit.net (nephish at xit.net) Date: 17 Jan 2006 18:02:52 -0800 Subject: check to see if value can be an integer instead of string Message-ID: <1137549772.543188.69240@g44g2000cwa.googlegroups.com> Hello there, i need a way to check to see if a certain value can be an integer. I have looked at is int(), but what is comming out is a string that may be an integer. i mean, it will be formatted as a string, but i need to know if it is possible to be expressed as an integer. like this var = some var passed to my script if var can be an integer : do this else: change it to an integer and do something else with it. whats the best way to do this ? thanks, shawn From sylvain.thenault at logilab.fr Tue Jan 10 09:41:37 2006 From: sylvain.thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Tue, 10 Jan 2006 15:41:37 +0100 Subject: [ANN] devtools 0.8 Message-ID: <20060110144137.GG5228@logilab.fr> Hi ! I'm pleased to announce the new 0.8 release of the devtools package. This release provides some bug fixes and major changes into the debian package generation. What's new ? ------------ * debianize: * updated to handle site-python installation with architecture independant package (implements #10119) * consider the optional debian_uploader variable in package information * fix .examples files generation with debianize * fix templates: control.standard-version is now 3.6.2, updated FSF address in debian licenses files * fix package type detection in preparedistrib (fix #9917) What is devtools ? ------------------ Set of tools which aims to help the developpement process, including : * standard for zope and python packages * tools to check and build source and/or debian packages * python coverage tool * cvs utilities Home page --------- http://www.logilab.org/projects/devtools Download -------- ftp://ftp.logilab.org/pub/devtools Mailing list ------------ mailto://python-projects at lists.logilab.org LOGILAB provides services in the fields of XML techniques and advanced computing (implementation of intelligent agents, knowledge management, natural language processing, statistical analysis, data mining, etc.), and also trainings on Python, XML, UML, Object Oriented design, design patterns use and other cutting edge topics. To know more about Logilab, visit http://www.logilab.com/. Logilab is also a strong supporter of the Free Software movement, and an active member of the Python and Debian communities. Logilab's open source projects can be found on http://www.logilab.org/. Enjoy and happy new year ! -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From steve at holdenweb.com Fri Jan 20 21:06:40 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Jan 2006 02:06:40 +0000 Subject: Is there a maximum length of a regular expression in python? In-Reply-To: References: <1137591911.333364.221990@z14g2000cwz.googlegroups.com> Message-ID: Bryan Olson wrote: > Roy Smith wrote: > >> olekristianvillabo at gmail.com wrote: >> >> >> >>>I have a regular expression that is approximately 100k bytes. (It is >>>basically a list of all known norwegian postal numbers and the >>>corresponding place with | in between. I know this is not the intended >>>use for regular expressions, but it should nonetheless work. >>> >>>the pattern is >>>ur'(N-|NO-)?(5259 HJELLESTAD|4026 STAVANGER|4027 STAVANGER........|8305 >>>SVOLV?R)' >>> >>>The error message I get is: >>>RuntimeError: internal error in regular expression engine >> >> >>I don't know of any stated maximum length, but I'm not at all surprised >>this causes the regex compiler to blow up. This is clearly a case of regex >>being the wrong tool for the job. > > > Does no one care about an internal error in the regular expression > engine? > > Not one that requires parsing a 100 kilobyte re that should be replaced by something more sensible, no. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From scott.daniels at acm.org Sun Jan 1 22:48:53 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 01 Jan 2006 19:48:53 -0800 Subject: Hypergeometric distribution In-Reply-To: References: <1135628335.580063.179200@z14g2000cwz.googlegroups.com> <1h871o5.4kfq9m1ueam9zN%aleax@mail.comcast.net> <1136075042.504604.122680@g14g2000cwa.googlegroups.com> <1136154279.355940.182310@g49g2000cwa.googlegroups.com> Message-ID: <43b8a280$1@nntp0.pdx.net> Steven D'Aprano wrote: > On Sun, 01 Jan 2006 14:24:39 -0800, Raven wrote: > >> Thanks Steven for your very interesting post. >> >> This was a critical instance from my problem: >> >>>> >from scipy import comb >>>>> comb(14354,174) >> inf > > Curious. It wouldn't surprise me if scipy was using floats, because 'inf' > is usually a floating point value, not an integer. > > Using my test code from yesterday, I got: > >>>> bincoeff(14354,174) > ... >> Yes I am calculating hundreds of hypergeometric probabilities so I >> need fast calculations > > Another possibility, if you want exact integer maths rather than floating > point with logarithms, is to memoise the binomial coefficients. Something > like this: > > # untested > def bincoeff(n,r, \ > cache={}): > try: > return cache((n,r)) > except KeyError: > x = 1 > for i in range(r+1, n+1): > x *= i > for i in range(1, n-r+1): > x /= i > cache((n,r)) = x > return x Well, there is a much better optimization to use first: def bincoeff1(n, r): if r < n - r: r = n - r x = 1 for i in range(n, r, -1): x *= i for i in range(n - r, 1, -1): x /= i return x Then, if you still need to speed it up: def bincoeff2(n, r, cache={}): if r < n - r: r = n - r try: return cache[n, r] except KeyError: pass x = 1 for i in range(n, r, -1): x *= i for i in range(n - r, 1, -1): x /= i cache[n, r] = x return x --Scott David Daniels scott.daniels at acm.org From adelagon at gmail.com Mon Jan 2 04:07:07 2006 From: adelagon at gmail.com (Alvin A. Delagon) Date: Mon, 02 Jan 2006 17:07:07 +0800 Subject: Any wing2.0 users here? Message-ID: <43B8ED3B.1030509@gmail.com> emacs has been my long time companion for php, perl, and python. My boss recommended to me Wing2.0, I find it hard to adjust though. What can you say about this IDE? He say's if I think it could improve my productivity he's willing to buy it for me. Suggestions for better python IDE's are welcome! Thanks in advance! ^_^ From asmirnov1234567890 at yahoo.com Fri Jan 6 14:17:58 2006 From: asmirnov1234567890 at yahoo.com (asmirnov1234567890 at yahoo.com) Date: 6 Jan 2006 11:17:58 -0800 Subject: JINI service -- Python client Message-ID: <1136575078.700006.125870@g14g2000cwa.googlegroups.com> Hi does anybody knows how to use JINI service from Python? Regards, Andrei From grahamd at dscpl.com.au Wed Jan 4 20:55:07 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 4 Jan 2006 17:55:07 -0800 Subject: Python as a Server vs Running Under Apache References: <1135978683.855654.120600@f14g2000cwb.googlegroups.com> <1136002758.289235.167000@g49g2000cwa.googlegroups.com> <1136397772.599597.24350@g47g2000cwa.googlegroups.com> Message-ID: <1136426107.471434.132050@g14g2000cwa.googlegroups.com> fuzzylollipop wrote: > there are lots of things you can't do or can't do easily or can't do at > efficiently in Apache using python as cgi or as anyone would more > likely assume mod_python. anything that requires any shared state or > shared resources in Apache is next to impossible. Doing similar things > in an app server or network application framework like twisted is > trivial. What one really should be identifying here is that different tools are better for different jobs. Apache is a web server, and it isn't necessarily practical or sensible to try and shoe horn it into service as a full blown application server by and in itself. At the same time though, I would suggest that something like Twisted is in itself not always the best solution either, ie., to take an application server, and try and bolt on to it a web server. Yes Twisted can perform as a web server, but when compared to the functionality and configurability that Apache provides as a web server, it is always going to be a lessor cousin in that role. If you do not need the full power that Apache can provide and can live with the lessor abilities inherent from running the web server as a component within the application server, then great, but this isn't necessarily going to suit everyone either. Thus one is still faced with the question of whether you should embed the application in the web server, or wrap a web server around the application. Unfortunately from what I have seen, often the decision is made based on the narrow focus of expertise of the developers involved. A web developer will be dismissive of the application developer and vice versus. Each will say that it is trivial if done in the system which embodies their area of expertise, although usually that is said without them really knowing how they will achieve the part they don't know too much about. The strongest personalities thus will win as to how the system is built. The alternative is to accept that both Apache and application frameworks such as Twisted are each good in their own space and use both, bridging between the two as necessary. This could be done using simple protocols like XML-RPC or more sophisticated messaging system protocols where persistent connections can exist between the Apache child processes and the backend application server thus avoiding the creation of socket connections on every request. The use of messaging systems also means that presence information can extend into the realm of the web server and it can be easier to deal with failure or unavailability of components of the backed system. Keeping a split like this means you also have the added benefit that you don't end up with application server code which is somehow inherently dependent on or knowing that it is being used purely within the context of a particular web server. You don't end up with application server code being tied to the use of a specific means of rendering web pages. With this sort of split it doesn't matter whether you use CGI, mod_python, mod_perl or PHP for web page generation. Provided that the interfaces between the two are well defined, you can change the application server code structure as much as you like and the web page generation code doesn't need to change. The opposite also applies in as much as changes to the web page generation code shouldn't affect the application server code. Overall I would have to say that you are both right and wrong. Where the state is served purely by the use of the database, there is nothing wrong with Apache/mod_python in itself being used. Where the state also embodies the need to have active agents which operate on that data, possibly independent of web requests, then a back end application server which embeds the core functionality of the application would be better. In doing that though, it doesn't mean that Apache has to be discarded as the web server, and a web server embeded in the application server be adopted. Depending on the requirements, you will get a more flexible, more easily maintained system if a combination of the two technologies is used. Anyway, that statisifies my daily need for a good rant. ;-) Graham From modelnine at bit-bukket.org Wed Jan 4 04:26:41 2006 From: modelnine at bit-bukket.org (Heiko Wundram) Date: Wed, 04 Jan 2006 10:26:41 +0100 Subject: Calling GPL code from a Python application References: <86irt0g3fz.fsf@bhuda.mired.org> Message-ID: Heiko Wundram wrote: > This is not what the general interpretation of the GPL seems to be with > TrollTech and several other companies. They specifically state that even > when you develop inhouse software with GPL-libraries (Qt in the former > case), you are required to release the code of the application under the > GPL. If this weren't so (and you're the first I hear of that takes this > stance), the GPL would basically be meaningless as a business model to > them, and AFAICT this is also what the FSF tells people. By the way, this is (one of the reasons) why the MySQL client libraries were licensed under the LGPL and now under a different licensing model with explicitly permits linking to GPL-incompatible licenses, at least if you take MySQL AB's word. See here: http://www.mysql.com/company/legal/licensing/foss-exception.html and here (german) http://www.sunflyer.ch/2004/01/18/MySQL-und-die-Lizenzen.php And maybe nobody has sued Google so far because they are considered to be the good guys, generally...? --- Heiko. From cfbolz at gmx.de Sat Jan 7 13:39:43 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sat, 07 Jan 2006 19:39:43 +0100 Subject: Does Python allow access to some of the implementation details? In-Reply-To: <7xpsn4u65p.fsf@ruckus.brouhaha.com> References: <7xpsn4u65p.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Claudio Grondi writes: > >>The question is if Python allows somehow access to the bytes of the >>representation of a long integer or integer in computers memory? > > > No it doesn't, and that's a good thing, since the internal > representation is a little bit surprising (it stores 15 bits of the > long int in each 16-bit word of the representation, to make the > arithmetic routines a little simpler). > Indeed. There are even more reasons why this is a Good Thing (tm) (not only because the internal representation is surprising). Basically it gives the implementor of a Python interpreter the freedom to choose the internal representation that he deems to be the most fitting. If implementation details leaked outside that wouldn't be possible anymore. Cheers, Carl Friedrich Bolz From wjb131 at web.de Tue Jan 10 02:41:25 2006 From: wjb131 at web.de (wjb131 at web.de) Date: 9 Jan 2006 23:41:25 -0800 Subject: Help wanted with md2 hash algorithm In-Reply-To: <7xhd8cn71x.fsf@ruckus.brouhaha.com> References: <1136588090.479620.237210@o13g2000cwo.googlegroups.com> <7x4q4f2zep.fsf@ruckus.brouhaha.com> <1136719690.033553.194790@g49g2000cwa.googlegroups.com> <7x7j99rd0q.fsf@ruckus.brouhaha.com> <1136848079.386327.295030@g14g2000cwa.googlegroups.com> <7xhd8cn71x.fsf@ruckus.brouhaha.com> Message-ID: <1136878885.227234.55420@o13g2000cwo.googlegroups.com> Paul Rubin wrote: > wjb131 at web.de writes: > > I thought I had build a proper implementation in Python. The error you > > mention can be avoided by studying the C implementation in RFC 1319. > > BUT: Some of the test vectors failed. That's my problem ;-( > > And therefore I asked for help. > > You might check PyCrypt against the test vectors. > > http://www.amk.ca/python/writing/pycrypt/ Already done before my first posting. But the problem was there. I studied the C sources of MD2 of that package, too. But all test cases with more than 16 bytes failed. Wolfgang From skip at pobox.com Sun Jan 1 22:50:22 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 1 Jan 2006 21:50:22 -0600 Subject: Getting terse tracebacks? In-Reply-To: References: Message-ID: <17336.41726.992555.580354@montanaro.dyndns.org> Roy> Is there any way to make the traceback printer built into the Roy> interpreter elide all the directories in pathnames (like Roy> strip_dirs() does for the profiler)? There's a compact traceback printer in asyncore (compact_traceback). I used it as the basis for a compact stack printer: import os import sys # adapted from asyncore.compact_traceback() def compact_stack(start=0, size=100): """build a compact stack trace from frame start to end""" f = sys._getframe(start+1) # don't include this frame info = [] while f: fn = os.path.normpath(os.path.abspath(f.f_code.co_filename)) info.append((fn, f.f_code.co_name, f.f_lineno)) f = f.f_back # eliminate any common prefix the filenames share info = [(f.split(os.sep)[-1], c, l) for (f, c, l) in info] return '\n'.join(['[%s|%s|%d]' % x for x in info[:size]]) def print_compact_stack(f=sys.stderr, start=0, size=100): print >> f, compact_stack(start+1, size) Skip From cito at online.de Sun Jan 22 14:12:08 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 22 Jan 2006 20:12:08 +0100 Subject: Some thougts on cartesian products In-Reply-To: References: <1137944129.386363.265070@f14g2000cwb.googlegroups.com> <1h9k5j6.13pwlz1x7likhN%aleax@mail.comcast.net> <1h9kakf.otz7vt3x3xmrN%aleax@mail.comcast.net> Message-ID: Steven D'Aprano wrote: > I beg to differ: Python *allows* people to create classes if they're keen > on the syntax (and I can sympathise with that like), but Python > *encourages* by example generic tools that operate on as many different > types as makes sense. But these generic tools (say the "pow" function) in turn simply use the methods defined by the classes. -- Christoph From blair.houghton at gmail.com Mon Jan 30 15:32:48 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 30 Jan 2006 12:32:48 -0800 Subject: webbrowser module + urls ending in .py = a security hole? In-Reply-To: <1138651762.673682.192210@g43g2000cwa.googlegroups.com> References: <1138593557.824516.116400@g14g2000cwa.googlegroups.com> <1138626217.999480.153140@g43g2000cwa.googlegroups.com> <1138651762.673682.192210@g43g2000cwa.googlegroups.com> Message-ID: <1138653168.785362.291070@g44g2000cwa.googlegroups.com> Sorry...should read: "I did use the script to fetch remote HTML (url='http://www.python.org') before I tried the local file, and it opened the webpage in Firefox." Too many chars, too few fingers. --Blair From DonQuixoteVonLaMancha at gmx.net Tue Jan 3 15:56:58 2006 From: DonQuixoteVonLaMancha at gmx.net (Karsten W.) Date: 3 Jan 2006 12:56:58 -0800 Subject: check if class really implements api? Message-ID: <1136321818.063009.224660@o13g2000cwo.googlegroups.com> Hello, with the zope.interface module I can query if my class claims to implement my API. This is what the method implementedBy is for. However, I find myself constantly changing the API and I am looking for a more reliable way to check my implementation classes. Is there a way to check if at least all function names of the API are defined by the class and if their parameter lists fit the API? A way to test this would save me a lot of time.. Kind regards, Karsten. From jgercken at gmail.com Tue Jan 10 13:16:48 2006 From: jgercken at gmail.com (Jeff Gercken) Date: Tue, 10 Jan 2006 13:16:48 -0500 Subject: String question - find all possible versions of a person's firstname In-Reply-To: <43C3F5C7.5060408@gmail.com> References: <43C3F5C7.5060408@gmail.com> Message-ID: This sounds like a homework problem. You might try splitting the name at the e's, check the length of the resulting list and do that many nested loops. On 1/10/06, Nico Grubert wrote: > Hi there, > > I have a string 'Mich?le' that represents the firstname of a person. > > What's the best way to get all possible versions of this name if I > consider to use these characters: e, ?, ?, ? > > I'd like to have a function that returns a list of the following names > when passing 'Mich?le' as parameter to it: > > 'Michele' > 'Michel?' > 'Michel?' > 'Michel?' > > 'Mich?le' > 'Mich?l?' > 'Mich?l?' > 'Mich?l?' > > 'Mich?le' > 'Mich?l?' > 'Mich?l?' > 'Mich?l?' > > 'Mich?le' > 'Mich?l?' > 'Mich?l?' > 'Mich?l?' > > > Thanks in advance, > Nico > -- > http://mail.python.org/mailman/listinfo/python-list > From Nainto at gmail.com Wed Jan 18 12:59:01 2006 From: Nainto at gmail.com (Nainto) Date: 18 Jan 2006 09:59:01 -0800 Subject: Clicking at a certain x,y position in python? (Mac OSX) In-Reply-To: <437dqmF1ltvp1U1@uni-berlin.de> References: <1137606341.254405.127350@g47g2000cwa.googlegroups.com> <437dqmF1ltvp1U1@uni-berlin.de> Message-ID: <1137607141.521834.151580@g43g2000cwa.googlegroups.com> There's no other way? I'd rather not have to use PyyyObjc. From aleax at mail.comcast.net Mon Jan 9 22:21:04 2006 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 9 Jan 2006 19:21:04 -0800 Subject: - E04 - Leadership! Google, Guido van Rossum, PSF References: <43b15d36$0$82640$ed2619ec@ptn-nntp-reader03.plus.net> <1135782518.053020.14730@g43g2000cwa.googlegroups.com> <1135784723.379971.131020@g47g2000cwa.googlegroups.com> <1136385474.032677.125670@z14g2000cwz.googlegroups.com> <1h8sgcn.hx53zc1p9d4qoN%aleax@mail.comcast.net> <43c12936@usenet.zapto.org> <1h8ua8s.hgisbx11q115N%aleax@mail.comcast.net> <43c26451$1@usenet.zapto.org> Message-ID: <1h8wvbr.1kimxwkzippecN%aleax@mail.comcast.net> Steve Holden wrote: ... > On the available evidence that seems completely untrue. Alex, as I know > from personal experience, has no problems accepting the material rewards > of a lifetime spent developing expertise, but that doesn't make him > elitist. I guess what DOES make me an elitist is that I'm perfectly happy to see greater material rewards go to those who have greater skills or are more inclined to exert constructive effort. NOT to the skewed extent one observes in some countries -- I think countries such as Denmark, Japan, Sweden, and Belgium, with Gini indices of 25 or less, strike a better balance than ones such as the UK or Italy, with 36, not to mention the US's 40 or Brazil's 60 (particularly because it's far from certain, in high-Gini-index countries, that the "greater material rewards" are actually mostly flowing to the elite who I think _deserves_ them, the people who work hard and successfully and thus contribute to everybody's benefit, as opposed to, people whose only substantial "contribution" has been to get born in the right family). But, that's another issue. > I have seen him helping Python programmers without any monetary > reward (and he got precious little for all the time he spent as a > technical editor of "Python Web Programming"), Actually, I got the enormous pleasure of enjoying your work, and of helping you (and helping friends is always a joy!) AND the whole programming community (by helping you enhance a book that was already good to start with). _Material_ rewards are not the only ones that matter, not by a great deal! > and I know him to be quite far from elitist. I guess you and I have in mind different meanings for the word "elitist", because, as above outlined, I do consider myself one. Even though I believe in the "wisdom of crowds", I'm definitely anything but a *populist* -- the "wise crowd", as I see it, is one where each individual makes up his or her own mind on their own criteria, all different but all compatible with rationality, as opposed to "following the herd" or "fashion". Alex From ss23111983 at yahoo.co.in Fri Jan 13 12:43:29 2006 From: ss23111983 at yahoo.co.in (sandy) Date: Fri, 13 Jan 2006 17:43:29 -0000 Subject: I've started new blog Message-ID: Hi all, I've started a new blog for discussion about the help can be provided to freshers. visit following URL: http://forfreshers.blogspot.com/ please visit and let the frshers get benifit from our discussion. thank you in advance. sandeep. From shejo284 at gmail.com Tue Jan 10 08:25:46 2006 From: shejo284 at gmail.com (Sheldon) Date: 10 Jan 2006 05:25:46 -0800 Subject: syntax error In-Reply-To: <11s7c1mftjm5523@corp.supernews.com> References: <1136897662.381141.118230@z14g2000cwz.googlegroups.com> <11s7c1mftjm5523@corp.supernews.com> Message-ID: <1136899546.636407.16060@g14g2000cwa.googlegroups.com> Hi Rod, This sounds very interesting. I am checking the previous lines and will get back to you. Thanks, Sheldon From dmbkiwi at gmail.com Fri Jan 27 21:14:46 2006 From: dmbkiwi at gmail.com (dmbkiwi at gmail.com) Date: 27 Jan 2006 18:14:46 -0800 Subject: cookielib extracting a cookie value as a string Message-ID: <1138414486.581938.94500@g14g2000cwa.googlegroups.com> I am trying to extract the value of a cookie from a CookieJar() object using cookielib. I have a CookieJar() object called cj. Printing cj gives: <_LWPCookieJar.LWPCookieJar[, ]> But i can't work out how to extract the value. If I use make_cookies(), I get: [Cookie(version=0, name='GA3T', value='XMi__nHPWW4', port=None, port_specified=False, domain='www.google.com', domain_specified=False, domain_initial_dot=False, path='/accounts', path_specified=False, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}), Cookie(version=0, name='GoogleAccountsLocale_session', value='en', port=None, port_specified=False, domain='www.google.com', domain_specified=False, domain_initial_dot=False, path='/accounts', path_specified=False, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={})] But I can't find a simple way to get the "value" key pair, so I can manipulate it as a string. Can anyone please help. From has.temp2 at virgin.net Sun Jan 8 13:59:32 2006 From: has.temp2 at virgin.net (has) Date: 8 Jan 2006 10:59:32 -0800 Subject: MVC programming with python (newbie) - please help References: Message-ID: <1136652661.391322.308830@f14g2000cwb.googlegroups.com> bwaha wrote: > The author refers to mvctree.py in wxPython as an example of MVC design. > However I'm still too green so I find that particular example too complex > and I'm not understanding the separation the author is recommending. MVC is all about separation of concerns. The Model is responsible for managing the program's data (both private and client data). The View/Controller is responsible for providing the outside world with the means to interact with the program's client data. The Model provides an internal interface (API) to enable other parts of the program to interact with it. The View/Controller provides an external interface (GUI/CLI/web form/high-level IPC/etc.) to enable everything outwith the program to communicate with it. The Model is responsible for maintaining the integrity of the program's data, because if that gets corrupted then it's game over for everyone. The View/Controller is responsible for maintaining the integrity of the UI, making sure all text views are displaying up-to-date values, disabling menu items that don't apply to the current focus, etc. The Model contains no View/Controller code; no GUI widget classes, no code for laying out dialog boxes or receiving user input. The View/Controller contains no Model code; no code for validating URLs or performing SQL queries, and no original state either: any data held by widgets is for display purposes only, and merely a reflection of the true data stored in the Model. Now, here's the test of a true MVC design: the program should in essence be fully functional even without a View/Controller attached. OK, the outside world will have trouble interacting with it in that form, but as long as one knows the appropriate Model API incantations, the program will hold and manipulate data as normal. Why is this possible? Well, the simple answer is that it's all thanks to the low coupling between the Model and View/Controller layers. However, this isn't the full story. What's key to the whole MVC pattern is the _direction_ in which those connection goes: ALL instructions flow _from_ the View/Controller _to_ the Model. The Model NEVER tells the View/Controller what to do. Why? Because in MVC, while the View/Controller is permitted to know a little about the Model (specifically, the Model's API), but the Model is not allowed to know anything whatsoever about the View/Controller. Why? Because MVC is about creating a clear separation of concerns. Why? To help prevent program complexity spiralling out of control and burying you, the developer, under it. The bigger the program, the greater the number of components in that program. And the more connections exist between those components, the harder it is for developers to maintain/extend/replace individual components, or even just follow how the whole system works. Ask yourself this: when looking at a diagram of the program's structure, would you rather see a tree or a cat's cradle? The MVC pattern avoids the latter by disallowing circular connections: B can connect to A, but A cannot connect to B. In this case, A is the Model and B is the View/Controller. BTW, if you're sharp, you'll notice a problem with the 'one-way' restriction just described: how can the Model inform the View/Controller of changes in the Model's user data when the Model isn't even allowed to know that the View/Controller, never mind send messages to it? But don't worry: there is a solution to this, and it's rather neat even if it does seem a bit roundabout at first. We'll get back to that in a moment. In practical terms, then, a View/Controller object may, via the Model's API, 1. tell the Model to do things (execute commands), and 2. tell the Model to give it things (return data). The View/Controller layer *pushes instructions* to the Model layer and *pulls information* from the Model layer. And that's where your first MyCoolListControl example goes wrong, because the API for that class requires that information be *pushed* into it, so you're back to having a two-way coupling between layers, violating the MVC rules and dumping you right back into the cat's cradle architecture that you were [presumably] trying to avoid in the first place. Instead, the MyCoolListControl class should go with the flow, pulling the data it needs from the layer below, when it needs it. In the case of a list widget, that generally means asking how many values there are and then asking for each of those items in turn, because that's about the simplest and loosest way to do it and therefore keeps what coupling there is to a minimum. And if the widget wants, say, to present those values to the user in nice alphabetical order then that's its perogative; and its responsibility, of course. Now, one last conundrum, as I hinted at earlier: how do you keep the UI's display synchronised with the Model's state in an MVC-based system? Here's the problem: many View objects are stateful, e.g. a checkbox may be ticked or unticked, a text field may contain some editable text. However, MVC dictates that all user data be stored in the Model layer, so any data held by other layers for display purposes (the checkbox's state, the text field's current text) must therefore be a subsidiary copy of that primary Model data. But if the Model's state changes, the View's copy of that state will no longer be accurate and needs to be refreshed. But how? The MVC pattern prevents the Model pushing a fresh copy of that information into the View layer. Heck, it doesn't even allow the Model to send the View a message to say its state has changed. Well, almost. Okay, the Model layer isn't allowed to talk directly to other layers, since to do so would require it knows something about those layers, and MVC rules prevent that. However, if a tree falls in a forest and nobody's around to hear it, does it make a sound? The answer, you see, is to set up a notifications system, providing the Model layer with a place it can announce to no-one in particular that it has just done something interesting. Other layers can then post listeners with that notification system to listen for those announcements that they're actually interested in. The Model layer doesn't need to know anything about who's listening (or even if anyone is listening at all!); it just posts an announcement and then forgets about it. And if anyone hears that announcement and feels like doing something afterwards - like asking the Model for some new data so it can update its on-screen display - then great. The Model just lists what notifications it sends as part of its API definition; and what anyone else does with that knowledge is up to them. MVC is preserved, and everyone is happy. Your application framework may well provide a built-in notifications system, or you can write your own if not (see the 'observer pattern'). ... Anyway, hope that helps. Once you understand the motivations behind MVC, the reasons why things are done the way they are starts to make sense, even when - at first glance - they seem more complex than necessary. Cheers, has From fuzzyman at gmail.com Wed Jan 11 09:35:08 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Jan 2006 06:35:08 -0800 Subject: New Python.org website ? In-Reply-To: References: <1136984197.134545.164360@g49g2000cwa.googlegroups.com> Message-ID: <1136990108.090514.67670@z14g2000cwz.googlegroups.com> Content in ReST - iot ought to be using rest2web then. ;-) Fuzzyman http://www.voidspace.org.uk/python/rest2web/ From fredrik at pythonware.com Sat Jan 28 09:37:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Jan 2006 15:37:28 +0100 Subject: SLUT distibution mangled? References: <1138457494.565368.62690@g44g2000cwa.googlegroups.com> <1138457723.888258.167930@z14g2000cwz.googlegroups.com> Message-ID: Ido Yehieli wrote: > OKl, sorry this seems to have nothing to do with SLUT it self, for some > reason a directory names 'aux' can not be created... most bizzare. > "mkdir aux" just returns "The directory name is invalid." on windows ? win32 reserves the file names CON, PRN, AUX, CLOCK$, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 for devices. From sybrenUSE at YOURthirdtower.com.imagination Sun Jan 15 08:43:05 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 15 Jan 2006 14:43:05 +0100 Subject: SPE [was: Wingide is a beautiful application] References: <1134839352.112192.182010@o13g2000cwo.googlegroups.com> <1134929375.728971.141000@o13g2000cwo.googlegroups.com> <1137306048.933630.43570@g49g2000cwa.googlegroups.com> Message-ID: SPE - Stani's Python Editor enlightened us with: > This is a misinterpretation, SPE failed because of something else. > (As would have become clear if you would have run SPE in the > debugging mode 'python SPE.py --debug'.) IMO displayed messages should be clear without having to resort to a debugging mode. Debugging mode should only be for removing bugs, not for enlightenment of the user. Anyway, apt-getting spe now... which doesn't work: Unpacking python-wxversion (from .../python-wxversion_2.6.1.1.1ubuntu2_all.deb) ... dpkg: error processing /var/cache/apt/archives/python-wxversion_2.6.1.1.1ubuntu2 _all.deb (--unpack): trying to overwrite `/usr/lib/python2.4/site-packages/wxversion.py', which is also in package wxpython2.5.3 If it's so hard to get the requirements installed, I'd rather stick to Vim. > I adapted SPE such that it can ran out of the box of an archive (zip > or tar.gz). This has the advantage that Linux (but also Mac and > Windows) don't have to install SPE anymore but can just run it out > of a folder or USB stick, provided the right version of wxPython > (2.6) is installed on the system as it is always the case with > Ubuntu boxes. Ehm... I think I've clearly shown that, at least as far as the Ubuntu packages go, not all requirements are always there on an Ubuntu system. > If it doesn't work, let me know privately. Why? What's wrong with this newsgroup? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From __peter__ at web.de Tue Jan 24 03:46:29 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 24 Jan 2006 09:46:29 +0100 Subject: list comprehention References: <1137688948.317183.159290@z14g2000cwz.googlegroups.com> <1137689209.568911.132120@g14g2000cwa.googlegroups.com> <1137690685.243720.191690@o13g2000cwo.googlegroups.com> Message-ID: [Mathijs] > Example2: > ref=[2, 2, 4, 1, 1] > list=[2, 2, 5, 2, 4] > solution: 3 (note that only the first two 2's count, the third 2 in the > list should not be counted) [Morten Vold] > May I suggest another one-liner: > > len(set(ref).intersection(lis)) > > I have no idea how this scales/performs compared to the other > suggestions you've received, but I find it immediately comprehensible. >>> len(set([2, 2, 4, 1, 1]).intersection([2, 2, 5, 2, 4])) 2 Close, but no cigar. Peter From bj_666 at gmx.net Mon Jan 23 09:38:32 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 23 Jan 2006 15:38:32 +0100 Subject: wxPython or wxWidgets References: <1138025918.249400.6240@g43g2000cwa.googlegroups.com> Message-ID: In <1138025918.249400.6240 at g43g2000cwa.googlegroups.com>, py wrote: > i need to design a GUI for my python app. i heard of wxWidgets and was > going to look into that, but then I saw wxPython. Why would I use > wxPython over wxWidgets? wxPython are the Python bindings to wxWidgets which is a C++ library. Ciao, Marc 'BlackJack' Rintsch From paul at subsignal.org Sat Jan 14 17:01:40 2006 From: paul at subsignal.org (=?ISO-8859-1?Q?paul_k=F6lle?=) Date: Sat, 14 Jan 2006 23:01:40 +0100 Subject: SQLObject connection/transaction blowing up In-Reply-To: <1137274261.768452.7010@g47g2000cwa.googlegroups.com> References: <1137274261.768452.7010@g47g2000cwa.googlegroups.com> Message-ID: jacob.miles at gmail.com wrote: > I'm trying to connect to a mysql database, with autoCommit and caching > off, and I'm trying to create a transaction. Why does this blow up? As the traceback is telling you, your connectionString is missing the actual values. Not sure about the cache parameter but: connectionString = 'mysql://admin at localhost/mc_image_library_dev?autoCommit=1' should work. cheers Paul > >>>> from sqlobject import * >>>> connectionString = 'mysql://admin at localhost/mc_image_library_dev?cache=&autoCommit=' [snipp] > conn.autocommit(self.autoCommit) > TypeError: an integer is required > From aleax at mail.comcast.net Thu Jan 26 09:52:30 2006 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 26 Jan 2006 06:52:30 -0800 Subject: Match First Sequence in Regular Expression? References: Message-ID: <1h9reyq.z7u4ziv8itblN%aleax@mail.comcast.net> Tim Chase wrote: ... > I'm not quite sure what your intent here is, as the > resulting find would obviously be "aaa", of length 3. But that would also match 'aaaa'; I think he wants negative loobehind and lookahead assertions around the 'aaa' part. But then there's the spec about matching only if the sequence is the first occurrence of 'a's, so maybe he wants '$[^a]*' instead of the lookbehind (and maybe parentheses around the 'aaa' to somehow 'match' is specially?). It's definitely not very clear what exactly the intent is, no... Alex From matthew.garrish at sympatico.ca Mon Jan 2 14:42:42 2006 From: matthew.garrish at sympatico.ca (Matt Garrish) Date: Mon, 2 Jan 2006 14:42:42 -0500 Subject: application and web app technologies References: <1136226294.170886.159690@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1136226294.170886.159690 at z14g2000cwz.googlegroups.com... > January, 2006. > > * OO Perl/Perl6 -- Perl has worked real well for us, but we have > doubts that it is the best technology, and we want to make a serious > attempt to look at other things. It might help if you elaborated on what these "doubts" are. It doesn't sound like you know any of the languages you've listed and are hoping that somehow you'll find one magical beast by cross-posting to a bunch of groups. I don't expect you're going to have much luck. The fact that you list Perl 6 shows you aren't following Perl's development very closely. Perl 6 is not on the near horizon, and even as an avid Perl enthusiast I'd say you'd have to be insane to jump on it for production use as soon as it is. That said, Perl is still one of the best choices for both Web and admin scripting, and I don't see that you'd gain anything by rewriting all of your existing code to Ruby or Python just for the sake of saying you now use Ruby or Python (not that there's anything wrong with either, but why rewrite code for the sake of rewriting it?). If you wrote terrible and unreadable Perl code, what's really going to stop you from writing terrible and unreadable Ruby and Python code? That's more a statement on your programmers and lack of in-house style than the language. C# isn't too bad for Web scripting and quick GUIs, but I've never used it for admin scripting and the downside is that it takes a lot of effort to do tasks in .Net that are simple in Perl/Python/Ruby (particularly database work). I wouldn't use C/C++ for the web, but there's nothing stopping you. Matt From rocky at panix.com Sat Jan 7 07:54:57 2006 From: rocky at panix.com (R. Bernstein) Date: 07 Jan 2006 07:54:57 -0500 Subject: pdb.py - why is this debugger different from all other debuggers? References: <1136502205.939944.59110@o13g2000cwo.googlegroups.com> <86acearvfp.fsf@bhuda.mired.org> <86irsxqn83.fsf@bhuda.mired.org> Message-ID: Mike Meyer writes: > But if I had to choose between being > able to play with objects interactively or being able to step through > code, I'll take the interactive interpreter every time. Why would you have to choose? You've created a straw-man argument. No one has previously suggested *removing* tools or forcing one to use one and not the other! The thrust that started this thread and the intent was thoughts on *improving* debugging. You say you are happy with what you have. Great! But then out of the blue offer your non-help. And although that too wasn't the thrust of the thread either (soliciting volunteers), it's not like you apparently *had* been working on this either. Weird. > Well, the tools I'm talking about here are ones that Python comes > with. It may be simple-minded to assert that everyone who writes > Python code uses the tools that come with Python, but it's not very > bright to not use the tools that come with the language. Not if one uses *better* tools. :-) Again in this very thread another interpreter was mentioned which, alas, doesn't come with Python. But on many systems it is installed rather easily. It addresses some things that again in this thread have been noted as perhaps lacking in the stock Python-supplied interpreter. > I'm all to aware that not everyone writes code as easy to understand > as what I do. (And it just may be that not everyone finds reading your code as easy to understand as you think it is.) > The correct solution for bad code was elucidated by > Kernighan and Plauger nearly 30 years ago: "Don't fix bad > code. Rewrite it." I don't do that nearly often enough. I heartily agree. (But I also can't help note that this may be a little bit of a self-serving statement.) > A good debugger is a valuable thing, and I've used some incredible > debuggers, including one that actually implemented DWIM. Stepping > through the code is one of the least valuable thing a debugger does, > but it's also the thing that makes it a debugger. Hmmm. If that's really your view of what makes a debugger, I can see why it's not all that important to you. But this could another one of your exaggerate-to-make-absurd arguments. Now that you mention it, stepping in pydb.py does have this little thing that seems just a little different from the norm. When one steps through a class or even a script with lots of methods/functions, the debugger seems to stop at every def, which isn't all that exciting. And say in contrast to gdb's step/next, you can't give a count. (Perl allows one to enter an arbitrary expression to step/next into). These do tend to make stepping less useful. But as with the "restart" command that was mentioned at the beginning of the thread, it wasn't all that hard to address in the current code base. > Pretty much > everything else that a debugger does can be done by other tools. So tell me what tools you have to set a breakpoint somewhere in a program possibly based on variable values, inspect arbitrary values as you see fit and perhaps change them, and then either continue or restart the program depending on how long it took to get to the point and how messed up things were when you got there? None of this involves stepping, so by your definition it's something that doesn't need a debugger. > As > those tools improve, the value of the debugger decreases. Python has > very good other tools. The argument also goes the other way. If one has a debugger that's lacking -- and it looks to me that pdb.py is a little bit neglected (in some cases I would even say not pythonic)-- then, sure, people are going to try to find ways to avoid using it. This too was mentioned on this thread. Without a doubt Python has good tools. And no doubt they will continue to improve as perhaps they should. But I don't see this as an argument for not to improving debugging in Python as well. From jbperez808 at yahoo.com Wed Jan 11 22:56:05 2006 From: jbperez808 at yahoo.com (Jon Perez) Date: Thu, 12 Jan 2006 11:56:05 +0800 Subject: Indentation/whitespace In-Reply-To: <1135435420.555103.48990@g49g2000cwa.googlegroups.com> References: <1135360496.036672.326570@g47g2000cwa.googlegroups.com> <1135380715.339155.241090@o13g2000cwo.googlegroups.com> <1135435420.555103.48990@g49g2000cwa.googlegroups.com> Message-ID: thakadu wrote: > While I have no doubt that there are lousy browsers out there, the > problem is not only with browsers, but also I agree with you its not > Python's fault. The issue is that the code I am pasting may have used a > DIFFERENT indentation scheme, so lets say I used four spaces and the > code I am pasting used two spaces, or worse yet, a tab, that is where > the problem arises. Now assuming that the browser and the copy and > paste buffers dont screw up the indentation, when I paste that code > into my editor that is where the problem arises. Sure if everyone stuck > to the recommended 4 spaces in the style guide it would help. But even > then in the context of your program you may be a further level of > indentation. Although the below does work, I believe: def fun1(): print "I use two space indentation" while (1): print "but" print "four space works just as well" print "and can coexist" It just has to be consistent within a *single* block. From lycka at carmen.se Mon Jan 30 10:50:44 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 30 Jan 2006 16:50:44 +0100 Subject: VB to Python migration In-Reply-To: <1138566539.478552.113180@g49g2000cwa.googlegroups.com> References: <1138421531.231633.41140@z14g2000cwz.googlegroups.com> <1138566539.478552.113180@g49g2000cwa.googlegroups.com> Message-ID: Ravi Teja wrote: > Rewrites are always good and result in smaller code base if features > are not added. However, I doubt that will make the screens fewer. Lines > of code? Certainly. That depends on whether you just refactor the implementation of if you look at the problem domain with a different perspective than you had the first time around. Obviously, I don't know anything about this particular system, but with 230 screen it seems like some things could be generalized. I suspect a much smaller number of slightly context sensitive screens would suffice... My gut tells me that if I looked at the system, I'd find lots of screens that were basically the same, just slightly different... Whether to use the same actual screen and perhaps let it be modified in runtime due to some data driven approach or share most code in base classes and have small modules with the specialized behaviour is something to argue about in some design meetings. I'll leave that to the guys who have to do it. > You are comparing Python with VB 6. That's not what the OP is moving to > as an alternative. No, but it's what they've used and know. It's the reference for their thinking. > It's .NET. VB 6 has been out of development since 8 > years? Its not something to be compared to anymore. .NET on the other > hand has all the advantages of Python accessible toolkits for this task > and then some. But as indicated by the OP, there might be reasons not to sit down in that warm and soft lap from Redmond once more... I assume they don't consider Python as a chance to avoid having to really understand OO, or to be able to stay with the current code base. Avoiding vendor lock-in is a very reasonable aspect, and making it easier to port to non-windows platforms is also a reasonable aspect. > I am not saying Python is unfit for 230 screens. Just that I have not > seen anyone build such a thing and better write about it. Right, and this is interesting. After about 25 years of programming I'm still not sure whether I should be impressed or worried when I hear people describing systems with hundreds of screens and hundreds of database tables. I've worked with systems like that, and while I'm sure there are situations where such big systems are really warranted, the systems of this size that I saw could probably have been shrunk to a quarter of their size if proper software development practices had been used. > People on the > other hand have build web sites with such volume. Result? We have a ton > of web application frameworks to address such needs. I'm not 100% sure that the plethora of Python web kits is entirely a benefit. >>The really silly thing to do is to apply VB idioms on Python. > > It is. But that's what people do on their first few projects and it's > perfectly natural. Didn't you :-) ? No, I had used Python for years the first time I had to code VB. I'm sure I wrote stupid code, but most of my awkward programming experiences have been when I had to code Perl or VB6 after long periods when I had only written Python and C++. From timr at probo.com Sun Jan 22 01:52:01 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 22 Jan 2006 06:52:01 GMT Subject: Returning a tuple-struct References: <1137637493.938952.321270@g47g2000cwa.googlegroups.com> Message-ID: groups.20.thebriguy at spamgourmet.com wrote: >I've noticed that there's a few functions that return what appears to >be a tuple, but that also has attributes for each item in the tuple. >For example, time.localtime() returns a time.time_struct, which looks >like a tuple but also like a struct. That is, I can do: > >>>> time.localtime() >(2006, 1, 18, 21, 15, 11, 2, 18, 0) >>>> time.localtime()[3] >21 >>>> time.localtime().tm_hour >21 Ah, but it ISN'T really a tuple: >>> import time >>> t = time.localtime() >>> type(t) >>> str(t) '(2006, 1, 21, 22, 49, 32, 5, 21, 0)' It's a class object. The __repr__ method returns a string that LOOKS the same as a tuple. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From riko.wichmann at remove-this.desy.de Wed Jan 4 11:07:54 2006 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Wed, 04 Jan 2006 17:07:54 +0100 Subject: inline function call In-Reply-To: References: Message-ID: Hey guys, thanks for all the quick replies! In addition to the tips Peter and Stuart gave me above, I also followed some of the hints found under http://wiki.python.org/moin/PythonSpeed/PerformanceTips That greatly improved performance from about 3 minutes initially (inner loop about 2000, outer loop about 10000 runs - I think) down to a few seconds. My question on the inline function call was triggered by the 3 minute run on a pretty small statistic (10000 events) Monte Carlo sample. Now, I'm much more relaxed! :) One of the biggest improvements in addition to using psyco was actually being careful about avoiding global namespace lookup. So, thanks again, I learned a great deal about efficient python coding today! :) Cheers, Riko From _karlo_ at _mosor.net_ Wed Jan 4 17:47:39 2006 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Wed, 4 Jan 2006 22:47:39 +0000 (UTC) Subject: What's wrong with this code snippet? References: <1136414439.366841.247490@g49g2000cwa.googlegroups.com> Message-ID: "Gerard Flanagan" wrote in news:1136414439.366841.247490 at g49g2000cwa.googlegroups.com: > Class methods must have at least the 'self' argument. So Arrrrrgh! :) Thanks guys! -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From python-url at phaseit.net Tue Jan 10 18:08:03 2006 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 10 Jan 2006 23:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 10) Message-ID: QOTW: "I'm a huge fan of single digit numbers ..." - Jim Hugunin, illustrating his undiminished grasp on the Pythonic ethos "It's hard to say exactly what constitutes research in the computer world, but as a first approximation, it's software that doesn't have users." - Paul Graham Microsoft makes IronPython official. Sort-of: http://www.redmondmag.com/news/article.asp?EditorialsID=7116 Movable Python has the potential to affect your programming life even more than Microsoft's embrace. Yes, it's that important: http://www.voidspace.org.uk/python/movpy/ http://opag.ca/pipermail/opag/2005-December/001816.html Can a generator have "additional methods"? Raymond Hettinger, Lonnie Pricehouse, and others push the envelope: http://groups.google.com/group/comp.lang.python/browse_thread/thread/49083fe389ce321f/ Adults discuss itertools deeply: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6ada7bd0897442df/ Ziga Seilnacht supplies apparently-working code which reports on a Windows host's notions about the Python installations it has registered: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e31cb87ba2778e63/ Jean-Paul Calderone exhibits four amusingly succinct segfaults attainable with "pure Python" on, for example, standard Linux installations: http://groups.google.com/group/comp.lang.python/msg/378d8ac5b87ba694 Sit in windowless rooms with other T-shirt clad zealots--it's PyCon 2006! http://us.pycon.org/TX2006 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From brianc at temple.edu Mon Jan 16 16:46:22 2006 From: brianc at temple.edu (Brian Cole) Date: Mon, 16 Jan 2006 16:46:22 -0500 Subject: Restarting scripts In-Reply-To: References: Message-ID: <54b165660601161346w48d28e9cn638c65f4a5e93d0@mail.gmail.com> If everything dies by a Python exception... if __name__ == '__main__': try: main(sys.argv) except: os.execlp("python", "python", sys.argv) Pretty nasty peice of code, but it works well for restarting your script. -Brian On 1/16/06, Ron Griswold wrote: > > > > This may be a little OT, but it does involve python scripts. I've written a > server that hosts my companies asset management system. Of course something > like this cannot be down for very long without data being lost (of course I > have taken measures to inform the user of the down time and ask them nicely > to please try again later? but in the real world people will just bypass the > system and save manually). So what I need is some facility to start the > server, and if it goes down, automatically start it back up again. > > > > If anyone has any ideas on how I might accomplish this, either with python > code, or third party software, I'd love to hear about it. > > > > Thanks, > > > > Ron Griswold > > Character TD > > R!OT Pictures > > rgriswold at rioting.com > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From Pavol.Severa at gmail.com Sat Jan 14 09:34:48 2006 From: Pavol.Severa at gmail.com (Pavol.Severa at gmail.com) Date: 14 Jan 2006 06:34:48 -0800 Subject: Sudoku solver: reduction + brute force References: <1137196845.482476.217160@f14g2000cwb.googlegroups.com> Message-ID: <1137249288.634242.259160@g49g2000cwa.googlegroups.com> ago wrote: > Inspired by some recent readings on LinuxJournal and an ASPN recipe, I > decided to revamp my old python hack... The new code is a combination > of (2) reduction methods and brute force and it is quite faster than > the > ASPN program. If anyone is interested I attached the code in > http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html I suggest trying input=""" 0,0,0,0,9,6,8,0,0 0,0,1,0,0,0,0,7,0 0,2,0,0,0,0,0,0,3 0,3,0,0,0,8,0,0,6 0,0,4,0,2,0,3,0,0 6,0,0,5,0,0,0,8,0 9,0,0,0,0,0,0,5,0 0,7,0,0,0,0,1,0,0 0,0,5,9,4,0,0,0,0""" your program seems to take too long to solve it. I think the hard part is not to solve, but rather to create *difficult* sudoku grids. But to inflate my ego beyond the known universe, here is my solver (that solves the avove mentioned grid reasonably fast). I suppose the only difference is that is uses 3, rather than 2, rules to simplify before starting tree-like search. ######### #if a copyryght is needed: #this is pulbic domain, do with it whatever you want #i.e. most probably nothing ######### class DeadEnd(Exception): pass class sudoku(object): def __init__(self,*args): self.changed=True self.possible=[] if len(args) != 81: raise ValueError, "need 81 numbers" for i in args: if i==0: self.possible.append(range(1,10)) else: self.possible.append([i]) def __getitem__(self,(x,y)): return self.possible[9*x+y] def __setitem__(self,(x,y),what): self.possible[9*x+y]=what def copy(self): result=sudoku(*(81*[1])) for i in range(9): for j in range(9): result[i,j]=list(self[i,j]) return result def solved(self): for i in range(9): for j in range(9): if len(self[i,j]) != 1: return False return True def trials(self): for i,j in ((i,j) for ln in range(2,10) for i in range(9) for j in range(9) if len(self[i,j])==ln): for k in self[i,j]: new=self.copy() new[i,j]=[k] yield new def clean1(self,x,y): self.changed=False if len(self[x,y]) == 1: return remove=set() for places in self.regions(x,y): missing=set(range(1,10)) for xx,yy in places: if xx==x and yy==y: continue if len(self[xx,yy])==1: remove.add(self[xx,yy][0]) missing-=set(self[xx,yy]) if missing: a=missing.pop() self[x,y]=[a] self.changed=True for a in remove: try: self[x,y].remove(a) if not self[x,y]: raise DeadEnd self.changed=True except ValueError: pass def clean3(self,out1,out2): for (o1, o2) in ((out1,out2), (out2,out1)): remove=set(range(1,10)) for x,y in o1: remove-=set(self[x,y]) for x,y in o2: for n in remove: try: self[x,y].remove(n) if not self[x,y]: raise DeadEnd self.changed=True except ValueError: pass @staticmethod def regions(x,y): return (((xx,y) for xx in range(9)), ((x,yy) for yy in range(9)), ((xx,yy) for xx in range(3*(x//3),3*(x//3)+3) for yy in range(3*(y//3),3*(y//3)+3))) @staticmethod def outs(): for i in range(3): for j in range(3): for k in range(3): out1=[(a+3*i,b+3*j) for a in range(3) if a is not k for b in range(3)] out2=[(k+3*i,n) for n in range(9) if n//3!=j] yield out1, out2 for k in range(3): out1=[(a+3*i,b+3*j) for a in range(3) for b in range(3) if b is not k] out2=[(n,k+3*j) for n in range(9) if n//3!=i] yield out1, out2 def clean_all(self): while self.changed: self.changed=False for x in range(9): for y in range(9): self.clean1(x,y) for out1,out2 in self.outs(): self.clean3(out1,out2) def __repr__(self): result="" for x in range(9): for y in range(9): if len(self[x,y])==1: haf=self[x,y][0] else: haf=self[x,y] result+=str(haf)+' ' result+='\n' return result from collections import deque class liter(object): def __init__(self, *iterables): self.iters=deque(iter(x) for x in iterables) def __iter__(self): while self.iters: it=self.iters.popleft() try: result=it.next() except StopIteration: continue self.iters.append(it) yield result def append(self,what): self.iters.append(iter(what)) def solve(me): tree=liter([me]) for you in tree: try: you.clean_all() except DeadEnd: continue if you.solved(): return you tree.append(you.trials()) ###### input=( 0,0,0,0,9,6,8,0,0, 0,0,1,0,0,0,0,7,0, 0,2,0,0,0,0,0,0,3, 0,3,0,0,0,8,0,0,6, 0,0,4,0,2,0,3,0,0, 6,0,0,5,0,0,0,8,0, 9,0,0,0,0,0,0,5,0, 0,7,0,0,0,0,1,0,0, 0,0,5,9,4,0,0,0,0) result=solve(sudoku(*input)) print result From mooquack at suad.org Sat Jan 28 16:11:30 2006 From: mooquack at suad.org (Kirk McDonald) Date: Sat, 28 Jan 2006 13:11:30 -0800 Subject: String Manipulation Help! In-Reply-To: <1138481853.165529.321870@z14g2000cwz.googlegroups.com> References: <1138481853.165529.321870@z14g2000cwz.googlegroups.com> Message-ID: <43dbdd2c$1@nntp0.pdx.net> Dave wrote: > OK, I'm stumped. > > I'm trying to find newline characters (\n, specifically) that are NOT > in comments. > > So, for example (where "<-" = a newline character): > ========================================== > 1: <- > 2: /*<- > 3: ----------------------<- > 4: comment<- > 5: ----------------------<- > 6: */<- > 7: <- > 8: CODE CODE CODE<- > 9: <- > ========================================== [snip] Well, I'm sure there is some regex that'll do it, but here's a stupid iterative solution: def newlines(s): nl = [] inComment = False for i in xrange(len(s)): if s[i:i+2] == '/*': inComment = True if s[i:i+2] == '*/': inComment = False if inComment: continue if s[i] == '\n': nl.append(i) return tuple(nl) Your example returns: (0, 64, 65, 80, 81) This probably isn't as fast as a regex, but at least it works. -Kirk McDonald From Ernste at gmail.com Sun Jan 15 10:32:54 2006 From: Ernste at gmail.com (Ernst Elzas) Date: 15 Jan 2006 07:32:54 -0800 Subject: Replacing bidirectional unicode strings/regexps Message-ID: <1137339174.447844.291810@o13g2000cwo.googlegroups.com> Hello, I've tried to write a "sed s/original/replacement/g " -like script, but for dealing with situations where both original and replacement contain a mixture of left to right and right to left text (for now, English and Hebrew) Both the texts can span multiple lines, and the replacement has to be in files of a specific type (html) in all subdirectories. I'll probably need to create the script (or at least the text to be replaced and it's replacement) in some editor, since commandlines don't seem to like bidirectional texts that much. I figured this would be easy, but have not managed to get something working, nor have I found examples to use. I did find some Python scripts doing related things, but they went wrong as soon as I tried to adapt them to bidirectional text, the Perl sed-like script also looked promising, but I did not manage to get that working either in this situation. Please note that I had no prior experience with the use of either language, and might easily have overlooked the simple solution. Thanks for your help, Ernst From mwm at mired.org Wed Jan 4 22:09:16 2006 From: mwm at mired.org (Mike Meyer) Date: Wed, 04 Jan 2006 22:09:16 -0500 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <86acebd1y2.fsf@bhuda.mired.org> <43BC7DD6.9050805@REMOVEMEcyber.com.au> Message-ID: <861wzncqw3.fsf@bhuda.mired.org> Steven D'Aprano writes: > Mike Meyer wrote: >> Steven D'Aprano writes: >>>On Wed, 04 Jan 2006 10:54:17 -0800, KraftDiner wrote: >>>>I was under the assumption that everything in python was a refrence... >>>>so if I code this: >>>>lst = [1,2,3] >>>>for i in lst: >>>> if i==2: >>>> i = 4 >>>>print lst >>>>I though the contents of lst would be modified.. (After reading that >>>>'everything' is a refrence.) >>>See, this confusion is precisely why I get the urge to slap people who >>>describe Python as "call by reference". It isn't. >> Except this doesn't have *anything at all* to do with python being >> (or >> not being) call by reference. This is a confusion about name binding >> vs. assignment to a variable. The proper people to slap around for >> this case are the ones who talk about assignment to a variable. > Mike, you are wrong. Not about talk about "assigning to variables" > being harmful, I agree with that. But this confusion is *exactly* > about the call by reference misunderstanding. How do I know this? > > Because the Original Poster said so! He said, to paraphrase, "Hey, I > thought Python was call by reference, but I tried this, and it didn't > work, what gives???" And he's right, and you're wrong. Look at the *code*. There isn't a single call in it. He may have said "call by reference", but his example code didn't have anything to do with call by rereference, and he didn't demonstrate any confusion about the semantics of parameter passing. He *did* demonstrate confusion about the semantics of the assignment statement. >>>It is "call by object" -- you pass around *objects*. Internally, this is >>>quite fast, because the entire object doesn't need to be moved, only >>>pointers to objects, but you don't get the behaviour of either call by >>>reference or call by value. >> No, you get *exactly* that behavior from call by reference when you >> start passing objects around by reference. > Who cares what Python does internally? It is strictly irrelevant > whether Python internally passes around pointers, or copies values, or > sometimes one or the other. Who said anything about what Python does internally? I agree, it's strictly irrelevant. What matters is the *behavior*. >> If I declare a C object as >> "struct foo bar" and do the C "call-by-reference" hack of passing >> &bar, I get the exact same behavior I get when I pass an object >> referenced by bar to a Python subroutine. > It is not a question of whether Python's behaviour is *sometimes* the > same as call by reference. The question whether Python's behaviour is > *always* the same as CBR, and it is not. You're wrong. Python's behavior is *always* the same as CBR, once you identify what Python is passing a reference to. > Likewise, you shouldn't argue that Python is obviously call by value > just because *sometimes* it has the same behaviour as CBV. Actually, it's either always the same as CBV, or never the same as CBV. It's always the same as CBV because you always pass a value - and the value is always a reference. But every calling mechanism requires that you always pass a value. It's what the value is that determines the calling mechanism. You pass a reference for CBR, and a name for call by name. > I mean, come on! A whole bunch of people argue black and blue that > Python "obviously" is call by reference, and another vocal bunch argue > that it is "obviously" call by value. I don't think I've seen anyone arguing that Python is call-by-value. There are people who argue that it's sometimes one and soemtimes the other, but that's mostly because they have incorrectly identified what Python is passing a reference to. > Just google on "Python is call by value" and "Python is call by > reference" -- including quotes -- to see this argument come up time > and time again, year after year after year. And all because of some > false dichotomy that CBR and CBV are the only two valid descriptions > of a computer language. I tried the google, and I don't see a lot of arguments. I see people declaiming one way or another, and not very many of those. I don't think it's an apparent dichotomy has much to do with it. I know there are other things than CBV and CBR, and even understand Jensen's device. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jstroud at ucla.edu Tue Jan 24 21:33:12 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 24 Jan 2006 18:33:12 -0800 Subject: logging into secure website with script In-Reply-To: <1138155601.647749.40370@o13g2000cwo.googlegroups.com> References: <1138155601.647749.40370@o13g2000cwo.googlegroups.com> Message-ID: dpoehls wrote: > Hello there, > > I am new to python, and shell scriping in general..I have done quite a > bit of php, but that it about it. Anyhow, I am wondering if it would be > possible to write a python script that would login to a password > enabled site (qmailadmin) and then be able to add a new account. I > imagine it could be done by accessing the website and then it would > send POSTs to the website? If this makes no sense, I apologize, just > wondering if anyone could point me in the right direction. Thanks ahead > of time! > Spend some time perusing this code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 It helped me with a similar problem. I'm not sure if it works for https. If the form is using POST to "hide" the login, just suck the web page and change POST to GET. Then use your sucked webpage and submit your login from it. You will then see the fields (separated by "+"s and the values, separated from the fields by "="s). Use the fields and values to populate the "txdata" dictionary in the example using urllib.urlencode (an example is in the discussion). James From bretthoerner at gmail.com Thu Jan 19 20:02:11 2006 From: bretthoerner at gmail.com (Brett Hoerner) Date: 19 Jan 2006 17:02:11 -0800 Subject: how to find not the next sibling but the 2nd sibling or findsibling "a" OR sinbling "b" In-Reply-To: <1137710393.212201.208840@g49g2000cwa.googlegroups.com> References: <1137611999.797593.164690@g47g2000cwa.googlegroups.com> <1137699882.648075.247520@g44g2000cwa.googlegroups.com> <1137710393.212201.208840@g49g2000cwa.googlegroups.com> Message-ID: <1137718931.615844.75720@g49g2000cwa.googlegroups.com> localpricemaps at gmail.com wrote: > hey fredrik, > > i don't understand what you are saying Do what he showed in the Python interactive shell, > Fredrik Lundh wrote: > > 'food' or 'drink' doesn't do what you think it does: > > > > >>> 'food' or 'drink' > > 'food' > > > > >>> {'class': 'food' or 'drink'} > > {'class': 'food'} "or" returns the first true element, anything but False or None, I think... so 'food' (a string) is true, and always will return in that code. http://diveintopython.org/power_of_introspection/and_or.html Brett From michele.simionato at gmail.com Thu Jan 5 03:32:49 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 5 Jan 2006 00:32:49 -0800 Subject: Python article in Free Software Magazine In-Reply-To: References: <1136393156.863086.303500@g43g2000cwa.googlegroups.com> Message-ID: <1136449969.542278.277780@o13g2000cwo.googlegroups.com> Some of the reasons are explained here: http://www.amk.ca/python/writing/why-not-zope.html I am using the last Zope (2.8.4) at work, and the situation is slightly better now than in the past, but only slightly. Zope 3 looks better, but I am not sure how much better. Michele Simionato From LukasMeyerUK at gmail.com Wed Jan 11 04:38:54 2006 From: LukasMeyerUK at gmail.com (LukasMeyerUK at gmail.com) Date: 11 Jan 2006 01:38:54 -0800 Subject: Restart process with SIGHUP Message-ID: <1136972334.145748.101590@g49g2000cwa.googlegroups.com> Hello, I'm trying to restart a process with the os.kill command. My Problem is that if the command gets executed, my python script stops working. I want to SIGHUP a process with the following command: os.kill(pid, signal.SIGHUP). Can anyone give me a hint in solving this? Best regards, Lukas From mwm at mired.org Sun Jan 15 03:02:53 2006 From: mwm at mired.org (Mike Meyer) Date: Sun, 15 Jan 2006 03:02:53 -0500 Subject: Is 'everything' a refrence or isn't it? References: <1136400857.126833.111990@z14g2000cwz.googlegroups.com> <1136664144.464232.289760@g49g2000cwa.googlegroups.com> <1137111113.310683.178770@o13g2000cwo.googlegroups.com> <1137212572.427212@jetspin.drizzle.com> <864q46wicc.fsf@bhuda.mired.org> <86irsmv088.fsf@bhuda.mired.org> <86wth2t939.fsf@bhuda.mired.org> Message-ID: <86d5itudea.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 14 Jan 2006 23:21:14 -0500, Mike Meyer wrote: >> So those properties of object() are all identical because they're >> really properties of object. If you define an object() by those >> properties, you have to conclude that object is itself an instance of >> object(). > In this specific case, object instances get their properties from the > class, but your conclusion doesn't follow. The easiest way to tell this is > to ask, can we distinguish the object class (type) from an object > instance? The answer is, yes we can: >>>> object > >>>> object() > Yes, but you're not looking at properties of the object, but rather of the type of the object. And for what it's worth, object is an instance of object. >>> isinstance(object, object) True http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gregtech at wp.pl Mon Jan 23 16:13:02 2006 From: gregtech at wp.pl (Grzegorz Smith) Date: Mon, 23 Jan 2006 22:13:02 +0100 Subject: trying to get hash from os.urandom Message-ID: Hi all I'm writing small python module which will be a password generator. I read that python can use system random generator on machine whit *nix os. So i start using os.urandom and when i generate random string i get something like this: urandom(8) -> '\xec2a\xe2\xe2\xeb_\n',"\x9f\\]'\xad|\xe6\xeb",'\xb0\xf8\xd3\xa0>01\xaf'. How can I convert this to hash? i change python defaultencoding from ascii to utf-8 and try convert this to unicode object but I only get: '\xb4\xa8b\xed\xb9Y-\xf3' Any help i will appreciated. Does anyone use os.urandom to cryptography? Gregor From gene.tani at gmail.com Wed Jan 18 02:15:57 2006 From: gene.tani at gmail.com (gene tani) Date: 17 Jan 2006 23:15:57 -0800 Subject: search multiple dictionaries efficiently? In-Reply-To: References: Message-ID: <1137568557.078857.127700@g14g2000cwa.googlegroups.com> Livin wrote: > I'm a noobie so please be easy on me. I have searched a ton and did not find > anything I could understand. > > I'm using py2.3 > > I've been using Try/Except but this gets long with multiple dictionaries. > > I found some code on web pages and such but cannot get them to work. Any > help is appreciated as I need to search multiple dictionaries for keys. > > > > here's the code I found but cannot get to work... > > dict_set = (self.dictHSdevices, self.dictHSevents, self.dictHSbtnDevices) > <-- /creates set of dictionaries/ > > /code to search the set/--> > > val = [ d for d in dict_set if d[value] in dict_set ] > OR > for key, value in dict.iteritems(): pass http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305268 http://mail.python.org/pipermail/python-list/2005-August/294519.html (I think these may be a little different from what you're asking above, since they search dicts sequentially and return 1st hit) From tim.leeuwvander at nl.unisys.com Mon Jan 16 09:39:41 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 16 Jan 2006 06:39:41 -0800 Subject: Python and Word In-Reply-To: <1137421747.147357.157470@f14g2000cwb.googlegroups.com> References: <1137418609.701104.321930@g47g2000cwa.googlegroups.com> <1137420613.562874.52080@g44g2000cwa.googlegroups.com> <1137421747.147357.157470@f14g2000cwb.googlegroups.com> Message-ID: <1137422381.224069.244930@o13g2000cwo.googlegroups.com> Hi Rod, If you download and install the 'Python Win' extensions, which I think are linked from from the Python download page for windows, you have a set of COM classes for Python which allow you to do everything you can do in Word from a Python program. It allows a lot of interactive exploration at the command prompt, although not everything is very obvious (in part due to the way the word object model is structured). BTW, if you are new to Python, why not use VBA for the program? cheers, --Tim From roy at panix.com Fri Jan 13 08:47:04 2006 From: roy at panix.com (Roy Smith) Date: Fri, 13 Jan 2006 08:47:04 -0500 Subject: how do "real" python programmers work? References: <1137097250.592204.129310@g43g2000cwa.googlegroups.com> <86wth5eys7.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > we need a term for development environment built out of Unix tools.... We already have one. The term is "emacs". From duncan.booth at invalid.invalid Fri Jan 27 08:07:58 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Jan 2006 13:07:58 GMT Subject: decorators to add test* TestCase methods References: <1138363674.195738.316890@g44g2000cwa.googlegroups.com> Message-ID: Bruce Cropley wrote: > Hi all > > I'm trying to generate test methods in a unittest TestCase > subclass, using decorators. I'd like to be able to say: > > class MyTestCase(unittest.TestCase): > @genTests(["Buy", "Sell"], [1,2,3], [True, False]) > def something(self, side, price, someFlag): > # etc... > I would make the decorator simply save its arguments as attributes on the function and then add an explicit call after the class has been created to go and generate the tests. so (untested code): def generateTests(klass): for name in dir(klass): fn = getattr(klass, name) if hasattr(fn, 'genTests'): # generate tests here... def genTests(*args): def decorator(f): f.genTests = args return f return decorator and then: class MyTestCase(unittest.TestCase): @genTests(["Buy", "Sell"], [1,2,3], [True, False]) def something(self, side, price, someFlag): # etc... generateTests(MyTestCase) You could automate the call to generateTests using a metaclass if you wanted to avoid the explicit call. From godoy at ieee.org Fri Jan 13 11:42:23 2006 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 13 Jan 2006 14:42:23 -0200 Subject: return values of os.system() on win32 References: Message-ID: <87lkxkqdu8.fsf@ieee.org> rbt writes: > Is it safe to say that any value returned by os.system() other than 0 is an > error? I believe not. That depends on the return/error code of the specific program you ran. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From steve at REMOVETHIScyber.com.au Sun Jan 1 04:33:39 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 01 Jan 2006 20:33:39 +1100 Subject: Hypergeometric distribution References: <1135628335.580063.179200@z14g2000cwz.googlegroups.com> <1h871o5.4kfq9m1ueam9zN%aleax@mail.comcast.net> <1136075042.504604.122680@g14g2000cwa.googlegroups.com> Message-ID: On Sat, 31 Dec 2005 16:24:02 -0800, Raven wrote: > Thanks to all of you guys, I could resolve my problem using the > logarithms as proposed by Robert. I needed to calculate the factorial > for genomic data, more specifically for the number of genes in the > human genome i.e. about 30.000 and that is a big number :-) > I didn't know gmpy > Thanks a lot, really Are you *sure* the existing functions didn't work? Did you try them? >>> def log2(x): ... return math.log(x)/math.log(2) ... >>> n = 0.0 >>> for i in range(1, 300000): # ten times bigger than you need ... n += log2(i) ... >>> n 5025564.6087276665 >>> t = time.time(); x = 2L**(int(n) + 1); time.time() - t 0.26649093627929688 That's about one quarter of a second to calculate 300,000 factorial (approximately), and it shows that the calculations are well within Python's capabilities. Of course, converting this 1.5 million-plus digit number to a string takes a bit longer: >>> t = time.time(); len(str(x)); time.time() - t 1512846 6939.3762848377228 A quarter of a second to calculate, and almost two hours to convert to a string. Lesson one: calculations on longints are fast. Converting them to strings is not. As far as your original question goes, try something like this: (formula from memory, may be wrong) >>> def bincoeff(n,r): ... x = 1 ... for i in range(r+1, n+1): ... x *= i ... for i in range(1, n-r+1): ... x /= i ... return x ... >>> bincoeff(10, 0) 1 >>> bincoeff(10, 1) 10 >>> bincoeff(10, 2) 45 >>> bincoeff(10, 3) 120 >>> import time >>> t = time.time(); L = bincoeff(30000, 7000); time.time() - t 28.317800045013428 Less than thirty seconds to calculate a rather large binomial coefficient exactly. How many digits? >>> len(str(L)) 7076 If you are calculating hundreds of hypergeometric probabilities, 30 seconds each could be quite painful, but it certainly shows that Python is capable of doing it without resorting to logarithms which may lose some significant digits. Although, in fairness, the log function doesn't seem to lose much accuracy for arguments in the range you are dealing with. How long does it take to calculate factorials? >>> def timefact(n): ... # calculate n! and return the time taken in seconds ... t = time.time() ... L = 1 ... for i in range(1, n+1): ... L *= i ... return time.time() - t ... >>> timefact(3000) 0.054913997650146484 >>> timefact(30000) # equivalent to human genome 5.069951057434082 >>> timefact(300000) # ten times bigger 4255.2370519638062 Keep in mind, if you are calculating the hypergeometric probabilities using raw factorials, you are doing way too much work. -- Steven. From alanmk at hotmail.com Fri Jan 13 16:52:00 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 13 Jan 2006 21:52:00 +0000 Subject: XML vs. cPickle In-Reply-To: <1137179729.890964.279170@o13g2000cwo.googlegroups.com> References: <1137179729.890964.279170@o13g2000cwo.googlegroups.com> Message-ID: [Mike] > I know XML is more (processor) costly than cPickle, but how bad is it? Are you sure you know that? I'd guess that XML serialisation with cElementTree is both cpu and memory competitive with cpickle, if not superior. Although I'm too lazy to fire up the timeit module right now :-) Also, how quickly the relevant parsers work depends on the input, i.e. your data structures. Only you can take measurements with your data structures .... > The idea is I want to store data that can be described as XML can != should > into my > database as cPickle objects. Except my web framework has no support for > BLOB datatype yet, and I might have to go with XML. Or you could encode the binary pickle in a text-safe encoding such as base64, and store the result in a text column. Although that will obviously increase your processing time, both going in and out of the database. > Ideas are appreciated, I'd write a few simple prototypes and take some empirical measurements. HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From cartercc at gmail.com Tue Jan 3 16:37:23 2006 From: cartercc at gmail.com (ccc) Date: 3 Jan 2006 13:37:23 -0800 Subject: application and web app technologies In-Reply-To: <84zuf.1485$H37.218721@news20.bellglobal.com> References: <1136226294.170886.159690@z14g2000cwz.googlegroups.com> <1136306578.271826.302110@g44g2000cwa.googlegroups.com> <84zuf.1485$H37.218721@news20.bellglobal.com> Message-ID: <1136324243.848092.57630@o13g2000cwo.googlegroups.com> > If no one knows the language > you want to use, do you have time to account for the learning curve? Do you > really want to try and replace all your programmers? We don't have any 'programmers' on staff. At most, we have several people writing, maybe, two hours of code a week, with maybe once a year building an application. We are just your basic IT shop, system and network administration, hardware, help desk, the web site, and database administration. This is also the reason for the 'bad code' ( which we have in abundance.) People who are not programmers and whose job it isn't to program will not write good code. I'm not being perjorative, just factual. > If you let > programmers build their own little universes they will! Yeah, well, if you have a database admin writing his scripts, a network admin writing his scripts, and a couple of floaters trying to fix things that break, with no one holding the reins, you get little universes. Which is what happened and which we want to be proactive and prevent in the future. > You should probably look at other measures > that involve your programmers more in making the coding a collective > practice (peer review, for example). So long as the focus is constructive, > it will help the group better understand what they should all be striving > for and what they should all be doing. That more than anything will help > prevent you from winding up in the same mess in a few years when you > discover each person has their own coding ideas for whatever language you > opt for. Exactly! And a major decision is deciding on a technology so that we'll all be using the same thing. Actually, Java was a pretty easy decision to make, since we already had a problem with Perl, no one wanted to do C or C++, and no one knows VB, and most of us had used Java at some point along the way. HOWEVER, we know we face a learning curve, and we want to get the most bang for the buck, and we have a good enough handle on our Perl scripts so this isn't a time critical desicion, so we are just looking. CC From dennis.varghese at wipro.com Thu Jan 19 21:59:11 2006 From: dennis.varghese at wipro.com (pycraze) Date: 19 Jan 2006 18:59:11 -0800 Subject: why is my hash being weird?? In-Reply-To: References: <1137649610.117757.31830@g14g2000cwa.googlegroups.com> <43CF50A3.3080101@REMOVEMEcyber.com.au> <1137677484.929233.273350@o13g2000cwo.googlegroups.com> Message-ID: <1137725951.521840.176000@g49g2000cwa.googlegroups.com> Surely adopting the above method is much better than what i have approached earlier . The main reason i did adopt this exercise was when i have to marshal a 20 - 40 MB above test.py file to the disk , the simple load of the test.py will sky rocket my virtual memory consumption. I was bit troubled with this bottleneck , so i wanted to do some research before i come to some conclusions . Anyways , i really appreciate ur enthusiasm to helping me come to a conclusion Dennis From WESTBCL04 at juniata.edu Sat Jan 28 19:19:31 2006 From: WESTBCL04 at juniata.edu (Westbrook, Christopher L (WESTBCL04)) Date: Sat, 28 Jan 2006 19:19:31 -0500 Subject: Trouble opening files Message-ID: <76102184A7588C4D8770BEB3D90B62EA0FA7B91F@MAIL2K.juniata.edu> I am having some trouble, and I can't figure out why. I'm trying to use the simple keylogger project from source forge, and then create a web interface to open the resulting files, so people from the outside can see the keys logged on a server. I've got the keylogger script working fine, and I have a script that reads and displays all the directories and files of the log directory, but when I select the link of the file it doesn't open. I've made some changes to the pykeylogger source, mainly using @@ between the date and window name rather than _ and getting rid of the window handle. First, I have placed the script that makes the page with the lists of the directories and files, and then I've pasted the script that opens the file, or at least attempts to. Can someone help? #!c:\python24\python.exe import os print"Content-type:text/html\n\n"; print"directory list" for f in os.listdir("c:\\temp\\logdir"): print "

",f,"

\n" subdir = os.path.join("c:\\temp\\logdir",f) #debug info here print "
subdir=",subdir for g in os.listdir(subdir): print "
g= ",g file = os.path.splitext(g)[0] print "
file=",file fullPath = os.path.join(subdir,file) [date, name] = file.split('@@') print "",name,"" print "
last modified: ",date #now for the script that opens the file #!c:\\python24\\python.exe #import re import cgi import string form = cgi.FieldStorage() print "Content-type:text/html\n\n"; filename = form["file"].value+".txt" #all files end in .txt extension filename = filename.replace("\\","\\\\") #print filename f = file(filename,'\r') #open file for reading for line in f: #replace carriage returns with html newline characters line = line.replace("\r","
") print line I'm running this on a windows machine. Any help would be appreciated. From rodmc at userpro.com Sun Jan 8 10:12:08 2006 From: rodmc at userpro.com (rodmc) Date: 8 Jan 2006 07:12:08 -0800 Subject: Sockets on Windows and Mac References: <1136638006.316311.324250@g44g2000cwa.googlegroups.com> <43c0f7ca$0$11067$e4fe514c@news.xs4all.nl> Message-ID: <1136733128.750173.228440@g49g2000cwa.googlegroups.com> I am on 10.3, I keep getting exceptions when it hits lines like mySocket.bind (SERVER_IP, 2727 ) or mySocket = socket.socket(socket.AF_NET,socket.SOCK_STREAM) The code I am using is copied from a tutorial on a website somewhere. Cheers, rod From bokr at oz.net Mon Jan 30 17:50:15 2006 From: bokr at oz.net (Bengt Richter) Date: Mon, 30 Jan 2006 22:50:15 GMT Subject: "Intro to Pyparsing" Article at ONLamp References: <1138444565.250434.28030@g47g2000cwa.googlegroups.com> <1138548235.414808.134410@g44g2000cwa.googlegroups.com> Message-ID: <43de95be.669114065@news.gmane.org> On Mon, 30 Jan 2006 16:39:51 -0500, Peter Hansen wrote: >Christopher Subich wrote: >> Using English, because that's the only language I'm fluent in, consider >> the sentence: >> >> "The horse raced past the barn fell." >> >> It's just one of many "garden path sentences," where something that >> occurs late in the sentence needs to trigger a reparse of the entire >> sentence. > >I can't parse that at all. Are you sure it's correct? Aren't "raced" >and "fell" both trying to be verbs on the same subject? English surely >doesn't allow that forbids that sort of thing. () > The computer at CMU is pretty good at parsing. You can try it at http://www.link.cs.cmu.edu/link/submit-sentence-4.html Here's what it did with "The horse raced past the barn fell." : ++++Time 0.00 seconds (81.38 total) Found 2 linkages (2 with no P.P. violations) Linkage 1, cost vector = (UNUSED=0 DIS=0 AND=0 LEN=13) +------------------------Xp------------------------+ | +----------------Ss---------------+ | +-----Wd-----+ +----Js----+ | | | +--Ds-+---Mv--+--MVp--+ +--Ds-+ | | | | | | | | | | | LEFT-WALL the horse.n raced.v past.p the barn.n fell.v . Constituent tree: (S (NP (NP The horse) (VP raced (PP past (NP the barn)))) (VP fell) .) IIUC, that's the way I parse it too ;-) (I.e., "The horse [being] raced past the barn fell.") BTW, the online response has some clickable elements in the diagram to get to definitions of the terms. Regards, Bengt Richter From rockyrocks_m.21fn6t at no-mx.forums.yourdomain.com.au Tue Jan 10 13:20:27 2006 From: rockyrocks_m.21fn6t at no-mx.forums.yourdomain.com.au (rockyrocks_m) Date: Tue, 10 Jan 2006 13:20:27 -0500 Subject: Opening for Python Professionals Message-ID: Hi I AM RAVEESH We have Urgent Openings with a leading UK based Mnc at Noida Delhi NCR for Python professsionsl ( scripting/ Programming, Developers) Exp Level --------- 1----8 Years Excellent Salary Send cvs at raveeshdgntechnologies at yahoo.com raveesh at dgntechnologiesinc.com raveesh_13 at yahoo.com -- rockyrocks_m Message posted via http://www.exforsys.com for all your training needs. From noaddress at ohno.email.com Tue Jan 17 13:20:52 2006 From: noaddress at ohno.email.com (Twig) Date: Tue, 17 Jan 2006 19:20:52 +0100 Subject: Looking for standalone Python Message-ID: Hello, I have a need to have python on intranet server for other users to create a common tool base for working community (SW). So that workers can take it in use just by mapping the drive adding dirs to paths. Need to have all standard modules at the same place, so there would not be any local installations required. Is this possible? Easy? Any ideas. From jtanis at pycoder.org Sat Jan 7 00:52:06 2006 From: jtanis at pycoder.org (James Tanis) Date: Sat, 7 Jan 2006 00:52:06 -0500 Subject: python speed In-Reply-To: References: Message-ID: <65dcde740601062152m3083c112p162cfc3332629524@mail.gmail.com> Quite honestly I've never heard of java being faster than.. well.. anything. Faster than Python? I really doubt it. Their are several libraries for game programming specifically as well as opengl, sdl, as well as several different audio systems/daemons.. I'd suggest browsing through the categories in python.org's module search engine. Disclaimer (:P): The majority of generalizations have some amount of exceptions, the java crack above was just my opinion - it was not really intended to offend any java addicts out there (the poor, miss-guided souls). On 11/29/05, Krystian wrote: > Hi > are there any future perspectives for Python to be as fast as java? i > would like to use Python as a language for writing games. > > best regards > krystian > -- > http://mail.python.org/mailman/listinfo/python-list > -- James Tanis jtanis at pycoder.org http://pycoder.org From none at no.chance Tue Jan 3 04:40:24 2006 From: none at no.chance (Peter Tillotson) Date: Tue, 03 Jan 2006 09:40:24 +0000 Subject: python concurrency proposal In-Reply-To: <1136251504.521728.113350@g49g2000cwa.googlegroups.com> References: <1136251504.521728.113350@g49g2000cwa.googlegroups.com> Message-ID: I'd really like to see a concurrency system come into python based on theories such as Communicating Sequential Processes (CSP) or its derivatives lambda or pi calculus. These provide an analytic framework for developing multi thread / process apps. CSP like concurrency is one of the hidden gems in the Java Tiger release (java.util.concurrency). The advantages of the analytic framework is that they minimise livelock, deadlock and facilitate debugging. I'm no expert on the theory but i've developed under these frameworks and found them a more reliable way of developing distributed agent systems. You may also be interested in looking at http://sourceforge.net/projects/pympi p corey.coughlin at comcast.net wrote: > Alright, so I've been following some of the arguments about enhancing > parallelism in python, and I've kind of been struck by how hard things > still are. It seems like what we really need is a more pythonic > approach. One thing I've been seeing suggested a lot lately is that > running jobs in separate processes, to make it easy to use the latest > multiprocessor machines. Makes a lot of sense to me, those processors > are going to be more and more popular as time goes on. But it would > also be nice if it could also turn into a way to make standard > threading a little easier and trouble free. But I'm not seeing an easy > way to make it possible with the current constraints of the language, > so it seems like we're going to need some kind of language improvement. > Thinking of it from that perspective, I started thinking about how it > would be easy to deal with in a more idealized sense. It would be nice > to abstract out the concept of running something in parallel to > something that can be easily customized, is flexible enough to use in a > variety of concepts, and is resonably hard to screw up and fairly easy > to use. Perhaps a new built-in type might be just the trick. Consider > a new suite: > > pardef (self, , arguments...): > self.send(, , arguments) > self.receive(, arguments) > return arguments > yield arguments > > so the object would then be something you can create an instance of, > and set up like a normal object, and it would have other interface > functions as well. Consider your basic vector add operation: > > import concurrent > import array > > pardef vecadd(self, concurrent.subprocess, veca, vecb, arrtype): > import array > output = array.array(arrtype) > for a,b in zip(veca, vecb): > output.append( a + b) > return output > > a = array.array('d') > b = array.array('d') > for i in range(1000): > a.append(float(i)) > b.append(float(i)) > > h1 = vecadd(a[:500], b[:500], 'd') > h2 = vecadd() > h2.veca = a[500:] > h2.vecb = b[500:] > h2.arrtype = 'd' > > h1.run() > h2.run() > c = h1.result + h2.result > > You can see a few things in this example. First off, you'll notice > that vecadd has the import for array inside it. One of the most > important things about the pardef is that it must not inherit anything > from the global scope, all variable passing must occur through either > the arguments or .receive statements. You'll also notice that it's > possible to set the arguments like instance values. This isn't as > important in this case, but it could be very useful for setting > arguments for other pardefs. Take this example of your basic SIMD-ish > diffusion simulation: > > import concurrent > > pardef vecadd(self, concurrent.subprocess, right, left, up, down, > initval): > current = initval > maxruns = 100 > updef = not (isinstance(up, int) or isintance(up, float)) > downdef = not (isinstance(down, int) or isintance(down, float)) > rightdef = not (isinstance(right, int) or isintance(right, float)) > leftdef = not (isinstance(left, int) or isintance(left, float)) > for i in range(maxruns): > if updef: > upval = self.receive(up, 'up') > else: > upval = up > if downdef: > downval = self.receive(down, 'down') > else: > downval = down > if rightdef: > rightval = self.receive(right, 'right') > else: > rightval = right > if leftdef: > leftval = self.receive(left, 'left') > else: > leftval = left > current = (upval + downval + leftval + rightval) / 4 > if updef: > up.send('down', current) > if downdef: > down.send('up', current) > if rightdef: > right.send('left', current) > if leftdef: > left.send('right', current) > return current > > diffgrid = {} > for x, y in zip(range(10), range(10)): > diffgrid[(x, y)] = vecadd() > for x, y in zip(range(10), range(10)): > gridpt = diffgrid[(x, y)] > gridpt.initval = 50.0 > if x == 0: > gridpt.left = 75.0 > else: > gridpt.left = diffgrid[(x-1, y)] > if x == 10: > gridpt.right = 50.0 > else: > gridpt.right = diffgrid[(x+1, y)] > if y == 0: > gridpt.down = 0.0 > else: > gridpt.down = diffgrid[(x, y-1)] > if y == 10: > gridpt.up = 100.0 > else: > gridpt.up = diffgrid[(x, y+1)] > for coord in diffgrid: > diffgrid[coord].run() > for x, y in zip(range(10), range(10)): > print '(%i, %i) = %f' % (x, y, diffgrid[(x,y)].return()) > > Now sure, this example is a little contrived, but it shows the utility > of allowing the input parameters to be set after instantiating the > pardef. You can also imagine that this would be useful for running a > single pardef over and over again with different arguments. > Remember that pardefs don't inherit any data from the global scope. > Data is only passed in through receive statements and the arguments. > The would control how the send and receive functions work, > and how the return and yield pass data back. In a way, the pardef > works something like a built in type, and something like an interface. > In this way, it can be used to implement different kinds of > parallelism. It could be used for threads, for processes, and > conceivably for clustering as well. I suspect that the easiest way to > implement it would be to use strict data copying for send and recieve, > and only allow shared data through the arguments, but it would be > easiest to leave it to the implementation. This would in > effect create this data type as more of an interface than anything > else. Since parallel processing is kind of complicated, this would > allow for a number of different approaches, but still keep them all > within the same framework, creating consistency between the approaches. > You could test with a safe version of threading, then change it to a > less safe but higher performance version if you need to, and so on. > Ultimately the approach would be obvious without having to get bogged > down in details. > So to be specific, the interface to this object would consist of at > least the following functions: > > .run() -> runs the code, or restarts from a yield, non-blocking > .return() -> gets the return or yield value of the code, blocking > .send(