From jzgoda at o2.usun.pl Fri Nov 11 06:37:30 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 11 Nov 2005 12:37:30 +0100 Subject: XML GUI In-Reply-To: <1131457704.275657.237970@g49g2000cwa.googlegroups.com> References: <1131457704.275657.237970@g49g2000cwa.googlegroups.com> Message-ID: py napisa?(a): > Looking for information on creating a GUI using a configuration file > (like an XML file or something). Also, how do you map actions (button > clicks, menu selections, etc) to the XML? Depending on GUI toolkit, you will have a range of choices: Glade for GTK, XRC for wxPython, Qt dialog editor also produces XML files with UI description. Each of these toolkits has its own way to process GUI events. -- Jarek Zgoda http://jpa.berlios.de/ From cito at online.de Thu Nov 24 12:47:43 2005 From: cito at online.de (Christoph Zwerschke) Date: Thu, 24 Nov 2005 18:47:43 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132844756.190248.141870@g47g2000cwa.googlegroups.com> References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> <1132828514.489889.7110@g44g2000cwa.googlegroups.com> <1132844756.190248.141870@g47g2000cwa.googlegroups.com> Message-ID: Fuzzyman schrieb: > d.keys() will still return a copy of the list, so d.keys()[i] will > still be slower than d.sequence[i] Right, I forgot that. Bengt suggested to implement __call__ as well as __getitem__ and __setitem__ for keys, values and items. In this case, you could very effectively access it as d.values[i]. -- Christoph From bokr at oz.net Thu Nov 3 22:08:05 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 04 Nov 2005 03:08:05 GMT Subject: Not Equal to Each Other? References: <1131066067.980875.223790@g43g2000cwa.googlegroups.com> Message-ID: <436ace8a.66565105@news.oz.net> On 3 Nov 2005 17:01:08 -0800, ale.of.ginger at gmail.com wrote: >Another question: I am writing a sudoku solving program. The >'solving' part of is just multiple iterations. It will take random >numbers and keep switching it all around until a set of logic >statements has been met (ie; all numbers in a row are not equal to each >other) ... that's where my question comes in. > >Cellboard = my list for storing each row/column's data. > >Rather than writing > >cellboard[0] is not* (cellboard[1] and cellboard[2] and cellboard[3] >and cellboard[4] ... cellboard[8]) >cellboard[1] is not (cellboard[0] and cellboard[2] and cellboard[3] and >cellboard[4] ... cellboard[8]) >etc... > >* should this be != ? > >the above so that all the data in one row is not equal to each other, >is there something I can write to make it simpler? For example, >(cellboard[0] is not cellboard[1] is not ... cellboard[8]) only worked >for the numbers to the left and right of the cell - is there anyway I >can expand this to cover all numbers in a set range? > UIAM if you have a list of items that are comparable and hashable, like integers, you can make a set of the list, and duplicates will be eliminated in the set. Therefore if the resulting set has the same number of members as the list it was made from, you can conclude that the list contains no duplicates. E.g., >>> cellboard = range(8) >>> cellboard [0, 1, 2, 3, 4, 5, 6, 7] >>> set(cellboard) set([0, 1, 2, 3, 4, 5, 6, 7]) >>> len(set(cellboard)) 8 >>> cellboard[2] = 7 >>> cellboard [0, 1, 7, 3, 4, 5, 6, 7] >>> set(cellboard) set([0, 1, 3, 4, 5, 6, 7]) >>> len(set(cellboard)) 7 So the test would be >>> len(set(cellboard))==len(cellboard) False And after repairing the list to uniqueness of elements: >>> cellboard[2] = 2 >>> len(set(cellboard))==len(cellboard) True HTH Regards, Bengt Richter From bokr at oz.net Tue Nov 22 01:33:44 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 06:33:44 GMT Subject: Looking for magic method to override to prevent dict(d) from grabbing subclass inst d contents directly Message-ID: <4382b99b.436079699@news.oz.net> Has anyone found a way besides not deriving from dict? Shouldn't there be a way? TIA (need this for what I hope is an improvement on the Larosa/Foord OrderedDict ;-) I guess I can just document that you have to spell it dict(d.items()), but I'd like to hide the internal shenanigans ;-) Regards, Bengt Richter From cito at online.de Sun Nov 27 06:00:23 2005 From: cito at online.de (Christoph Zwerschke) Date: Sun, 27 Nov 2005 12:00:23 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <4389193a.8914908@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <1132735254.039468.106660@g44g2000cwa.googlegroups.com> <4385b7b6.632202659@news.oz.net> <4389193a.8914908@news.oz.net> Message-ID: Bengt Richter wrote: >>d.keys[:] = newkeyseq > > Do you really mean just re-ordering the keys without a corresponding reording of values?? > That would be a weird renaming of all values. Or do you means that any key should still > retrieve the same value as before if used as d[key]? In which case the values must undergo > the same permutation as the keys. I.e., you are assuming key->value pairings remain stable > through any key reorderings? Since it is considered as being a dictionary in the first place, the key->value pairings should of course stay stable. In the usual implementation based on an ordinary dictionary with an additional key list ("sequence" in the Foord/Larosa and "_keys" in the Bejamin/Winter implementation), you would only set the key list, since the value list is generated dynamically. But if your implementation keeps internal values or items lists, these need to be adjusted as well. I will assume that d has is a Foord/Larosa ordered dict with "sequence" attribute in the following. Then, with other words, d.keys[:] = newkeyseq should do the same as: d.sequence = newkeyseq > Exactly what, though? should e.g. > d.keys[3] = newk3 > mean (not a suggested implementation, just to define semantics) > keys = d.keys() > if newk3 in keys and keys.index(newk3)!=3: > raise ValueError,'Attempt to introduce duplicate key' > items = d.items() > items[3] = (newk3, items[3][1]) > d.clear() > d.update(items) Yes, that would be the correct semantics. Of course this should not be the real implementation and use KeyError instead of ValueError. With other words, d.keys[i] = newkey sould be the same as: if d.sequence[i] != newkey: if newkey in d.sequence: raise KeyError,'Attempt to introduce duplicate key' else: d.sequence[i] = newkey > This would allow what you might call renaming in place. > Similarly > d.keys[i:j] = newkeysij > might have the semantics of > keys = d.keys() > outside = set(keys[:i])+set(keys[j:]) > if outside & set(newkeysij) or len(newkeysij) != len(set(newkeysij)): > raise ValueError,'Attempt to introduce duplicate key(s)' > items = d.items() > items[i:j] = [(k, items[kx+i][1]) for kx,k in enumerate(newkeysij)] > d.clear() > d.update(items) > > Is this what is desired? Not quite, because it does not preserve the key->value pairings (see above) and it would behave strangely or raise an exception if the new slice is larger. The following code would do: keys = d.keys() outside = set(keys[:i])|set(keys[j:]) if outside & set(newkeysij) or len(newkeysij) != len(set(newkeysij)): raise ValueError,'Attempt to introduce duplicate key(s)' items = d.items() items[i:j] = [(k, d.get(k, None)) for k in newkeysij] d.clear() d.update(items) (Note that there was a bug in the second line. You cannot add sets.) Again, this would be equivalent to: seq = d.sequence newseq = seq[:] newseq[i:j] = newkeysij if len(newseq) != len(set(newseq)): raise KeyError,'Attempt to introduce duplicate key(s)' for k in set(seq[i:j]) - set(newkeysij): del d[k] for k in set(newkeysij) - set(seq[i:j]): d[k] = None d.sequence = newseq >>You don't keep track of the item lists, they need to be built on every >>occasion. > > That depends on how you implement ;-) Ok, I was thinking of the usual implementations. > Back from holiday, so maybe I'll hack something out. Let us know when you have something to check out. Maybe Fuzzyman can make some moderate improvements to the existing odict.py, and you can do something more "radical". Then we have two "reference implementations" and can compare how they prove regarding performance and usability. -- Christoph From onurb at xiludom.gro Wed Nov 23 08:56:35 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 23 Nov 2005 14:56:35 +0100 Subject: a new design pattern for Python Library? In-Reply-To: <1132738181.664201.272500@g44g2000cwa.googlegroups.com> References: <1132709883.708313.279720@g44g2000cwa.googlegroups.com> <1132738181.664201.272500@g44g2000cwa.googlegroups.com> Message-ID: <43847514$0$21623$636a15ce@news.free.fr> Ben Sizer wrote: > The Eternal Squire wrote: > >>I tend to use this design pattern a lot in order to aid in >>compartmentalizing interchangeable features in a central class that >>depend on the central class's data. > > > I'm afraid I've read this paragraph and the code 3 times and I still > have no idea what you're trying to convey. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed Nov 23 07:18:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 13:18:14 +0100 Subject: Hot to split string literals that will across two or more lines ? References: Message-ID: Magnus Lycka wrote: > Fredrik Lundh wrote: >> cursor.execute( >> 'select * from foo' >> ' where bar=%s' >> ' limit 100', >> bar >> ) > > The disavantage with this is that it's easy to make > a mistake, like this... > > cursor.execute( > 'select * from foo ' > 'where bar=%s' > 'limit 100', > bar > ) that's why I prefer to put the spaces first. if you do that, you'll spot the mistakes immediately. (on the other hand, the chance that the SQL engine won't notice this typo is pretty slim). > That might be a reason to prefer triple quoting instead: > > cursor.execute( > '''select * from foo > where bar=%s > limit 100''', > bar > ) "but it looks ugly" (as usual, threads like this goes round and round and round ;-) > This last version will obviously contain some extra whitespace > in the SQL text, and that could possibly have performance > implications, but in general, I prefer to reduce the risk of > errors (and I've made mistakes with missing spaces in adjacent > string literals). absolutely. but if you don't want newlines and whitespace in your strings, using auto-catenated plain literals is a good alternative, at least if you combine with a little indentation discipline. From randomtalk at gmail.com Sat Nov 19 22:40:58 2005 From: randomtalk at gmail.com (randomtalk at gmail.com) Date: 19 Nov 2005 19:40:58 -0800 Subject: query domain registry from python? Message-ID: <1132458058.364466.110450@f14g2000cwb.googlegroups.com> hi, does anyone know of a library that can query domain registry or any site that provide information to such an activity? as i want to build a simple domain name searching program for my own benefit.. thanks alot :D From aleax at mail.comcast.net Fri Nov 11 00:41:51 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 10 Nov 2005 21:41:51 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131639786.958533.45070@z14g2000cwz.googlegroups.com> Message-ID: <1h5tx6n.ayer08s58osaN%aleax@mail.comcast.net> petantik wrote: ... > I think that is not workable because it is easy to say the the internet > is available everywhere. This implies that, if it were difficult to say it, then the scheme WOULD be workable... which I doubt is what you mean, of course;-) > It is not available in developing countries or in rural areas and so Things are getting better all the time in these respects - and they will keep getting better, quite apart from "web apps", because access to information is MUCH more precious than mere computation. > these people who live/work there will never benefit from a webservice > type protection scheme, It's debatable whether the customer BENEFITS from having their ability to run an application RESTRICTED. It appears that the trend (in developing countries even more than in rich ones) is towards using open source, anyway. > and what if the network in your area goes down? > bye bye app that I *really* need for tomorrow. Reliability is But the risk of your specific MACHINE going down is much higher than that of the NET going down in all of its forms at once! If I rely on a web app, and need to use it tonight to have something ready tomorrow, then if my machine goes down (or I suffer a power brown-out in my area, an occurrence that is frequent in many developing countries, and not unheard of in developed ones), then I stand a chance to rush elsewhere, to a library, town hall, internet cafe, or ANY other location where I may be able to grab a machine, ANY machine, connect to the net, identify and authenticate myself, and keep using that crucial web app. If said app is well designed and mature, it will have autosaved most of my work up to the point of my machine's crash (or the area brown-out, etc), too. The importance of reliability speaks in FAVOUR of keeping important stuff on the internet, rather than on unreliable, crash-prone local machines (...and when's the last time you did a full backup of all of your work with all proper precautions...? For most users, "never" -- for users of web apps hosted on well-maintained sites, on the other hand, backups ARE taken care of, professionally and properly!). > important but so is protecting your code in an effective manner There is no effective manner of protecting your code, except running it only on well-secured machines you control yourself. If you distribute your code, in ANY form, and it's at all interesting to people with no interest in respecting the law, then, it WILL be cracked (and if users choose to respect the law, then you need no "protecting"). > I do believe that you are right about those that crack software for > kicks or money. If you look around at you local market place i'm sure > there are many 'discounted' commercial softwares/games sold. of course > the big software companies might say 'trusted computing will save us' > but I for one will never truly trust it. > > Perhaps a comprehensive protection for interpreted languages can never > be built because of their high level nature? Many, perhaps most, of those cracked commercial programs have NOT been written in "interpreted languages" (whatever that means), but in assembly code, C, C++... so your last paragraph is easily shown to be an irrelevant aside -- it's not an issue of what language the code is in. Alex From exarkun at divmod.com Tue Nov 8 22:37:10 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 8 Nov 2005 22:37:10 -0500 Subject: Storing empties In-Reply-To: <1h5q338.dzx76si94rwcN%aleax@mail.comcast.net> Message-ID: <20051109033710.10365.1173173431.divmod.quotient.5493@ohm> On Tue, 8 Nov 2005 19:28:36 -0800, Alex Martelli wrote: >Aahz wrote: > ... >> >For pickling, object() as a unique "nothing here, NOT EVEN a None" >> >marker (AKA sentinel) works fine. >> >> How does that work? Maybe I'm missing something obvious. >> >> sentinel = object() >> class C: >> def __init__(self, foo=sentinel): >> self.foo = foo >> def process(self): >> if self.foo is not sentinel: >> .... >> >> Now, the way I understand this, when your application restarts and an >> instance of C is read from a pickle, your sentinel is going to be a >> different instance of object() and process() will no longer work >> correctly. Are you suggesting that you need to pickle the sentinel with >> the instance? Or is there some other trick I'm missing? > >Yes, I'd set self.sentinel=sentinel (and test wrt that) -- while in the >abstract it would be better to set sentinel at class level, since >classes are only pickled "by name" that wouldn't work. > >If you don't need the absolute ability to pass ANY argument to C(), >there are of course all sorts of workaround to save some small amount of >memory -- any object that's unique and you never need to pass can play >the same role as a sentinel, obviously. This is a reasonable trick, though: class sentinel: pass Now sentinel pickles and unpickles in a manner which agrees with the above pattern without any extra works. Jean-Paul From lycka at carmen.se Mon Nov 7 07:53:55 2005 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 07 Nov 2005 13:53:55 +0100 Subject: Using Which Version of Linux In-Reply-To: References: Message-ID: blah at blah.blah wrote: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. Maybe you've already figured it out, but Ubuntu is your distro. See http://www.ubuntulinux.com/ It's based on Debian, but while standard Debian is a bit daunting to get up and running the first time, Ubuntu is one of the easiest Linux distros. Ubuntu is also much more up-to-date than the stable Debian, but still very stable. If you just want to try it out, and don't want to repartition your disk (or install a second disk), you can try the Ubuntu Live CD. Ubuntu has good support for modern hardware and a polished user interface, and it's very much focused on Python. You'll find a lot of Python modules that are maintained in the Ubuntu repositiories and will be kept up-to-date with something similar to Windows Update, all very convenient if you're on the net. Naturally, you can install Python source packages and run 'python setup.py install' the normal way, but then you won't get this auto-update feature. Mark Shuttleworth's projects, such as Ubuntu and School Tool, are also investing good money in Python development. You can even get Ubuntu CDs sent to you for free! Order ten and give out to your friends! I think it's a good way to promote Python. I've used Linux since Slackware 2.3. (Or 2.2?1994?) I'm certainly computer literate, but never had the stamina to get the normal Debian distro to work. After Slackware, I've tried Red Hat, SuSE and Mandrake etc, and I mainly use Red Hat Enterprise Linux at work, but given a choice I prefer Ubuntu these days. From raNOsky at deveSPAMler.com Fri Nov 11 04:14:00 2005 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Fri, 11 Nov 2005 10:14:00 +0100 Subject: LARGE numbers References: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> <1131691903.961955.19950@o13g2000cwo.googlegroups.com> Message-ID: casevh at comcast.net wrote: > An early alpha-quality release is available at > http://home.comcast.net/~casevh/ Given the module named "Decimal" in Python 2.4, I'd suggest you to rename your library. -- Giovanni Bajo From rurpy at yahoo.com Tue Nov 22 22:59:35 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 22 Nov 2005 19:59:35 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> <1132712643.968300.151010@g49g2000cwa.googlegroups.com> <1132713954.040591.120660@f14g2000cwb.googlegroups.com> Message-ID: <1132718374.960509.206800@z14g2000cwz.googlegroups.com> bonono at gmail.com wrote: > r... at yahoo.com wrote: > > > * It is bug-prone -- zip(x,x) behaves differently when x is a sequence > > > and when x is an iterator (because of restartability). Don't leave > > > landmines for your code maintainers. > > > > Err thanks for the advice, but they are *my* code maintainers and > > I am the best judge of what constitutes a landmine. > :-) > > > > * The design spirit of zip() and related functions is from the world of > > > functional programming where a key virtue is avoidance of side-effects. > > > Writing zip(it, it) is exploiting a side-effect of the implementation > > > and its interaction with iterator inputs. The real spirit of zip() is > > > having multiple sequences translated to grouped sequences out -- the > > > order of application (and order of retrieving inputs) should be > > > irrelevant. > > > > I'm not sure what to say when people start talking about "spirit" > > when making technical decisions. > I am with raymond on this one though. It is not really about spirit but > the definition of zip(). How it would interact with "it", whatever it > is really has nothing to do with the functionality of zip(), and there > is no technically reason why it would do it one way or another. zip() > only gurantee zip(a,b) to be [(a0,b0), (a1,b1) ...], no more, no less. I don't have a problem with that. That is a reason based on the intrinsic behavior that zip() should have, without regard to how someone might or might not use it. In contrast, Raymond's arguments were based on how zip() might be used if it were more precisely defined. I did not take any position on how zips behavior should be defined, my only beef was the arguments used in support of not defining it. I am not sure if I looked at the same SF Bug that Raymond refered to, but the submitter also was not asking for a change of behavior, only either documenting how zip() behaves, or documenting it as undefined. Seemed like a resonable request to me. > > > * Currently, a full understanding of zip() can be had by remembering > > > that it maps zip(a, b) to (a0, b0), (a1, b1), . . . . That is simple > > > to learn and easily remembered. In contrast, it introduces unnecessary > > > complexity to tighten the definition to also include the order of > > > application to cover the special case of zip being used for windowing. > > > IOW, making this a defined behavior results in making the language > > > harder to learn and remember. > > > > I don't see how defining zip()'s behavior more precisely, interfers > > at all with this understanding. > See above. Sorry, I still don't see that defining the order in which the argument elements are processed, makes zip() harder to understand in any real material sense. > > > Overall, I think anyone using zip(it,it) is living in a state of sin, > > > drawn to the tempations of one-liners and premature optimization. They > > > are forsaking obvious code in favor of screwy special cases. The > > > behavior has been left undefined for a reason. > > > > I really don't understand this point of view. It is exactly what > > I was just complaining about in a different thread. Every one > > your reasons (except the last, which is very weak anyway) is > > based on how you think someone may use zip if you define > > fully what it does. > > > > Why do you feel compelled to tell me how I should or > > shouldn't write my code?! > > > > It is this attitude of "we know what is best for you, child" > > that really pisses me off about Python sometimes. Please > > make language decisions based on technical considerations > > and not how you want me to use the language. Believe it > > or not, I can make those decisions on my own. > > That is so central to python though ;-) > > But I think it is implemented in a very interesting way, depends on > some magical thing in the head of the creator. > > Unlike a language like Haskell where you must ahere or else your > program won't run(Haskell compiler writers consider it a BUG in the > language if you find a trick to corner it), Python allows you to do a > lot of tricky things yet have lots of interesting idioms telling you > not to. Haskell is high on the queue to be learned (along with Ocaml) but I would not consider either as general purpose prgramming languages in the sense of C, Java, or (almost) Python. (But maybe I am wrong) So I would not be surprised to find them to be built around, and enforce, a very specific programming style. > But that to me is one thing I like about Python, I can ignore the idiom > and do my work. Well, I do too mostly. On rereading my post, it seems I overreacted a bit. But the attitude I complained about I think is real, and has led to more serious flaws like the missing if-then-else expression, something I use in virtually every piece of code I write, and which increases readability. (Well, ok that is not the end of the world either but it's lack is irritating as hell, and yes, I know that it is now back in favor.) From norman at littletank.org Fri Nov 11 05:58:38 2005 From: norman at littletank.org (Norman Silverstone) Date: Fri, 11 Nov 2005 10:58:38 +0000 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> <1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: > did you test the script? here's a simulator: < snip> Fredrik, thank you very much indeed for taking the trouble to show me the way. I am sorry that I made the comment I did, that will teach me to read more carefully. It is said that there is no fool like an old fool and, as I am approaching 78 years old, I think I qualify. It is also said that you are never too old to learn so I am trying. Now, I put the script you gave into an editor and ran it , (I use Ubuntu Linux by the way). It certainly showed how the computer arrived at the number guessed but guessed the number itself and gave me no chance to say whether high or low. I noticed also that the numbers were all greater than 50 and the loop ran until the number guessed was 100, then it stopped. Perhaps you can point out to me how I should go about debugging. Incidentally, I am only just starting to learn about functions and have not come across the module 're'. Also why is it (lo+hi)//2 and not (lo+hi)/2. Thanks again for your help. Norman > # end > >> Comments please. > > if this had been a java "let's pretend you're the java runtime" > certification question, you would have failed. > > From stefan.arentz at gmail.com Thu Nov 3 08:55:31 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 03 Nov 2005 14:55:31 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> Message-ID: <87d5lhltt8.fsf@keizer.soze.com> Antoon Pardon writes: > Op 2005-11-03, venk schreef : > > You see, > > The seen behavior is due to the result of python's name > > binding,scoping scheme. > > I know what causes the behaviour. But I still think it is > not sane behaviour. > > > > ... > > > > the same thing happens in the case of b.a = b.a + 2 .... search for b.a > > not found, read the value from the enclosing scope (of the class > > object).... then assign b.a to the local scope, with the value 3. > > This is an explanation depending on a specific implementation. > > Now can you give me a language design argument that supports the > idea that in "b.a = b.a + 2" b.a refers to two different objects. > > And even if you could do that, can you give such an argument that > in "b.a += 2" that one occurence of b.a should refer to two different > objects. Your problem is a namespace conflict together with a certain stubborness about lookup order :-) It is really simple. When you say b.a then the instance variable 'a' is looked up first. If it does not exist then a class variable lookup is done. Remember, Python is a dynamic language. It is all according to how things have been in Python for a long time. The real issue here is that you should propery name class variables so that there can't be any confusion about class or instance scope. I use all uppercase identifiers for class variables for example. S. From me at privacy.net Thu Nov 17 06:07:04 2005 From: me at privacy.net (Dan Sommers) Date: Thu, 17 Nov 2005 06:07:04 -0500 Subject: Simulating call-by-reference References: Message-ID: On Thu, 17 Nov 2005 10:03:50 GMT, Rikard Bosnjakovic wrote: > What I want is to rewrite it to something like this: > l = [ (re1, myclass.bar), > (re2, myclass.foo), > (re3, myclass.baz), > ] > for (x,y) in l: > m = re.search(x, y) > if m: > y = m.group(1) > But since Python doesn't work that way, that idea is doomed. What I'm > looking for are other (better) ways or pointers to accomplish this > task of cleanup. Put the results into a dictionary (untested code follows!): l = [ (re1, 'bar'), (re2, 'foo'), (re3, 'baz'), ] results = {} for (regexp, key) in l: m = re.search(regexp, data) if m: results[key] = m.group(1) Now you can access the results as results['foo'], etc. Or look up the Borg pattern in the ASPN cookbook and you can access the results as results.foo, etc. Regards, Dan -- Dan Sommers From tim.vets at skynet.be Thu Nov 24 06:39:55 2005 From: tim.vets at skynet.be (tim) Date: Thu, 24 Nov 2005 12:39:55 +0100 Subject: Python Midi Package: writing events non-chronologically Message-ID: <4385A68B.7060802@skynet.be> Someone using Python Midi Package from http://www.mxm.dk/products/public/ lately? I want to do the following : write some note events in a midi file then after doing that, put some controllers at the beginning of the midifile (because I want to be able to make those dependant on what notes were just written) def midctrls(): global roffset, melchan, roffset, gmt, timedisplay, out_file, midi, usednotes, n midi.reset_time() #seems to do nothing for cha in range(16): if cha==1: midi.abs_time=0 #seems to do nothing midi._relative_time = 0 #seems to do nothing, but I can imagine why midi._absolute_time = 0 #seems to do nothing midi.update_time(new_time=0, relative=0) #although I give the variable relative=0 it seems to be relative ? midi.continuous_controller(cha, 0, 122) (snip) With this code I want a controller number 0 with value 122 to be written at the beginning of my midifile. It is written at the end, how I move the writing position to the beginning? thanks for any help! From sybrenUSE at YOURthirdtower.com.imagination Tue Nov 1 14:14:38 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 1 Nov 2005 20:14:38 +0100 Subject: python.org offline References: <1130868156.412172.254110@g43g2000cwa.googlegroups.com> Message-ID: calad.sigilon at gmail.com enlightened us with: > Works fine for me, and I check it pretty frequently. Perhaps it's a > problem with your ISP's communication with the Python.org ISP? I doubt it, since they are one and the same ;-) 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 steve at holdenweb.com Mon Nov 7 08:13:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 Nov 2005 13:13:29 +0000 Subject: strange sockets In-Reply-To: References: <8ft*3tU2q@news.chiark.greenend.org.uk> Message-ID: Skink wrote: > Sion Arrowsmith wrote: > >>conn.sendall(struct.pack("!i", len(data)) + data) >> >>or after creating conn >> >>conn.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) >> >>to disable Nagle. >> > > > Sion, > > thank you for your help, > > it works but... > it works when client & server is in python > i tried both solutions and they work when client is client.py > they both don't work when client is java client > when i tried to connect python's server by java client i have the same: > > % java Loader server.py server.py server.py > init 29 > server.py reading 631 1 > server.py reading 631 40 > server.py reading 631 41 > > why? > Seems to me that should probably be a question for comp.lang.java. 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 mde at micah.elliott.name Fri Nov 18 16:57:32 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Fri, 18 Nov 2005 13:57:32 -0800 Subject: Choose meaningful subjects for posts [was: Re: newb ?] In-Reply-To: <11nsgj6250bne4e@corp.supernews.com> References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> <86u0eaj5ed.fsf@bhuda.mired.org> <11nsbh2r64kb9ae@corp.supernews.com> <17278.14762.150392.942325@montanaro.dyndns.org> <11nsgj6250bne4e@corp.supernews.com> Message-ID: <20051118215732.GC9941@kitchen.client.attbi.com> On Nov 18, Grant Edwards wrote: > There is an NNTP patch to allow you to use mutt to read Usenet > via an NNTP server. Yes, I'm aware of it; it's last (alpha) update was in 1999 and it probably has some fleas. :-) > Mutt users who don't do that seem to like slrn -- it has a very > similar look and feel. Cool! Thanks for the info. I might give it a try. -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From python-url at phaseit.net Wed Nov 9 12:08:03 2005 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 09 Nov 2005 17:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 9) Message-ID: QOTW: "The lesson for me is to spend much less time on Python discussion and much more on unfinished projects. So even if I never use the new syntax, I will have gained something ;-)" - Terry Reedy "In short, this group is a broad church, and those readers with brains the size of planets should remember that they are just as much in a minority as the readers who appear on the list for the first time this week. The vast majority are here to learn and grow, and I think that's the sort of behaviour we should be encouraging." -- Steve Holden The reasons you like Python probably are put into words in at least one of these threads: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b41ca4ba29b84471/ Tim Golden, ... help make the most of Excel: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bcd29beecba33c98/ Spread your expertise around, face-to-face, just outside Dallas. http://groups.google.com/group/comp.lang.python.announce/msg/b7f6f62db23e1265 Program generators date from the Carboniferous. Or the age of Cobol. Well, from *some* time in the past, as least. . . . Except that they keep turning up nowadays, in such guises as refinable templating systems: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8962903fc5717bfa/ While generators (like program generators, recursion, and many other powerful concepts) are great, they're *best* less often than is commonly realized: http://groups.google.com/group/comp.lang.python/browse_thread/thread/af6560b12bc719a6/ Deprecation of functionalism isn't an idle exercise. The point is not just to *say*, yes, we can live without lambda; Fredrik Lundh, for example, embraces New Python Style's willingness to define and redefine function objects, exactly in contrast to older lambda-oriented codings: http://mail.python.org/pipermail/tkinter-discuss/2005-November/000553.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. 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/topics/pythonurl/ (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 aleax at mail.comcast.net Wed Nov 9 22:00:16 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 9 Nov 2005 19:00:16 -0800 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> Message-ID: <1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Norman Silverstone wrote: ... > challenging. What I am thinking about at the moment is how to program for > the computer to guess the number which I select. I know it can be done but > I suspect it requires an approach which I have not yet learnt. I would > welcome suggestions on the best way to approach this problem. I assume the way the computer is going to guess is by trying some number, and you respond either that it's guessed right, or to go lower, or to go higher. In that case, think of "bisection". Originally, all the computer knows is that the number is in some range, say 0 to 100. It can then guess the midpoint, 50. If it's right, yay! Otherwise: if it's told to go lower, then the range is now 0 to 49 -- if higher, it's 51 to 100; in each case the range was just halved (actually, a bit more than halved). It does not take many halvings to squeeze even a pretty large original range down to a range which only includes one possible number... that's because "2 to the power of N" grows VERY fast with N, as the old story about the inventor of chess shows (the king told him to ask for a reward, and all he wanted was some rice -- one grain on the first cell of the chessboard, two on the next, then four, eight... all the way through the 64 squares of the board; the kind thought the inventor was being very moderate in his request, and granted it... to soon find out that not enough rice existed in the world to satisfy the request...;-). Well, repeated halving is just like repeated doubling "backwards", so it squeezes vast ranges of possibilities down to tiny ones just as fast as repeated doubling produces oceans of rice from a small chessboard;-). Alex From jd at something.com Fri Nov 11 04:36:42 2005 From: jd at something.com (JD) Date: Fri, 11 Nov 2005 09:36:42 -0000 Subject: output buffering Message-ID: Hello, When reading a large datafile, I want to print a '.' to show the progress. This fails, I get the series of '.'s after the data has been read. Is there a trick to fix this? Thanks From steve at holdenweb.com Thu Nov 10 01:51:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 10 Nov 2005 06:51:19 +0000 Subject: How to set program name in Python? ($0 in Perl) In-Reply-To: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> References: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> Message-ID: Swaroop C H wrote: > Hi, > > Is there a way to set the program name in Python, similar to $0 in > Perl? > >>From `man perlvar`: > > $0 Contains the name of the program being executed. On some oper- > ating systems assigning to "$0" modifies the argument > area that > the ps program sees. This is more useful as a way of > indicat- > ing the current program state than it is for hiding the > program > you're running. (Mnemonic: same as sh and ksh.) > > > > Thanks! > Swaroop > www.swaroopch.info > import sys print sys.argv[0] 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 rurpy at yahoo.com Thu Nov 24 15:14:33 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 24 Nov 2005 12:14:33 -0800 Subject: Python as Guido Intended In-Reply-To: <86k6ey25y2.fsf@bhuda.mired.org> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> Message-ID: <1132863273.378601.323870@f14g2000cwb.googlegroups.com> "Mike Meyer" writes: > rurpy at yahoo.com writes: > > Different programming styles are appropriate for different > > tasks, different times and different places, different people. > > And like morality, government, or economics, I do not believe > > that one style of programming fits all situations. > > If I read you right, what you're saying is that hammmers aren't good > at driving screws. I don't think anyone would argue about that. No, the analogy is more like this. Python is hammer that comes in green or blue. The hammer's developers say (perhaps with some reason) that cool colors like green and blue are the best colors because they promote calm when used. Calm hammerers are more productive and less violent. My work is repairing the inside of dark water tanks. It is hard to see blue and green hammers, and to find them if I put them down. I suggest that Python have the option of red hammers. The Python people respond with horror, pointing out the problems with red hammers. I say that I am a calm person already, that I know how to use red hammers safely, but of course the Python people don't want anything to do with the idea. "What will happen if your red hammer falls into the hands of a beginner?" they ask. (I note that although the hammer does have a lot of safety features, it is still easy to poke an eye out with the nail remover if one is not careful.) They also point out that adding a third color will cost time and effort. And the problems of deciding if the hammer should really be red, or maybe orange would be better. So they tell me to go use a red screwdriver. Regarding the differences between hammers and screwdrivers... When a screwdriver is appropriate I use a screwdriver. If I need to write code that does a large amount of CPU intensive number crunching, I use C, not Python. But suppose someone came up with a Python compiler. It would compile any Python program but there would be no speed benefit unless you carefully wrote the code to not use many of Python's dynamic features, so that either by type inferencing or programmer supplied static declarations, the compiler could generate efficient native machine code that executes at near C speeds. Obviously this would require changes (mostly additions?) to the Python language, though these changes would still allow today's style dynamic code to be written and run (though just as slow as today's runs). The payout would be that things written as C-extensions today, would be writable in (a restricted form of) Python. Would the Python orthodoxy favor such a development? Or would that be turning Python into a screwdriver? To me, it would be better because I can now do with a hammer, many of the things I used to do with a screw- driver. I can spend more time becoming a better hammerer, and less time learning the intricacies of screwdrivers. My life is better. > > This has the benefit of attracting more people to Python. > And why is this a benefit? More eyeballs to find bugs. More hands to make improvements. More minds to make suggestions. More hearts to share the joy. :-) From duncan.booth at invalid.invalid Wed Nov 30 04:36:53 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2005 09:36:53 GMT Subject: Why I need to declare import as global in function References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> <1133340177.628299.181340@g44g2000cwa.googlegroups.com> Message-ID: didier.doussaud at gmail.com wrote: > I think I understand my problem, but first the sample code extracted to > my project. > > Rq : it's an automatic run of unitary test, the names of unitary test > are parameter of main program "imported" file via the "execfile" > function (an usage of "import" instead may be a solution....) : > > file run.py : > ---------------- > > def run_ut( test ) : > # to have the problem the execfile MUST be in a function > execfile( test ) > run_ut( "ut_00.py" ) > > > file ut_00.py : > -------------------- > import math > > def f() : > ## global math # <-- just decomment this line to avoid error > print "Second access :" > print "\t",math.pi # ERROR > > print "First access :" > print "\t",math.pi # OK > f() > How interesting. Can anyone actually explain the behaviour here? Without the global statement everything works as I expect: the 'import math' is executed in the local scope of run_ut, so the function f() doesn't find it either in its local scope nor in global scope. Inserting 'global math' at the outer level in ut_00.py (e.g. before the 'import math') also works as I expect: math now becomes a global variable and is visible to f(). What I really don't understand is why the global statement *inside* f affects the scope of math outside f. If we had nested functions then a global variable in an inner function doesn't affect scope in outer functions. I realise that f() here isn't a nested function, but even so it looks to me like a bug unless I'm missing something. (Technically the program is invoking undefined behaviour as the language reference says that names listed in a global statement must not be defined in an import statement, but that isn't really relevant since you can replace the import with an assignment statement and get the same weird behaviour.) From apardon at forel.vub.ac.be Mon Nov 7 04:27:26 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 09:27:26 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <436c0527.146082265@news.oz.net> <864q6rkfie.fsf@bhuda.mired.org> <436d0b61.213212052@news.oz.net> <7xirv639kb.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-11-06, Steve Holden schreef : > Steven D'Aprano wrote: > [...] >> >> But I can't understand the position of folks who want inheritance but >> don't want the behaviour that Python currently exhibits. >> instance.attribute sometimes reading from the class attribute is a feature >> of inheritance; instance.attribute always writing to the instance is a >> feature of OOP; instance.attribute sometimes writing to the instance and >> sometimes writing to the class would be, in my opinion, not just a wart >> but a full-blown misfeature. >> >> I ask and I ask and I ask for some use of this proposed behaviour, and >> nobody is either willing or able to tell me where how or why it would be >> useful. What should I conclude from this? >> >> > > You should conclude that some readers of this group are happier > designing languages with theoretical purity completely disconnected from > users' needs. But of course we pragmatists know that practicality beats > purity :-) But explicit is better than implicit. -- Antoon Pardon From fredrik at pythonware.com Sat Nov 12 15:38:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Nov 2005 21:38:00 +0100 Subject: XUL behavior in Python via XPCOM, Mozilla References: <20051112142551.1cbe8641@samwise.anansi> Message-ID: Terry Hancock wrote: >I recently saw a claim that Mozilla XUL behaviors (normally > scripted in Javascript) can (or perhaps will) be scriptable > in Python. > > Also, "other languages such as Java or Python are supported > through XPCOM", said about Mozilla (from Luxor website). > > Yes, I know several ways to *generate* XUL from Python, and > at least one way to use XUL to create interfaces for Python > programs, but in this case, I'm talking about defining > button action behavior in XUL by calling Python scripts. > > I know that Javascript is the preferred language, but I've > seen several references to being able to do this in Python, > including a claim that a release was targeted for early > November (2005), to provide this. > > Now I can't find it again. Anyway, I was hoping someone > on c.l.p / python.org would have a reliable reference on > this. "mozilla xul python" + "I feel lucky" => http://weblogs.mozillazine.org/roadmap/archives/008865.html "Python for XUL will be available in the Mozilla 1.9 milestone time frame, when the DOM_AGNOSTIC_BRANCH is landed some time this calendar year for sure /.../ The next major Firefox release based on the 1.9 milestone (Firefox 1.5 is based on the Mozilla 1.8 milestone) will include Mark's work -- but not a C-Python en- vironment by default." also see http://www.mozilla.org/roadmap/gecko-1.9-roadmap.html#Python_for_XUL (which says the same thing) From mwm at mired.org Tue Nov 1 21:29:50 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 01 Nov 2005 21:29:50 -0500 Subject: Xah's edu corner: the Journey of Foreign Characters thru Internet References: <1130852975.525590.145080@f14g2000cwb.googlegroups.com> <1130874345.236356.248110@g14g2000cwa.googlegroups.com> <86d5lk15ai.fsf@bhuda.mired.org> Message-ID: <86d5ljzsrl.fsf@bhuda.mired.org> Peter Hansen writes: > Mike Meyer wrote: >> Xah Leh is incompetent, but >> apparently well-intentioned. > In your view is that ("well-intentioned") an established fact at this > point? I was still waiting for conclusive evidence. No, it's not an established fact, which is why I said "apparently". I think *he* thinks he is doing the world a favor by ignoring established netiquette in his postings. But he's clearly incompetent, and that's sufficient to explain his behavior. And there's a saying about malice and incompetence. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bonono at gmail.com Fri Nov 25 03:42:08 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 25 Nov 2005 00:42:08 -0800 Subject: Draw a triangle... In-Reply-To: References: <1132892375.761161.160630@o13g2000cwo.googlegroups.com> Message-ID: <1132908128.525652.245660@g47g2000cwa.googlegroups.com> Fredrik Lundh wrote: > The Eternal Squire wrote: > > > PyGame is your best bet for pure graphics. Simple shapes can be done > > in just a few statements. > > the same applies to Tkinter, of course. > > from Tkinter import * > > # set things up > c = Canvas(); c.pack() > > # draw stuff > c.create_polygon((0, 100, 50, 0, 100, 100), fill="red") > > # get things going > mainloop() > > at the "draw a triangle" level, the main difference is mostly that > Tkinter is a bit more likely to be installed on your machine... Out of curiousity : why not : c = Canvas() c.pack() From steven.bethard at gmail.com Thu Nov 17 13:42:44 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Nov 2005 11:42:44 -0700 Subject: Python Library Reference - question In-Reply-To: <1132217639.080443.144910@g44g2000cwa.googlegroups.com> References: <1132217639.080443.144910@g44g2000cwa.googlegroups.com> Message-ID: bobueland at yahoo.com wrote: > The "Python LIbrary Reference" at > http://docs.python.org/lib/contents.html seems to be an important > document. I have two questions > > Q1. How do you search inside "Python LibraryReference" ? Does it exist > in pdf or chm form? One other option. Go to google and use: site:docs.python.org inurl:lib That should work, though I haven't tested it thoroughly. STeVe From roy at panix.com Fri Nov 25 16:43:00 2005 From: roy at panix.com (Roy Smith) Date: Fri, 25 Nov 2005 16:43:00 -0500 Subject: Writing pins to the RS232 References: <1132953944.656557.31910@g14g2000cwa.googlegroups.com> Message-ID: In article <1132953944.656557.31910 at g14g2000cwa.googlegroups.com>, "jay.dow at gmail.com" wrote: > I want to write to the pins of an RS232 without using the serial > protocol. The use would be every pin could act to complete a circuit > in customized hardware. I could use python to communicate serially to > a BASIC stamp or a Javelin stamp and then use the stamp to set however > many pins as 0's or 1's but should it be that hard to do with python. > I've looked through how python does serial with the "serial" module but > it just uses Java's javax.comm libraries. Is there anyway to do very > low level device writing to COM ports? This really isn't a Python question -- it's a low-level hardware question. The short answer, however, is that it's almost certainly impossible to anything like what you want, for a number of reasons. The output pins on the connector are driven directly by some sort of serial hardware driver, and the hardware almost certainly doesn't expose an interface which lets you do what you're after. I think want you want to be doing is looking at using a parallel port (commonly called a printer port on PC's). But in any case, the answer to "How do I make the parallel port do this?" is a low-level hardware question, not a Python question. From bonono at gmail.com Tue Nov 22 18:22:44 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 15:22:44 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <43835bff.477651596@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: <1132701764.448464.98560@g14g2000cwa.googlegroups.com> Bengt Richter wrote: > On 22 Nov 2005 03:07:47 -0800, "bonono at gmail.com" wrote: > > > > >Bengt Richter wrote: > >> Ok, so if not in the standard library, what is the problem? Can't find what > >> you want with google and PyPI etc.? Or haven't really settled on what your > >> _requirements_ are? That seems to be the primary problem people who complain > >> with "why no sprollificator mode?" questions. They don't know what they really > >> mean when it comes down to a DYFR (Define Your Felicitous Requirements) challenge. > >> So DYFR ;-) > >Beat me. I am not the one asking the question. > Sorry, I thought you wanted an ordered dict too. I want/need(well I am told I don't need) to loop over a dict in certain order but I don't want or need a standard one as I don't think there is ONE implementation of it. My original post was a response to the question "why do one want ordered dict", in the tone of "there is no way one wants it". > > > > >> >> > parsing or not parsing is not the point, and parsing/converting is > >> >> > still "create a new view" of an existing data structure. > >> >> > >> So you'd like the mechanics to be automated and hidden? Then you need to > >> DYFR for using the black box you want. Methods, semantics. > >Lose you. don't know what you want to say. > > > I like solving problems. I just get frustrated when people don't focus on getting > the problem defined, which IME is 2/3 of the way to a solution. I don't mind, > in fact enjoy, rambling musings, but if someone seems actually to want a solution > for something, I like to try to realize it concretely. I tried to define the problem, and how I solve it(if it helps to convey the message), but was told you don't have the problem in the first place. From max at alcyone.com Sun Nov 13 16:17:18 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Nov 2005 13:17:18 -0800 Subject: Copyright [was Re: Python obfuscation] In-Reply-To: <868xvt147q.fsf@bhuda.mired.org> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <1131859100.890118.317030@g14g2000cwa.googlegroups.com> <868xvt147q.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Further, recent evidence is that this is no longer true in that > country, assuming it ever was. Oh, please. Take the political crap elsewhere. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis There is no fate that cannot be surmounted by scorn. -- Albert Camus From steve at holdenweb.com Sat Nov 5 11:21:39 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 05 Nov 2005 16:21:39 +0000 Subject: how to compile c-extensions under WinXP? In-Reply-To: References: Message-ID: Steve Holden wrote: > severa at sophia.dtp.fmph.uniba.sk wrote: > >>What should I do to be able to compile C-extensions (with python 2.4, >>winXP)? I get an error message, approximately "The .NET Framework SDK >>needs to be installed"; I tried to get something from the Microsoft web >>site, but maybe not the right version (or didn't set some variables), >>since the error remains. Could you please help me (it will need some >>patience with a computer newbie)? >> > > See > > http://www.vrplumber.com/programming/mstoolkit > > and say thanks to Mike Farmer. > That's Mike Fletcher [sorry, Mike]. 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 salvatore.didio at wanadoo.fr Thu Nov 17 14:51:01 2005 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 17 Nov 2005 11:51:01 -0800 Subject: os.spawnl error Message-ID: <1132257061.597353.70670@g43g2000cwa.googlegroups.com> Hello, Does someone already had ths problem ? >>> os.spawnl(os.P_NOWAIT,'c:\windows\notepad.exe') Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\os.py", line 565, in spawnl return spawnv(mode, file, args) OSError: [Errno 22] Invalid argument Regards Salvatore From bignose+hates-spam at benfinney.id.au Sat Nov 19 16:56:33 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Nov 2005 08:56:33 +1100 (EST) Subject: Immutable instances, constant values References: Message-ID: Steven D'Aprano wrote: > On Fri, 18 Nov 2005 14:32:46 +1100, Ben Finney wrote: > > Is there any difference between a Python immutable value, and a > > constant? I suppose "constant" also implies that the *name* binds > > unchangeably to a particular value. Is that meaningful? > > That's precisely how I understand "constant" to be useful. The Python docs don't really talk about such a thing. However, the None name cannot be re-bound. Is that all that's required to have a "constant" in Python? If so, it's part of the assignment statement, and not something the object itself can decide. True? > > How does one actually ensure an object is immutable? Is it a > > matter of overriding a bunch of methods, or is ther a neater way? Really hoping someone can come up with an answer for this. > > Is it bad style to make a user-defined class that creates > > immutable objects? Why? > > I can't see why it would be bad style. That's what FrozenSet does. "from foo import *" is supported in the language, but is still bad style. FrozenSet was *added* to the language (2.2), so that's evidence that Guido thinks it's a good idea. But I'd still like direct discussion: is making one's class instances immutable bad style? -- \ "Say what you will about the Ten Commandments, you must always | `\ come back to the pleasant fact that there are only ten of | _o__) them." -- Henry L. Mencken | Ben Finney From cyril.bazin at gmail.com Thu Nov 3 13:51:57 2005 From: cyril.bazin at gmail.com (Cyril Bazin) Date: Thu, 3 Nov 2005 19:51:57 +0100 Subject: Can Anyone Help me on this In-Reply-To: References: Message-ID: Here is an example of copying then reversing a list: >>> l1 = [1,2,"C"] >>> l2 = l1[:] >>> l2.reverse() >>> l2 ['C', 2, 1] From kent37 at tds.net Sun Nov 6 17:25:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 17:25:14 -0500 Subject: Pylab and pyserial plot in real time In-Reply-To: <1131278509.380060.281410@g44g2000cwa.googlegroups.com> References: <1131278509.380060.281410@g44g2000cwa.googlegroups.com> Message-ID: <436e806f$1_1@newspeer2.tds.net> googlinggoogler at hotmail.com wrote: > Hiya, > > I've got a PIC microcontroller reading me humidity data via rs232, this > is in ASCII format. I can view this data easily using hyperterminal or > pyserial and convert it to its value (relative humidty with ord(input)) > > But what im trying to do is plot the data in real time, ideally with > pylab - as it looks simple to use and simple is the way i want to go! > > My code is below, it doesnt show a graph, I was wondering whether > someone could suggest whats wrong? You have to call pylab.show() for the graph to be drawn. I don't know if it will work incrementally if you call show() in the loop. Kent > > thank you in advance > > David > > ######################################################################## > > import serial > from pylab import * > > ser = serial.Serial(0) > t = arange(0.0, 1.0+0.01, 0.01) > > xlabel('time') > ylabel('RH %') > title(' RH sensor data sampled at 1 sec intervals ') > #grid(true) > > x = 0 > > while 1: > s = ser.read() > b = ord(s) > h = [] > h.append(b) > x = x + 1 > plot(t,h) > > ser.close > > ######################################################################## > From fredrik at pythonware.com Wed Nov 9 12:12:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 18:12:58 +0100 Subject: PyFLTK - an underrated gem for GUI projects References: <3tenieFsgsmhU1@individual.net> Message-ID: Claudio Grondi wrote: > Running some of the test examples > (e.g. C:\Python24\pyfltk\test\doublebuffer.py) > I am getting an error I have never seen before: > > ============================================================== > TitleOfMessageBox: > Microsoft Visual C++ Runtime Library > > TheMessage: > Runtime Error! > > Program: C:\Python24\python.exe > > The application has requested the Runtime to terminate it in an unusual > way. > Please content the application's support team for more information. > ============================================================== afaik, that's the default behaviour for an explicit call to abort() on Windows. From deets at nospam.web.de Sat Nov 19 08:47:10 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 19 Nov 2005 14:47:10 +0100 Subject: Can you set a class instance's attributes to zero by setting the instance to zero? In-Reply-To: <1132406947.812243.274010@o13g2000cwo.googlegroups.com> References: <1132406947.812243.274010@o13g2000cwo.googlegroups.com> Message-ID: <3u8omrFvpptfU1@uni-berlin.de> Gerard Flanagan wrote: > Hello > > If I have the Vector class below, is there a means by which I can have > the following behaviour > > > >>>>A = Vector(1, 2) >>>>print A > > (1, 2) > >>>>A = 0 >>>>print A > > (0, 0) > > If there is such a means, will it still work with the __slots__ > attribution uncommented? No, you can't. The reason is that python doesn't have an assignment operator as e.g. C++ has. The "=" just binds the name A to some object - without the object knowing it. What's wrong with class A: def clear(): pass ... A.clear() ? Alternatively, you could try and abuse one of the seldom used in-place operator like __ior__: A |= 0 But I wouldn't recommend that. Regards, Diez From mwm at mired.org Wed Nov 23 23:27:50 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 23:27:50 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> <1132803762.570118.253770@o13g2000cwo.googlegroups.com> Message-ID: <86y83ezn3t.fsf@bhuda.mired.org> "bonono at gmail.com" writes: > Which is also my initial puzzle, items() and iteritems() already gives > you the tuples, why such gurantee or the others ? Doesn't that violate > the general idiom that if we can do certain thing in one way, there > better be one and only one way. Backwards compatability. The guarantee on the order of keys() and values() predates items() (and iteritems()). You can't remove the guarantee without potentially breaking old code, and that's Not Done - at least not to code that wasn't broken to begin with. Maybe dropping the guarantee should be considered for P3K, on the off chance that either keys or values could be made faster at some point in the future. But I don't see it as a big deal. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From nico-NoSp at m-tekNico.net Tue Nov 15 11:17:20 2005 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Tue, 15 Nov 2005 17:17:20 +0100 Subject: Default method arguments In-Reply-To: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> Message-ID: <437a0a1b_1@newsgate.x-privat.org> > I have little problem: > > class A: > def __init__(self, n): > self.data = n > def f(self, x = ????) > print x > > All I want is to make self.data the default argument for self.f(). (I > want to use 'A' class as following : > > myA = A(5) > myA.f() > > and get printed '5' as a result.) # use new-style classes, if there's no cogent reason to do otherwise class A(object): def __init__(self, n): self.data = n def f(self, x = None) # do NOT use "if not x" ! if x is None: print self.data else: print x -- Nicola Larosa - nico-NoSp at m-tekNico.net ...Linux security has been better than many rivals. However, even the best systems today are totally inadequate. Saying Linux is more secure than Windows isn't really addressing the bigger issue - neither is good enough. -- Alan Cox, September 2005 From mde at micah.elliott.name Mon Nov 28 12:01:41 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Mon, 28 Nov 2005 09:01:41 -0800 Subject: Extracting documentation for user relevant functions only? In-Reply-To: References: Message-ID: <20051128170141.GA2060@kitchen.client.attbi.com> On Nov 28, Anton81 wrote: > I've written a python script and added short docstrings. Now I'd > like to create a short overview of commands the user can use. > However I don't want the internal stuff that I also commented. Is > there a way to create a fancy documentation (e.g. pydoc) of certain > functions only? You can use the leading underscores convention to "hide" the intended invisible names. pydoc and epydoc both honor this... $ cat foo.py """Foo test mod. """ def spam(): "Like ham." pass def _secret(): "Can't see this docstring." pass class Mustard(object): __name1 = 1 _name2 = 2 name3 = 3 $ pydoc foo Help on module foo: NAME foo - Foo test mod. CLASSES ... class Mustard(__builtin__.object) ... | name3 = 3 FUNCTIONS spam() Like ham. -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From max at alcyone.com Tue Nov 15 19:15:50 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 15 Nov 2005 16:15:50 -0800 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <437a5980$0$18815$636a55ce@news.free.fr> Message-ID: <3tKdnek6kpqq5-fenZ2dnUVZ_sudnZ2d@speakeasy.net> Chris Mellon wrote: > I don't know about you, but I own the copyright to almost nothing that > I have written and been paid for, and further, none of has it's > copyright exploited to make money for the entity that does own the > copyright. But they wouldn't have paid you if you didn't (implicitly) transfer the copyright to them. So copyright is just as relevant whether it's a work for hire or not. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis You could have another fate / You could be in another place -- Anggun From smitty_one_each at bigfoot.com Fri Nov 11 03:37:19 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Fri, 11 Nov 2005 03:37:19 -0500 Subject: Needed class whose instances are many test cases References: <1131706265.113961.63370@f14g2000cwb.googlegroups.com> Message-ID: <87acgb60n4.fsf@bigfoot.com> >>>>> "Sumit" == Sumit writes: Sumit> I have scinario like I have to Create resource(in Sumit> __init__()) Before Running a set of testcases and then In Sumit> Testcases resources are going to used and then It will Sumit> cleared off after Running the testcases by destructor Sumit> __del__() import unittest import time Sumit> class app_adminfunc(unittest.TestCase): Sumit> def __init__(self, method = 'runTests'): Sumit> unittest.TestCase.__init__(self, method) Sumit> #------------Resource Creation -------- Sumit> def __del__(self): #--------------Resource Sumit> Deletion ----------------- Sumit> def test01----- def test02----- ....... .... Sumit> But in this above code Problem is that __init__() called at Sumit> each time when the Testcase is run ,But i want Single time Sumit> run of the Init Prior to run of each tests inside the class Sumit> . Can Anybody help me on this ? The unittest module runs a setUp and tearDown before each test case. If that is too high-frequency, why not just do something like class app_adminfunc(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def allYourTestCase(self): def test01(): pass def test02(): pass since python is so mellow about nesting functions and classes and such. HTH, Chris From samrobertsmith at gmail.com Sun Nov 20 18:36:41 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 15:36:41 -0800 Subject: How to draw a dash line in the Tkinter? In-Reply-To: References: <8c11e4350511171722r2edbf6bgc40c98fcfb1e57bc@mail.gmail.com> Message-ID: <1d987df30511201536r403797e1kbdd7e05d772ba11b@mail.gmail.com> On 11/20/05, Fredrik Lundh wrote: > Ben Bush wrote: > > > How to draw a dash line in the Tkinter? > > use the dash option. e.g. > > canvas.create_line(xy, fill="red", dash=(2, 4)) > canvas.create_line(xy, fill="red", dash=(6, 5, 2, 4)) > > (the tuple contains a number of line lengths; lengths at odd positions > are drawn, lengths at even positions are gaps. note that not all com- > binations are supported on all platforms; if Tkinter cannot find an exact > match, it will pick a the "closest possible"). > > where can I find the option settings for dash line? From claudio.grondi at freenet.de Tue Nov 22 03:30:04 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 22 Nov 2005 08:30:04 -0000 Subject: Any royal road to Bezier curves...? References: <3ufuvpF10ooqlU1@individual.net> Message-ID: <3ufvpuF10b2tfU1@individual.net> > http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm > has a Python example implementation of qubic Bezier curves available. Here my port to Tkinter (doesn't need PIL) from Tkinter import * master = Tk() objTkCanvas = Canvas(master, width=110, height=180) objTkCanvas.pack() def midpoint((x1, y1), (x2, y2)): return ((x1+x2)/2, (y1+y2)/2) MAX_LEVEL = 5 def drawCubicBezierCurveToCanvas(P1, P2, P3, P4, level=1): # global MAX_LEVEL # global objTkCanvas if level == MAX_LEVEL: objTkCanvas.create_line(P1[0],P1[1],P4[0],P4[1], fill='red', width=1.5) else: L1 = P1 L2 = midpoint(P1, P2) H = midpoint(P2, P3) R3 = midpoint(P3, P4) R4 = P4 L3 = midpoint(L2, H) R2 = midpoint(R3, H) L4 = midpoint(L3, R2) R1 = L4 drawCubicBezierCurveToCanvas(L1, L2, L3, L4, level+1) drawCubicBezierCurveToCanvas(R1, R2, R3, R4, level+1) #:if/else level == MAX_LEVEL #:def draw_curve(P1, P2, P3, P4, level=1) objTkCanvas.create_rectangle(10, 10, 100, 100, fill="yellow") objTkCanvas.create_line( 10, 20, 100, 20, fill="green") objTkCanvas.create_line( 10, 30, 100, 30, fill="green") objTkCanvas.create_line( 10, 40, 100, 40, fill="green") objTkCanvas.create_line( 10, 50, 100, 50, fill="green") objTkCanvas.create_line( 10, 60, 100, 60, fill="green") objTkCanvas.create_line( 10, 70, 100, 70, fill="green") objTkCanvas.create_line( 10, 80, 100, 80, fill="green") objTkCanvas.create_line( 10, 90, 100, 90, fill="green") objTkCanvas.create_line( 20, 10, 20, 100, fill="green") objTkCanvas.create_line( 30, 10, 30, 100, fill="green") objTkCanvas.create_line( 40, 10, 40, 100, fill="green") objTkCanvas.create_line( 50, 10, 50, 100, fill="green") objTkCanvas.create_line( 60, 10, 60, 100, fill="green") objTkCanvas.create_line( 70, 10, 70, 100, fill="green") objTkCanvas.create_line( 80, 10, 80, 100, fill="green") objTkCanvas.create_line( 90, 10, 90, 100, fill="green") drawCubicBezierCurveToCanvas((10,10),(100,100),(100,10),(100,100)) objTkCanvas.create_text( 10, 130, anchor='sw', text='Bezier curve:', font='Arial 10') objTkCanvas.create_text( 10, 140, anchor='sw', text=' P1=( 10, 10)', font='Courier 8') objTkCanvas.create_text( 10, 150, anchor='sw', text=' P2=(100,100)', font='Courier 8') objTkCanvas.create_text( 10, 160, anchor='sw', text=' P3=(100, 10)', font='Courier 8') objTkCanvas.create_text( 10, 170, anchor='sw', text=' P4=(100,100)', font='Courier 8') mainloop() # show the Tkinter window with the diagram of the cubic Bezier curve > http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm > > has a Python example implementation of qubic Bezier curves available. > > Claudio > > "Warren Francis" schrieb im Newsbeitrag > news:dlrin7$mtg$1 at charm.magnus.acs.ohio-state.edu... > > I'm fairly new to Python (2-3 months) and I'm trying to figure out a > simple > > way to implement Bezier curves... So far I've tried the following: > > > > http://runten.tripod.com/NURBS/ > > ...which won't work because the only compiled binaries are for Windows > 2000, > > python 2.1. I'm on Windows XP (for now), using Python 2.4. I downloaded > > the source distribution, but the header files aren't included, so I'm not > > sure how to compile it. > > > > It appears there's some bezier functionality in the python that comes > > Blender... but I'm not savvy enough yet to try and extract whatever makes > > beziers work there, to make it work in my general-purpose Python programs. > > > > Basically, I'd like to specify a curved path of an object through space. > 3D > > space would be wonderful, but I could jimmy-rig something if I could just > > get 2D... Are bezier curves really what I want after all? > > > > Any thoughts would be much appreciated. I've got some ideas I want to > test, > > but if I can't find a simple implementation of curves, I'm going to get so > > bogged down in trying to do that part, I'll never get to what I'm excited > > about. :-P > > > > Warren > > > > > > From rodney_garland at hotmail.com Sun Nov 27 01:53:16 2005 From: rodney_garland at hotmail.com (Rodney Garland) Date: Sat, 26 Nov 2005 22:53:16 -0800 Subject: SOAP - Beginner Desperately looking for Help References: <3uskfeF12hhjqU3@uni-berlin.de> <3uskjcF12hhjqU4@uni-berlin.de> Message-ID: <8qOdnZWxLdZ-yhTeRVn-sQ@comcast.com> Thanks :-) "Diez B. Roggisch" wrote in message news:3uskjcF12hhjqU4 at uni-berlin.de... >> I wanted to attach these - however, taht didn't work for NNTP, so I mail >> them to you. > > Didn't work - my mail server won't let me send these to you. So you're on > your own here. Shouldn't be too hard :) > > Diez From gmilas at gmail.com Tue Nov 15 16:31:25 2005 From: gmilas at gmail.com (gmilas at gmail.com) Date: 15 Nov 2005 13:31:25 -0800 Subject: Inheritance in nested classes In-Reply-To: <1132074525.214768.134850@g44g2000cwa.googlegroups.com> References: <3tuhcoFu85g8U1@uni-berlin.de> <1132074525.214768.134850@g44g2000cwa.googlegroups.com> Message-ID: <1132090285.843772.263710@g47g2000cwa.googlegroups.com> "I'm using the Active Server Pages integration in the win32 extensions, does anyone have good/bad experiences using this interface?" What is it you are trying to do? I'm using python2.4 with win32 and IIS/python ASP and find it ok. There were at some point some session overlappings but I'm not sure if it was the asp interface or my ajax code? Anyway I have someting you may find usefull in doing asp with python at http://www.emilas.com/pwh/ and this has an ORM that has an html form generator if I guess your intention of generating html using python. The generator there is not general but rather oriented towords databases tables and views. From usenet.20.evilspam at spamgourmet.com Tue Nov 8 22:00:13 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Wed, 09 Nov 2005 03:00:13 GMT Subject: SPE IDE for Python In-Reply-To: <1131457605.425734.54340@g44g2000cwa.googlegroups.com> References: <1131457605.425734.54340@g44g2000cwa.googlegroups.com> Message-ID: <1Ddcf.16783$Q27.1167@trnddc02> py wrote: > Anyone here use SPE (http://www.stani.be/python/spe/blog/). ...the IDE? > > Also, anyone know if it supports CVS or has a plugin for CVS? If not, > what do you use to get your code into CVS (via an IDE preferably)? I used to use SPE quite frequently, until it went nearly unmaintained for most of late last year. I switched to the PyDev plugin for Eclipse, which comes with standard support for CVS (there's also an SVN plugin). SPE development looks to be back in full swing, which in good, since it's one of the best pure Python IDEs around. Chris From fredrik at pythonware.com Sat Nov 26 10:42:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Nov 2005 16:42:47 +0100 Subject: Whitespace test after string.split References: Message-ID: Peter Otten wrote: >>>> [t.strip() for t in s.split(",") if t and not t.isspace()] > ['alpha', 'gamma', 'delta'] footnote: this solution is faster than my filter version. From onurb at xiludom.gro Tue Nov 29 14:37:43 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 29 Nov 2005 20:37:43 +0100 Subject: Web functions idea In-Reply-To: <438c9fae$0$15794$14726298@news.sunsite.dk> References: <438c9fae$0$15794$14726298@news.sunsite.dk> Message-ID: <438cae09$0$4342$626a54ce@news.free.fr> Mark Carter wrote: > I was musing recently about how one could, for example, set up a really > simple mailing subscription list. It occurred to me that a really simple > way to implement it would be to use xmlrpc. > So there could be a function > subscribe(emailAddress), > which would send an email for confirmation, and another function > confirm(emailAddress, password) > which would confirm the address ... and so on. > > Now, the problem is that, if you use xmlrpc, it requires some kind of > fiddly software that the client would have to install. What you would > really want is some kind of web interface instead of xmlrpc - a kind of > "web driven xmlrpc" (that would eliminate the need of an actual xmlrpc > server). Congratulations, you've just rediscovered REST !-) > The point of it being this: a developer would just write the functions > that he needed, a la xmlrpc, which would be "exposed" to this new module > (let's call it webrpc) - and webrpc would examine the function, work out > how many arguments it had, and display a form for the user to fill out. > From an application writer's point-of-view, it abstracts away the whole > web process, I'm afraid doing web developpement without a minimal knowledge of "the whole web process" is somewhat unrealistic. > leaving him free to just concentrate on the underlying > function implementation. Turbogears is probably what you're looking for (if not quite what you describe). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bobueland at yahoo.com Thu Nov 17 04:25:59 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 17 Nov 2005 01:25:59 -0800 Subject: newbie - How do I import automatically? References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> <3u0el9Fum367U1@individual.net> <1132154531.395649.168870@g14g2000cwa.googlegroups.com> Message-ID: <1132219559.826657.209940@f14g2000cwb.googlegroups.com> I tried to do it on my computer (win XP). I put an extra line in PyShell.py #! /usr/bin/env python import os import os.path import sys import string import getopt import re import socket import time import threading import traceback import types import exceptions # test sys.modules['__main__'].__dict__['os'] = os import linecache Then when I start idle I get IDLE 1.1.1 >>> dir() ['__builtins__', '__doc__', '__name__'] >>> So I don't see 'os' Do you see 'os' on your computer. If yes, what could be the difference? Bob From pmartin at snakecard.com Mon Nov 14 12:45:15 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Mon, 14 Nov 2005 11:45:15 -0600 Subject: SnakeCard products source code Message-ID: Dear all, The source code is available in the download section: www.snakecard.com Regards, Philippe From fredrik at pythonware.com Mon Nov 7 12:26:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 7 Nov 2005 18:26:58 +0100 Subject: RAW_INPUT References: <20051107155713.88147.qmail@web35913.mail.mud.yahoo.com> <1131387255.3171.1.camel@localhost.localdomain> Message-ID: "A D" wrote: >> print "You may pass,", s > > at this print line you need to do > print "you may pass, %s" % s > > this will allow you to enter the string s into the output sentence where did you buy your python license ? >>> s = "josh" >>> print "hello,", s hello, josh >>> print "hello, %s" % s hello, josh From mwm at mired.org Sat Nov 19 23:30:32 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 19 Nov 2005 23:30:32 -0500 Subject: Can a function access its own name? References: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> <1132430103.737707.82090@g47g2000cwa.googlegroups.com> Message-ID: <868xvkhrfb.fsf@bhuda.mired.org> bobueland at yahoo.com writes: > Thanks Diez and Peter, > Just what I was looking for. In "Library Reference" heading > 3.11.1 Types and members > Running this yields the result > > cap(s, n) You've now got three solutions. They'll work fine most of the time, but can't be trusted in general. Binding a name to a function doesn't change the name that these solutions return, and the name they return may no longer be bound to said function. Just a warning. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martin at v.loewis.de Sun Nov 27 02:46:59 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 27 Nov 2005 08:46:59 +0100 Subject: New docs for set elements/dictionary keys (Was: Why is dictionary.keys() a list and not a set?) In-Reply-To: <86mzjqew8l.fsf_-_@bhuda.mired.org> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> <863bljf1o8.fsf@bhuda.mired.org> <4388f6ce$0$22897$9b622d9e@news.freenet.de> <86mzjqew8l.fsf_-_@bhuda.mired.org> Message-ID: <43896474$0$22007$9b622d9e@news.freenet.de> Mike Meyer wrote: > Personally, I think we'd be better off to come up with a term for this > property that doesn't have a commonly understood meaning that has such > broad areas of disagreement with the property. I've been using > "hashable", which I would currently define as "has a __hash__ method > with the properties described in the __hash__ documentation, or does > not have either a __cmp__ or a __eq__ method." I would like to use "hashable" as a term as well, but it appears that many people would understand that to mean "has a __hash__ implementation" (i.e. hash(x) returns a value, instead of raising an exception). Regards, Martin From gdamjan at gmail.com Mon Nov 28 09:19:32 2005 From: gdamjan at gmail.com (Damjan) Date: Mon, 28 Nov 2005 15:19:32 +0100 Subject: Unicode in MIMEText References: Message-ID: patch submitted... > Thanks for taking the time to improve the quality of the Python library. Do you think it would be possible to do some kind of an automatic comprehensive test of compatibility of the standard library with unicode strings? -- damjan From andrea_gavana at tin.it Sat Nov 5 19:05:09 2005 From: andrea_gavana at tin.it (Andrea Gavana) Date: Sun, 6 Nov 2005 01:05:09 +0100 Subject: Calling Class' Child Methods Message-ID: <436bf7f2$0$6007$4fafbaef@reader4.news.tin.it> Hello NG, this may seem a stupid (or even impossible) question, but my knowlegde of Python is quite limited. I have basically a simple graphical user interface that contains a Panel, another panel (child of the main panel) and a custom widget (child of the main panel). Basically is something like (only some small code, is in wxPython but the question is more Python-related): class MainClass(wx.Panel): def __init__(self, *args, **kwds): wx.Panel.__init__(self, *args, **kwds) self.childpanel = wx.Panel(self, -1) self.customwidget = Custom(self, -1) layoutsizer = wx.BoxSizer(wx.VERTICAL) layoutsizer.Add(self.childpanel, 1) layoutsizer.Add(self.customwidget) layoutsizer.Layout() The class "Custom" has a lot of methods (functions), but the user won't call directly this class, he/she will call the MainClass class to construct the GUI app. However, all the methods that the user can call refer to the "Custom" class, not the MainClass class. That is, the methods that the user call should propagate to the "Custom" class. However, I know I can do: # Inside MainClass def SomeMethod(self, param): self.customwidget.SomeMethod(param) But the "Custom" class has *a lot* of methods, so I will end up in rewriting all the "SomeMethods" in the MainClass just to pass the parameters/settings to self.customwidget. Moreover, I know I can do (in the __init__ method of MainClass): def __init__(self, *args, **kwds): wx.Panel.__init__(self, *args, **kwds) Custom.__init__(self, parent, -1) In order to make MainClass knowing about the Custom methods. But the I will not be able (I suppose) to add self.customwidget to a layoutsizer. How can I write: layoutsizer = wx.BoxSizer(wx.VERTICAL) layoutsizer.Add(self.childpanel, 1) layoutsizer.Add(self) # <=== That's impossible layoutsizer.Layout() ? So (and I am very sorry for the long and maybe complex to understand post, english is not my mother tongue and I am still trying to figure out how to solve this problem), how can I let MainClass knowing about the Custom methods without rewriting all the Custom functions inside MainClass and then pass the parameters to Custom? Is there a way to "propagate" the methods to the child class (Custom)? Thanks for every suggestion, and sorry for the long post. Andrea. -- "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77 From bonono at gmail.com Thu Nov 24 07:52:26 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 04:52:26 -0800 Subject: wxPython Licence vs GPL In-Reply-To: References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> <86hda2zcli.fsf@bhuda.mired.org> <1132820796.119386.309160@o13g2000cwo.googlegroups.com> Message-ID: <1132836746.625340.17850@g49g2000cwa.googlegroups.com> Peter Hansen wrote: > Steven D'Aprano wrote: > > On Thu, 24 Nov 2005 00:26:36 -0800, bonono at gmail.com wrote: > >>As for the liability, that is for sure, withness what is happening for > >>the linux kernel. > > > > What is happening for the Linux kernel? > > The confidence of some of its (potential? gullible?) users in their > ability to use it without being sued is being eroded by crafty negative > marketing by Microsoft and others. > I meant the SCO saga, don't know if you are referring the same thing. From bokr at oz.net Wed Nov 30 17:41:26 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 30 Nov 2005 22:41:26 GMT Subject: Nested loop References: <1133339863.718152.140770@g43g2000cwa.googlegroups.com> Message-ID: <438e28c9.340577754@news.oz.net> On 30 Nov 2005 00:37:43 -0800, bonono at gmail.com wrote: > >viewcharts wrote: >> I am reading two text files comparing the values in one to the other, >> this requires two loops. The problem is that when the inner loop is >> finished, it never goes back into the loop. Any suggestions? >> >> >> for refSymbol in symbols.readlines(): >> for lookupSymbol in myfile.readlines(): >> showme = lookupSymbol.split('\t') >> if showme[3] == refSymbol.strip(): >> priceNew.write(refSymbol.strip()+" "+showme[10]) >As another poster said, you have "used up" the inner iterable in the >first round, it is an iterable, just not like a list where you can use >multiple times. > >Either turn it into a list(so you can reuse it) or better yet, turn it >into a dict which would speed up the matching process. Either way, it >better be done outside of the outer loop. > Yes, and unless there is an ordering requirement that can't be ignored or achieved by sorting afterwards, symbols seems like it could be a set. E.g., (untested) refSymbolSet = set(refSymbol.strip() for refSymbol in symbols) for showme in (lookupSymbol.split('\t') for lookupSymbol in myfile): if showme[3] in refSymbolSet: priceNew.write(showme[3]+" "+showme[10]) It would probably be more robust to check for blank lines and showme missing fields and symbol duplicates also. Regards, Bengt Richter From ondekoza at gmail.com Fri Nov 18 11:04:16 2005 From: ondekoza at gmail.com (ondekoza at gmail.com) Date: 18 Nov 2005 08:04:16 -0800 Subject: How to convert a "long in a string" to a "long"? Message-ID: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> Hello, I need to convert the string "FFFFFFFF" to a long. To convert this string I tried the following: >>> 0xffffffff -1 >>> 0xffffffffL 4294967295L OK, this is what I want, so I tried s = long("0xffffffffL") ValueError: invalid literal for long(): 0xffffffffL s = long("0xffffffff") ValueError: invalid literal for long(): 0xffffffffL What can I do? Thank you in advance. Stefan From steve at REMOVETHIScyber.com.au Thu Nov 3 10:47:10 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 02:47:10 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: On Thu, 03 Nov 2005 14:27:48 +0100, Sybren Stuvel wrote: > Antoon Pardon enlightened us with: >> I would expect a result consistent with the fact that both times b.a >> would refer to the same object. > > "b.a" is just a name, not a pointer to a spot in memory. Getting the > value associated with that name is something different from assigning > a new value to that name. You've got the right concept, but not the right terminology. The "b" before the dot is a name. The "a" after the dot is a name. But the whole thing together is not a name: b.a is an attribute reference. You wouldn't call b["a"] a name, and you shouldn't call b.a a name either. -- Steven. From deets at nospam.web.de Wed Nov 9 04:23:16 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Nov 2005 10:23:16 +0100 Subject: Is it a bug? In-Reply-To: References: Message-ID: <3tdtg5Fs7pfsU1@uni-berlin.de> Darren Cui Liang wrote: > Hi, there! > > Now I am working around with the "logging" module. Here is the code: > > > >>> import logging > >>> log1=logging.getLogger("a") > >>> log1.critical("msg") > No handlers could be found for logger "a" > >>> logging.critical("msg") > CRITICAL:root:msg > > Since every "logger" is under the "root logger", and if no handler is > found for the logger, the message will be passed to upper level loggers, > until the root, > then why do I get the msg: No handlers could be found for logger "a" The error-message is always for the used logger - but it will search the list of its parents for appropriate handlers. So setting a handler on a logger foo makes the logger foo.bar find it. Or, alternatively, obtain a reference tto the root-logger, and set your handler there. Then all loggers will find it. Diez From bokr at oz.net Thu Nov 24 06:18:12 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 24 Nov 2005 11:18:12 GMT Subject: strange behaviour when writing a large amount of data on stdout References: <7879o1t3acnq7dq9f60pspt6rhkpkbppsv@4ax.com> Message-ID: <43858e09.621533618@news.oz.net> On Wed, 23 Nov 2005 18:18:34 +0100, "Fredrik Lundh" wrote: >Manlio Perillo wrote: > >> >>>>> print data >> >> >> >> Traceback (most recent call last): >> >> File "xxx", line xxx, in ? >> >> print data >> >> IOError: [Errno 12] Not enough space >> > >> >errno 12 is ENOMEM (that is, the system did not have enough memory >> >to finish an operation). >> >> However I think the error message is not a good one. >> Better a "Not enough memory" > >the message text is provided by the operating system (or rather, by >the C library). I'm not sure rewriting error messages is a good thing... > >(if Python itself runs out of memory, it'll raise a MemoryError instead) > Maybe there's a bare except: somewhere blocking earlier & perhaps more informative messages? If windows has been running a long time (a few days or a week may be long ;-) it may get fragmented in some smallish memory arena reserved for special things (I forgot what versions, but I wouldn't be surprised if something still had s specialized limit). Does the program involve dynamic generation of desktop icons by any chance? Especially a lot of large true-color ones? I have some faint inkling of some correlation of that and memory problems with still huge amounts of heap memory available. Has the OP rebooted and just run the offending program alone? BTW, if the OP wants to find out how much memory is on the windows system, the amount of memory probably shows in the "about" window of the task manager (the NT task manager will give you a scrolling real-time graph of different kinds of memory usage as well). Also if the OP has windows word editor (probably winword.exe will start it from the console command line), the "about" dialog may have a "system info ..." button that will show memory and a lot more. What that button runs is C:\Program Files\Common Files\Microsoft Shared\MSInfo\MSINFO32.exe on my system. Since it's accessible from Word, I wouldn't think it would be too unsafe to run, but I guess the OP might not want to start diagnostic things on arbitrary devices etc., if that's accessible from his session. Regards, Bengt Richter From apardon at forel.vub.ac.be Wed Nov 30 05:57:04 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Nov 2005 10:57:04 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> <86fypkim4x.fsf@bhuda.mired.org> <861x10v4ks.fsf@bhuda.mired.org> <86psoj2w0c.fsf@bhuda.mired.org> Message-ID: On 2005-11-29, Mike Meyer wrote: > Antoon Pardon writes: >>> You see, you can make languages more powerful by *removing* things >>> from it. >> You cast this in way to general terms. The logic conclusion >> from this statements is that the most powerfull language >> is the empty language. > > The only way you reach that conclusion is if you read the statement as > saying that removing things *always* makes a langauge more > powerful. That's not what I said, I would say it is the common interpretation for such a sentence. > and that's as false as the belief > that adding things always makes a language more powerful. > >>> Wrong. There are some thing which there should *not* be a way to do. >>> For instance, there should not be a way to produce a segmentation >>> fault - which means certain features common to other languages will >>> never be added. >> Then C-extentions shouldn't be allowed. > > C-extensions aren't part of Python. As far as I understand, if you implement a class with a C-extension, then that class is understood to be part of Python. So if you think there should be no way to produce a segmentation fault in python you shouldn't allow such classes. >>> We don't talk much about how you produce buffer >>> overfows in Python, but people have asked for that as well. Adding >>> ways to write hard-to-read code is frowned upon. And so on. >> Do you mean people have asked for the possibility that a buffer >> overflow would overwrite other variables? > > Buffer overflows don't have to overwrite variables. They just asked > how you create buffer overflows in Python. I do wonder what they mean with a buffer overflow. Would the following classify: buf = range(10) buf[10] = 10 >>> I won't speak for others, but I wouldn't reject it out of hand. You >>> haven't provided enough information. Accepting it just because it adds >>> a way to do something is wrong. First, you have to ask whether or not >>> that something is something we want in Python at all. Then you >>> consider whether how the way proposed fits with the language: is it >>> ugly? >> That is a highly subjective question, answering it says more about >> the person then about the proposal. > > True. But whether or not a language is good is a highly subjective > question. Since the goal - keeping python good to the people who > already consider it good - is subjective, it's only natural that part > of the evaluation process be sujectie. > >>> Is it prone to abuse? >> I don't see why this is always brought up, given the number of >> features that can be abused in python. > > Just because Python isn't perfect is no reason to make it worse. Why is it worse. You seem to think that if one has a toolbox, which lacks a hammer, that the fact that the hammer can be abused makes your toolbox less usefull if you add a hammer to it. We have a toolbox, full of equipment that can be abused, yet that something else can be abused too, seems to be a mayor stumbling block for adding it. >>> In summary, the design philosophy is that it's better to do without >>> some facility than to add it in a way that doesn't fit with the >>> language, and the process reflects that. >> I don't mind that a proposal is worked on and that counter-proposals >> can be made. But some people just seem to counter any new proposal, >> while other are more interrested in searching for ways to make >> the new proposal fit the language. Now sometimes a proposal can't >> be fitted and gets rejected, so be it. But maybe more could be >> fitted in the langauge if more people were willing to look for >> ways to fit something, instead of rejecting it simply because >> the current proposal doesn't fit properly yet. > > The only way this would be good is if "more features" were inherently > better. That's simply not true. So the change in behavior you're > looking for isn't clearly good. No, this is good while there are still possible features that could make python a better language -- Antoon Pardon From avail4one at gmail.com Sun Nov 6 15:33:38 2005 From: avail4one at gmail.com (Waitman Gobble) Date: 6 Nov 2005 12:33:38 -0800 Subject: Validate string as UTF-8? In-Reply-To: <*firstname*nlsnews-835F79.13585206112005@news.verizon.net> References: <*firstname*nlsnews-835F79.13585206112005@news.verizon.net> Message-ID: <1131309218.391347.23300@f14g2000cwb.googlegroups.com> I have done this using a sytem call to the program "recode". Recode a file UTF-8 and do a diff on the original and recoded files. Not an elegant solution but did seem to function properly. Take care, Waitman Gobble From robert.kern at gmail.com Tue Nov 15 08:16:20 2005 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 15 Nov 2005 05:16:20 -0800 Subject: 3-dimensional plot in Python? In-Reply-To: References: <1131736814.721116.16890@g14g2000cwa.googlegroups.com> Message-ID: Frithiof Andreas Jensen wrote: > "questions?" wrote in message > news:1131736814.721116.16890 at g14g2000cwa.googlegroups.com... > >>I want to make a 3d plot. x is a vector(discrete), y is also a >>vector(discrete), for each pairwise x,y I have a value z(x,y)(it is not >>a function, just discrete values for each pair of x,y) >> >>I want to show them on a two dimensional plot by showing z(x,y) with >>colors. >> >>Thanks for any hint > > SciPy is your friend: Provides interfaces to several plot engines, including > gnuplot. Those interfaces are long since deprecated. Please use matplotlib instead. http://matplotlib.sf.net -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From p at ulmcnett.com Tue Nov 29 16:13:31 2005 From: p at ulmcnett.com (Paul McNett) Date: Tue, 29 Nov 2005 13:13:31 -0800 Subject: wxGrid and Focus Event In-Reply-To: <1133298277.358823.184670@f14g2000cwb.googlegroups.com> References: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> <438CACF1.1020909@ulmcnett.com> <1133294056.952406.108890@g44g2000cwa.googlegroups.com> <1133298277.358823.184670@f14g2000cwb.googlegroups.com> Message-ID: <438CC47B.1000503@ulmcnett.com> lux wrote: > TANKS!!! > Now it work!!! Not so fast. I've found out that I had to do the following ugly workaround to ensure it works in all cases: def _initEvents(self): ... if self.BaseClass.__name__ == "dGrid": ## Ugly workaround for grids not firing focus events from the keyboard ## correctly. self._lastGridFocusTimestamp = 0.0 self.GetGridCornerLabelWindow().Bind(wx.EVT_SET_FOCUS, self.__onWxGotFocus) self.GetGridColLabelWindow().Bind(wx.EVT_SET_FOCUS, self.__onWxGotFocus) self.GetGridRowLabelWindow().Bind(wx.EVT_SET_FOCUS, self.__onWxGotFocus) self.GetGridWindow().Bind(wx.EVT_SET_FOCUS, self.__onWxGotFocus) self.Bind(wx.EVT_SET_FOCUS, self.__onWxGotFocus) ... def __onWxGotFocus(self, evt): if self.BaseClass.__name__ == "dGrid": ## Continuation of ugly workaround for grid focus event. Only raise the ## Dabo event if we are reasonably sure it isn't a repeat. prev = self._lastGridFocusTimestamp now = self._lastGridFocusTimestamp = time.time() if now-prev < .05: return self.raiseEvent(dEvents.GotFocus, evt) -- Paul McNett http://paulmcnett.com http://dabodev.com From fredrik at pythonware.com Wed Nov 9 08:05:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 14:05:36 +0100 Subject: append to non-existing list References: <4371EFBC.1030502@sitasoftware.lu> Message-ID: Yves Glodt wrote: > if I do this: > > for row in sqlsth: > ________pkcolumns.append(row[0].strip()) > ________etc > > without a prior: > > pkcolumns = []; > > I get this error on first iteration: > UnboundLocalError: local variable 'pkcolums' referenced before assignment > > I guess that's normal as it's the way python works...?!? > > My question is: Is there no way to append to a non existing list? how do you expect Python to figure out what kind of empty object you want ? From hancock at anansispaceworks.com Sat Nov 12 18:03:39 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 12 Nov 2005 17:03:39 -0600 Subject: XUL behavior in Python via XPCOM, Mozilla In-Reply-To: <1131828478.149076.159200@g44g2000cwa.googlegroups.com> References: <1131828478.149076.159200@g44g2000cwa.googlegroups.com> Message-ID: <20051112170339.3362a4c5@samwise.anansi> On 12 Nov 2005 12:47:58 -0800 "Devan L" wrote: > Nufox? > http://trac.nunatak.com.au/projects/nufox Nufox is a server-side tool to *generate* XUL from Python. Luxor http://luxor-xul.sourceforge.net/ is a XUL-interpreter written in Python, which therefore *replaces* Mozilla for XUL-based GUI applications. It scripts in Python or Java by default. But then there's the announcement at http://weblogs.mozillazine.org/roadmap/archives/008865.html by Brenden Eich that will use the PyXPCOM work by Mark Hammond to put python scripting capability into the Mozilla XUL engine, so that you can use script="application/x-python" in order to do behavior scripting in Python from within XUL running on top of Mozilla. I was also a little foggy about the relationship between these components (which I hope I've just spelled out for the record). Thanks for the replies, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From peter at engcorp.com Wed Nov 30 17:57:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 30 Nov 2005 17:57:24 -0500 Subject: python speed In-Reply-To: References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133358884.407477.219560@g47g2000cwa.googlegroups.com> <438db382$0$67257$157c6196@dreader2.cybercity.dk> <1133368487.648595.50950@z14g2000cwz.googlegroups.com> <86sltdn6ma.fsf@bhuda.mired.org> Message-ID: Donn Cave wrote: > I read yesterday morning in the paper that the Goto Basic Linear > Algebra Subroutines, by a Mr. Kazushige Goto, are still the most > efficient library of functions for their purpose for use in > supercomputing applications. Apparently hand-optimized assembler > for specific processors. > http://seattlepi.nwsource.com/business/250070_goto29.html > (actually from the NY Times, apparently) "Goto No Longer Considered Harmful" ? ;-) From mwm at mired.org Thu Nov 17 13:33:00 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Nov 2005 13:33:00 -0500 Subject: How to write an API for a Python application? References: <437af434@news.bezeqint.net> <1132150685.389414.258170@z14g2000cwz.googlegroups.com> <86psp0nx1m.fsf@bhuda.mired.org> Message-ID: <86wtj7m8f7.fsf@bhuda.mired.org> "Eric Brunel" writes: > On Wed, 16 Nov 2005 15:43:33 -0500, Mike Meyer wrote: > >> "Eric Brunel" writes: >>> On 16 Nov 2005 06:18:05 -0800, Paul Boddie wrote: >>>> One technology that I used many years ago with Python, and which should >>>> still do the job is CORBA - at that time ILU, but I suppose the various >>>> other ORBs should also be as capable; certainly, ILU permitted >>>> callbacks from the server into the client. These days, you might want >>>> to look at omniORB, Fnorb and ORBit. >>> I never saw any way to create callbacks from server to client with CORBA. How would you describe such a callback in the IDL file? >> It's OO, not functional. You pass an object to the server, and the >> server invokes methods on that object. In the IDL, you use the >> interface name as a type. I.e.: >> >> interface Window { >> ... >> } >> and in another interface: >> WindowList FindWindows(in Window name) ; > > This is slowly drifting OT, but aren't the interfaces in the IDL implemented on the server, and not on the client? So passing an "interface instance" to a method will just make the server call itself, won't it? Or you have to turn your client into a server, which makes things a lot more complicated. Yes, your client turns into a server. That's pretty much required for callbacks to work, no matter what technology you use. While the details are a lot more complicated than being a simple client, you get to ignore a lot of them - like how clients find you - and a lot of the rest are taken care of by the ORB, which you have to have to be a CORBA client. What you pass isn't an "interface instance", it's a locator for an object that implements the interface. So you can pass an instance on the server if you really want to, but you can also pass one for the client. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From david at jotax.com Thu Nov 17 16:24:15 2005 From: david at jotax.com (David Poundall) Date: 17 Nov 2005 13:24:15 -0800 Subject: Stretching a bitmap Message-ID: <1132262655.753062.210080@g14g2000cwa.googlegroups.com> Is it possible to import a bitmap and stretch it to fit a defined area with wxPython? If so, could someone point me to any relevent web reference on the subject? Thanks in advance David From noway at sorry.com Thu Nov 24 02:52:10 2005 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 24 Nov 2005 07:52:10 GMT Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Note that this property of __slots__ is an implementation detail. You > can't rely on it working in the future. I don't "rely" on it. I just want to catch bugs in my code. > I'm curious as to why you care if people add attributes to your > "immutable" class. Personally, I consider that instances of types > don't let me add attributes to be a wart. To catch stupid bugs, typos and whatnot. If an instance is immutable, you can't modify it, period. If you do it, it's a bug. So why not have the bug raises an exception, rather than go unnoticed? I don't see your point, either. Why would you want to add attributes to an object documented to be immutable? -- Giovanni Bajo From mwm at mired.org Fri Nov 25 23:20:05 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 25 Nov 2005 23:20:05 -0500 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> Message-ID: <8664qgghvu.fsf@bhuda.mired.org> Steven D'Aprano writes: > "Hmmm, the class designer didn't want me adding attributes to instances... > maybe he had a good reason for that..." When it was suggested that a facility for doing this be added to the language, I asked for a use case for it. Nobodies come up with a reason for placing such restriction on the client yet. If you've got a use case, I'd be interested in hearing it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Mon Nov 21 07:21:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 21 Nov 2005 23:21:23 +1100 Subject: duplicate items in a list References: Message-ID: On Mon, 21 Nov 2005 02:49:56 -0800, Shi Mu wrote: > I used the following method to remove duplicate items in a list and > got confused by the error. > >>>> a > [[1, 2], [1, 2], [2, 3]] >>>> noDups=[ u for u in a if u not in locals()['_[1]'] ] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iterable argument required Confused by the error? I'm confused by your code!!! If you want to remove duplicate items in a list, try something like this: def remove_dups(L): """Removes duplicate items from list L in place.""" # Work backwards from the end of the list. for i in range(len(L)-1, -1, -1): # Check to see if the current item exists elsewhere in # the list, and if it does, delete it. if L[i] in L[:i]: del L[i] Instead of deleting duplicate items in place, we can create a new list containing just the unique items: def unique_items(L): """Returns a new list containing the unique items from L.""" U = [] for item in L: if item not in U: U.append(item) return U The trick you are trying to do with _ is undocumented and, even if you get it to work *now*, is probably not going to work in the future. Don't do it. -- Steven. From alanmk at hotmail.com Mon Nov 7 18:26:50 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 07 Nov 2005 23:26:50 +0000 Subject: Map of email origins to Python list In-Reply-To: References: <1131390365.721288.272070@g47g2000cwa.googlegroups.com> <1131396963.363256.12250@g47g2000cwa.googlegroups.com> <1131400439.260344.19880@g44g2000cwa.googlegroups.com> Message-ID: <8pRbf.18342$R5.1653@news.indigo.ie> [Claire McLister] > Thanks, Alan. You are absolutely right, we are not using the > NNTP-Posting-Host header for obtaining the IP address. Aha, that would explain the lack of precision in many cases. A lot of posters in this list/group go through NNTP (either with an NNTP client or through NNTP-aware services like Google Groups) which should give very good results, when available. > So, we'll have to go back and fix the script that is extracting the IP > address (which is written in Python, btw). What better language to write in :-) > Let me know if someone is > interested in taking a look at it and I can post it somewhere. Sure, please do make it available, or at least the geolocation component anyway. I'm sure you'll get lots of useful comments from the many clever and experienced folk who frequent this group. Don't be aggrieved at the negative comment you've received: I think what you're doing is fascinating. But don't forget that a lot of people are not aware that this kind of geolocation can be done, along with the many other inferences that can be drawn from message and browser headers. So don't be surprised if some of them try to "shoot the messenger". I look forward to the map with updated precision :-) -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From grante at visi.com Wed Nov 2 16:17:23 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 02 Nov 2005 21:17:23 -0000 Subject: Hexadecimal Conversion in Python References: <1130963306.183112.3720@g49g2000cwa.googlegroups.com> <1130963890.241985.268920@g14g2000cwa.googlegroups.com> <1130964825.322352.138330@f14g2000cwb.googlegroups.com> Message-ID: <11mib73t3275t32@corp.supernews.com> On 2005-11-02, DaBeef wrote: > I have been coding for 5 years. This is a proprietary protocol, so it > is difficult converting. Eh? What's so difficult about it? > I did this in java but was just able to convert a stream. Yet you seem unable to describe what it is you're trying to do. > I looked through the Python library, I am more or less getting > backa string represented as a "...." And what is it you _want_? If the other end sent you four ASCII "." bytes, shouldn't that be what you see? > So now I want to convert it to all the hexa, bin Sorry, I've no clue what "hexa, bin" is or how to convert to it. > until I see a match and can then work teh rest of my program I have absolutely no idea what you're trying to do, but maybe this will help: In Python a "string" is an array of 8-bit bytes. If you want the integer equivalent of the 3rd byte in a string s, do this: b = ord(s[2]) For example: >>> s = "ABC" >>> ord(s[0]) 65 >>> ord(s[1]) 66 >>> ord(s[2]) 67 If you want a list of the integer equivalents of the bytes in a string, do this: bl = [ord(c) for c in s] >>> [ord(c) for c in s] [65, 66, 67] -- Grant Edwards grante Yow! Make me look like at LINDA RONSTADT again!! visi.com From gregpinero at gmail.com Thu Nov 24 12:29:22 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 24 Nov 2005 12:29:22 -0500 Subject: Locking a file under Windows In-Reply-To: <9A28C052FF32734DACB0A288A3533991044D235B@vogbs009.gb.vo.local> References: <9A28C052FF32734DACB0A288A3533991044D235B@vogbs009.gb.vo.local> Message-ID: <312cfe2b0511240929h361397ecj68268352cc983f7b@mail.gmail.com> I'd be more worried about two users writing to the file at the same time. I don't have much experience in that area though so maybe someone could chime in on if that's a legitimate worry or not. -Greg On 11/24/05, Tim Golden wrote: > > [Guy Lateur] > > I'm working on an application that will be used by several users at > the same > > time. The user should be able to both read and write to some data file > > > stored on our file server. My question is: how can I prevent that one > user > > writes to the file while another user is reading it? > > Might be worth looking in the Python Cookbook area. I seem > to remember several recipes to do this kind of thing > cross-platform. eg, > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 > > Also the pywin32 docs come with a flock-style example. Hope > one of the two can help you. > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkpaladin79 at gmail.com Thu Nov 3 21:37:26 2005 From: darkpaladin79 at gmail.com (Ivan Shevanski) Date: Thu, 3 Nov 2005 21:37:26 -0500 Subject: putting an Icon in "My Computer" In-Reply-To: <17d4ae400511031835w58e245baufc5f2f1656b22d6@mail.gmail.com> References: <1131071030.209405.37800@z14g2000cwz.googlegroups.com> <1131071329.475037.289140@g47g2000cwa.googlegroups.com> <17d4ae400511031835w58e245baufc5f2f1656b22d6@mail.gmail.com> Message-ID: <17d4ae400511031837j464a42dau72033d12860e00e5@mail.gmail.com> On 11/3/05, Ivan Shevanski wrote: > > > > On 3 Nov 2005 18:28:49 -0800, Brett Hoerner > wrote: > > > > > I've been asked by my boss to put an Icon in WinXP's "My Computer" for > > > a utility we use around the shop. My tool of choice is of course > > > Python and therefore what I am using to attempt my given task. I have > > > no trouble putting Icons in the WinXP Toolbar using Python, but have > > > totally failed to get an Icon to appear in My Computer. Any Idea on > > > why and maybe how to get around this using Python? > > > > I'm pretty sure the My Computer menu is limited to devices and special > > Windows folders like My Documents, etc. I've never seen a program add > > an icon there, and I don't think its allowed through the API. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > If this can be achieved at all, it would be through the windows registry. > I know you can change all the icons for the recycle bin and special folders > through it. . .I would figure adding folders might even be under the same > key. Try google. > -Ivan > Actually, this link might just be what you need. http://www.winguides.com/registry/display.php/73/ Hope that helps, -Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrea_gavana at tin.it Sun Nov 6 13:48:25 2005 From: andrea_gavana at tin.it (Andrea Gavana) Date: Sun, 6 Nov 2005 19:48:25 +0100 Subject: ? MDI depreciated References: <1131294807.907281.58980@g47g2000cwa.googlegroups.com> Message-ID: <436e4ffb$0$1502$4fafbaef@reader2.news.tin.it> Hello Len, > Hate to ask this dum question (since I've been hiding under a rock). > But if the MDI UI model is/was depreciated. What is the new UI model. This much depends on which kind of application you have in mind. In my organization a lot of software that we use (basically for reservoir geology/engineering visualization) use the MDI model. They are not deprecated, in some case MDI is the best approach that one may take in order to create effective and easy-to-use applications. According to Micro$oft, the MDI model (in their opinion) is deprecated, but it should be noted that: "MDI was used a lot with versions of Windows prior to Windows 95. However, Microsoft researchers discovered that users found this split artificial and confusing. So from Windows 95, Microsoft announced that MDI would be deprecated and it should not be used for Windows applications ... well, Microsoft's story on MDI has never been consistent; legacy support has continued to be included with windows and the .NET Framework supports the MDI Approach in an excellent manner." you can find the whole thing here: http://www.akadia.com/services/dotnet_software_design.html For a while, M$ were preaching this as *the* way to do complex user interfaces, but they have backed away from it quite a lot. You can read something about it here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch10g.asp If you want to read about pros/cons of MDI approach, go to the bottom of the page. Some of modern applications have moved away from MDI in favour of different other approaches: - SDI (Single Document Interface); - Notebook Style - Splitter Windows/Sash Windows with multiple panels - Docking Windows The approach you will take, much depends on the type of application you have in mind. I usually prefer the Notebook approach, but this is just a personal style. HTH. Andrea. -- "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77 From steven.bethard at gmail.com Mon Nov 28 11:49:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 28 Nov 2005 09:49:17 -0700 Subject: Death to tuples! In-Reply-To: <1133163207.641767.210610@o13g2000cwo.googlegroups.com> References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> Message-ID: Dan Bishop wrote: > Mike Meyer wrote: > >>Is there any place in the language that still requires tuples instead >>of sequences, except for use as dictionary keys? > > The % operator for strings. And in argument lists. > > def __setitem__(self, (row, column), value): > ... Interesting that both of these two things[1][2] have recently been suggested as candidates for removal in Python 3.0. [1]http://www.python.org/dev/summary/2005-09-01_2005-09-15.html#string-formatting-in-python-3-0 [2]http://www.python.org/dev/summary/2005-09-16_2005-09-30.html#removing-nested-function-parameters STeVe From gsakkis at rutgers.edu Tue Nov 22 10:42:31 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 22 Nov 2005 07:42:31 -0800 Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <438301ef$0$29180$8fcfb975@news.wanadoo.fr> Message-ID: <1132674151.370320.100130@g44g2000cwa.googlegroups.com> "Laurent Rahuel" wrote: > Hi, > > newList = zip(aList[::2], aList[1::2]) > newList > [('a', 1), ('b', 2), ('c', 3)] > > Regards, > > Laurent Or if aList can get very large and/or the conversion has to be performed many times: from itertools import islice newList = zip(islice(aList,0,None,2), islice(aList,1,None,2)) George From bignose+hates-spam at benfinney.id.au Fri Nov 18 19:10:42 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 19 Nov 2005 11:10:42 +1100 (EST) Subject: Behaviour of enumerated types References: <437d6711.87269326@news.oz.net> <437e3cb3.141959727@news.oz.net> Message-ID: Bengt Richter wrote: > Ben Finney wrote: > >Getting a numeric index might be useful in a language such as > >Pascal, with no built-in dict or sequence types. In Python, where > >any immutable object can be a dict key, and any sequence can be > >iterated, it seems of no use. > > Does your concept of enumeration not have a fixed order of a set of > names? It does. The values are iterable in the same order they were specified when creating the Enum. > If it does, what is more natural than using their index values as > keys to other ordered info? I don't see why. If you want sequence numbers, use enumerate(). If not, the enum object itself can be used directly as an iterable. > OTOH, the index values (and hence my enums) are[1] not very good as > unique dict keys, since they compare[2] promiscuously with each > other and other number types. Indeed, that's why (in my design) the values from the enum are only useful for comparing with each other. This, to me, seems to be the purpose of an enumerated type. > To me the int correspondence is as expectable and natural as > a,b,c=range(3) (at least as a default) though I think different > enumerations should be different types. That's a complete contradiction, then. If you want them to be different types, you don't want them to be integers. > Note that the ordering of int values makes the instances nicely > sortable too, e.g., That only means the enum values need to compare in the same sequence; it doesn't mean they need to correspond to integer values. > But bottom line, I really thing the int base type is more than an > implementation detail. I think it's natural for an _ordered_ set of > names ;-) I think I've addressed all your current concerns; I don't believe an inherent correlation to integers is necessary at all. It's no more necessary than saying that ["a", "b", "c"] requires that there be some specific correlation between the values of that list and the integers 0, 1, 2. If you *want* such a correlation, in some particular case, use enumerate() to get it; but there's nothing about the values themselves that requires that correspondence. > I'll go look at PyPI now ;-) Feedback appreciated :-) -- \ "Oh, I realize it's a penny here and a penny there, but look at | `\ me: I've worked myself up from nothing to a state of extreme | _o__) poverty." -- Groucho Marx | Ben Finney From svenn.are at bjerkem.de Tue Nov 1 14:55:49 2005 From: svenn.are at bjerkem.de (svenn.are at bjerkem.de) Date: 1 Nov 2005 11:55:49 -0800 Subject: Using graphviz to visualize trace.py output, anybody? In-Reply-To: References: <1130710534.618559.40680@g43g2000cwa.googlegroups.com> Message-ID: <1130874949.408641.288070@g49g2000cwa.googlegroups.com> I was originally thinking of piping the output of trace.py into a text file and then have python massage that text file into a dot file for graphviz to visualize. Some formatting is possible with graphviz, but I would expect the graph to be very dependent on how the program under test runs so I have little idea what to expect. I think a counter would be needed to show the progress of the execution of the program as some parts of code are visited at intervalls. -- Svenn From fredrik at pythonware.com Thu Nov 10 18:49:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 00:49:35 +0100 Subject: thread variable scope with start_new_thread References: <1131665433.616558.105670@f14g2000cwb.googlegroups.com> Message-ID: "Luxore" wrote: > I am trying to create threaded python project and I'm running into some > weird Python variable scoping. the "weird scoping" you're seeing has nothing to do with threads (read on) > I am using the "thread" module (I know, it's old and I should be using > threading)... but for example: > > > import thread > def extract_archive(session, user, archive, dest=None): > job_id = sunlib.job.new(...) > def thread_extract_archive(): > if not os.path.exists(archive): > <...do stuff...> > if not os.path.isfile(archive): > <...do stuff...> > if dest == None: > dest = os.path.dirname(archive) > <...do more stuff...> > thread.start_new_thread(thread_extract_archive, ()) > return job_id > > > It appears that thread_extract_archive() inherits many of the variables > that are passed or defined in extract_archive(). I find this scary, > although very convenient because my thread process needs to reference a > number of items. The problem popped up when I added the "if dest == > None" bit. Python barks that "dest" is an uninitialized variable. > That would make sense to me, but what I find odd is that > thread_extract_archive() does not have any trouble accessing the > session, user, or archive variables. The only difference is that I > pass these variables to other functions (e.g. os.path.isfile), and I am > doing a simple pythonic test on "dest." no, the difference is that you're assigning to "dest" in the inner function. anything you assign to is considered to be a local variable: http://docs.python.org/ref/naming.html If a name is bound in a block, it is a local variable of that block. If a name is bound at the module level, it is a global variable. /.../ If a variable is used in a code block but not defined there, it is a free variable. for more on nested scopes, read the above page carefully, and, if you want even more details, this page: http://www.python.org/peps/pep-0227.html From ed at leafe.com Wed Nov 30 16:37:09 2005 From: ed at leafe.com (Ed Leafe) Date: Wed, 30 Nov 2005 16:37:09 -0500 Subject: ANN: Dabo 0.5 released! Message-ID: We are pleased to announce Dabo 0.5, the fifth major release of our data application framework. The Dabo framework is a true 3-tier design, with data access and UI code separated from your business logic. And since it's Python, and uses wxPython for its UI, it is completely cross-platform, having been tested on Linux, Windows and OS X. Download from http://dabodev.com/download Anyone interested in contributing to Dabo, or who just want to find out what it is all about is encouraged to join our mailing lists: dabo-users: for those interested in learning how to work with Dabo to create applications, and for general help with Dabo. http://leafe.com/ mailman/listinfo/dabo-users dabo-dev: for those interested in the ongoing development of Dabo. This list contains lots of lively discussion on design issues, as well as notices of all commits to the code repository. http://leafe.com/mailman/listinfo/dabo-dev Here is a brief summary of what's new/changed in Dabo 0.5: Dabo Framework: ---------------- Added a new class, DataSet, which lets you issue SQL queries against local Dabo data, not just against the backend. You can query, sort, and update individual DataSets, and even join multiple DataSets - all without making a call to the backend database server. Began the work of making an embedded, internal, database engine (SQLite). Currently SQLite is an option; starting with future releases, it will be an integral part of Dabo. Automatic binding of events to method code! If you have a button class with an onHit method, it will automatically be bound to the button's Hit event. Simply by naming your methods 'onBleh()', if there is a 'Bleh' event that is raised by the object, the onBleh() method will be bound to it. You can still bind manually using bindEvent(), of course, but auto-binding of events now works so well that it is the default. Added a basic framework for drawing shapes on any window. Once created, the shapes are accessible with an object reference. This should make dealing with wx.DC's a thing of the past for most uses. Way cool! Sorted out MDI/SDI issues. By default, dForm on Windows MDI children and dFormMain on Windows will be MDI parents. On other platforms, both dForm and dFormMain will be SDI by default. The above statement is true for datanav applications (ones generated by the AppWizard). The pure-Dabo default is for SDI forms. In any case, you may change this by setting dabo.MDI. Improved the datanav Quick Report feature, which can print a list of the current records, mimicing the browse page, or a whole page of information on one record, mimicing the edit page. Added the ability for the user to save the generated report form for editing with the Report Designer or editing the rfxml directly. Improved showContextMenu(), and sorted out the difference between MouseRightClick and ContextMenu events. dCheckBox now supports 3 state mode, (True, False and None). dForms now know how to read in cdxml files, created by the upcoming UI Designer. Improved the handling of broken database connections. Added middle button and scroll mouse events. Added some hooks to datanav.Form that allow developers to control the select options for given fields. This would allow you to put, for example, a radiogroup with a few choices instead of the default textbox. Added connection manager to dApp, which maintains a set of open database connections that your forms can reference by name. Added Connection property to dForm. Improved report writer's paragraph handling. And, of course, more bug fixes than we'd like to say! Dabo Demo: ------------ Added several small programs to the tutorial section. Instead of emphasizing actual complex, working apps in Dabo, such as the games, these show smaller, bite-sized examples of Dabo code. Began work on a demo app that mirrors the wxPython demo, which includes all of the controls, some sample code for each along with a brief explanation of how that control is used. This is the work of Adi J. Sieker, who has already added several Dabo controls, and who will be adding more as time goes on. The Bubblet game has been completely re-written to use the new Draw objects. This is an excellent way to learn how to control images drawn on your UI surfaces. Dabo IDE: --------- The AppWizard has been overhauled significantly, and now creates apps that are much more easily customized, and scales much better to non- trivial applications. The Class Designer has improved greatly - it now supports extremely complex layouts, such as multiply-nested sizers, paged controls inside other paged controls, etc. It can save these designs into XML files that can then be used to create runtime forms that have the same structure as the original design. The next step will be added soon: integration of code to bind to events, so that not only will you be able to control how your forms look, but also how they behave. The Report Designer continues to improve: it now has an integrated Property Sheet for altering the appearance of objects, as well as improved layering. It also supports full 2-way editing: both visual and XML editing changes are reflected in the other. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From mensanator at aol.com Wed Nov 30 18:37:23 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 30 Nov 2005 15:37:23 -0800 Subject: python speed In-Reply-To: <1133390257.578054.218620@g47g2000cwa.googlegroups.com> References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133383306.218266.123210@f14g2000cwb.googlegroups.com> <1133390257.578054.218620@g47g2000cwa.googlegroups.com> Message-ID: <1133393843.248185.33410@g47g2000cwa.googlegroups.com> Isaac Gouy wrote: > Peter Hansen wrote: > > Isaac Gouy wrote: > > > Peter Hansen wrote: > > >>Judging by the other posts in this thread, the gauntlet is down: Python > > >>is faster than Java. Let those who believe otherwise prove their point > > >>with facts, and without artificially handcuffing their opponents with > > >>non-real-world "purity" requirements. > > > > > That form of argument is listed as one of the principal forms of > > > illogical thinking in "Being Logical" D.Q.McInerny - "An Inability to > > > Disprove Does Not Prove" > > > > Good thing this is the form of argument *against* which I was arguing, > > rather than that which I choose to use myself. (Read very carefully, if > > you really think I was saying otherwise, and point out exactly where I > > made any such claims for my own part. In fact, I was referencing the > > arguments of others -- who *were* supporting their arguments with facts, > > as near as I can tell -- and I was calling on the opposition to do the > > same, and without changing the rules mid-discussion.) > > > > > "The fact that there is no concrete proof against a position does not > > > constitute an argument in favour of the position. I cannot claim to be > > > right simply because you can't prove me to be wrong." > > > > Isn't that what I was saying? That those who claim Python isn't faster > > were not supporting their arguments with actual facts? > > > > -Peter > > *Python is faster than Java. Let those who believe otherwise prove > their point with facts* > > We must be looking at different threads :-) > > afaict the only posting that provided something like "facts" was > http://groups.google.com/group/comp.lang.python/msg/309e439697279060 > > Which stated "Python is doing the heavy lifting with GMPY which is a > compiled C program with a Python wrapper" - but didn't seem to compare > that to GMPY with a Java wrapper? Is there such an animal? I only know about Java's BigInteger. And if there is, it just proves my point that benchmarks are worthless. From peter at engcorp.com Thu Nov 24 07:48:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Nov 2005 07:48:13 -0500 Subject: wxPython Licence vs GPL In-Reply-To: References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> <86hda2zcli.fsf@bhuda.mired.org> <1132820796.119386.309160@o13g2000cwo.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Thu, 24 Nov 2005 00:26:36 -0800, bonono at gmail.com wrote: >>As for the liability, that is for sure, withness what is happening for >>the linux kernel. > > What is happening for the Linux kernel? The confidence of some of its (potential? gullible?) users in their ability to use it without being sued is being eroded by crafty negative marketing by Microsoft and others. -Peter From bonono at gmail.com Fri Nov 25 03:15:21 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 25 Nov 2005 00:15:21 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> <1132803762.570118.253770@o13g2000cwo.googlegroups.com> <1132806307.326654.12130@g14g2000cwa.googlegroups.com> Message-ID: <1132906520.989879.211120@g49g2000cwa.googlegroups.com> Duncan Booth wrote: > bonono at gmail.com wrote: > > > As for the (k,v) vs (v,k), I still don't think it is a good example. I > > can always use index to access the tuple elements and most other > > functions expect the first element to be the key. For example : > > > > a=d.items() > > do something about a > > b = dict(a) > > > > But using the imaginary example : > > > > a = zip(d.values(), d.keys()) > > do something about a > > b = dict(a) # probably not what I want. > > > > The typical use case for the (v,k) tuple would be when you want sort the > contents of a dictionary by value. e.g. counting the number of occurrences > of each word in a document. > > a = zip(d.values(), d.keys()) > a.sort() > a.reverse() > print "Today's top 10:" > print str.join(',', [ k for (v,k) in a[:10]]) > > Ok, so today you can do that another way, but before there was a key > parameter to sort you had to build the tuple somehow: > > print str.join(',', sorted(a.iterkeys(), > key=a.__getitem__, reverse=True)[:10]) > > and the advantage of the latter is of course that it works even when you've > been counting the number of occurences of complex numbers in a document :) Thanks, so for newer python(2.3+?, don't know when the sort has been enhanced), this (v,k) is again there for historical reason but not a real use case any more. From robert.kern at gmail.com Tue Nov 15 14:43:54 2005 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 15 Nov 2005 11:43:54 -0800 Subject: is parameter an iterable? In-Reply-To: <1132082783.353359.69900@g49g2000cwa.googlegroups.com> References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: py wrote: > Dan Sommers wrote: > >>Just do it. If one of foo's callers passes in a non-iterable, foo will >>raise an exception, and you'll catch it during testing > > That's exactly what I don't want. I don't want an exception, instead I > want to check to see if it's an iterable....if it is continue, if not > return an error code. Why return an error code? Just pass along the exception (i.e. do nothing special). Python's exception mechanism is far superior to error codes. Don't try to fight the language. > I can't catch it during testing since this is > going to be used by other people. Then *they'll* catch it during testing. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From godoy at ieee.org Mon Nov 7 20:23:20 2005 From: godoy at ieee.org (Jorge Godoy) Date: 07 Nov 2005 23:23:20 -0200 Subject: Newbie Alert: Help me store constants pythonically References: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> <436EDDA8.5020600@REMOVEMEcyber.com.au> <1131412583.285926.185740@g49g2000cwa.googlegroups.com> Message-ID: <87fyq8yltj.fsf@jupiter.g2ctech> "Brendan" writes: > seems risky. Also my config files have (a tiny bit of) nested > structure, such as: > > Model1( > numBumps = 1 > sizeOfBumps = 2 > transversePlanes = [ > Plane(type=3, z=4), > Plane(type=5, z=6), > Plane(type=3, z=8) > ] > ) > > which I'm not sure the .ini format can easily support. I could use > (key buzzword voice) XML, but I fear that might send me down the > 'overcomplicating things' path. Your suggestion has given me some new > places to search Google (configparser, python config files), so I'll > look around for better ideas. Take a look at pickle (specially cPickle) module for pickling and unpickling data directly from / to Python types. What you want can be mapped to dictionaries of lists of dictionaries. :-) -- Jorge Godoy From pmartin at snakecard.com Mon Nov 21 18:16:22 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Mon, 21 Nov 2005 17:16:22 -0600 Subject: Python install minimum requirements Message-ID: <0zsgf.12765$ih5.9671@dukeread11> Hi, I am attemtping to package Python in a "U3" install program for Windows. I got Python to compile/link and prior to adding the necessary code for the U3 SDK registration, I would like to know where I can find the actual list of files needed for a minimum installation (are DLLs and libs enough ?) Regards, Philippe From http Fri Nov 4 05:32:17 2005 From: http (Paul Rubin) Date: 04 Nov 2005 02:32:17 -0800 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <86irv8hg74.fsf@bhuda.mired.org> Message-ID: <7xy844d7pq.fsf@ruckus.brouhaha.com> Mike Meyer writes: > I've already argued that the kludges suggested to "solve" this problem > create worse problems than this. The most obvious solution is to permit (or even require) the programmer to list the instance variables as part of the class definition. Anything not in the list is not an instance variable, i.e. they don't get created dynamically. That's what most other languages I can think of do. Some Python users incorrectly think this is what __slots__ does, and try to use __slots__ that way. That they try to do that suggests that the approach makes some sense. From fredrik at pythonware.com Sun Nov 20 11:45:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 17:45:07 +0100 Subject: what happens when the file begin read is too big for all linestobe?read with "readlines()" References: <000001c5edd5$2a8e1a20$a100a8c0@reyesr2> Message-ID: Ross Reyes wrote: > Maybe I'm missing the obvious, but it does not seem to say what happens when > the input for readlines is too big. Or does it? readlines handles memory overflow in exactly the same way as any other operation: by raising a MemoryError exception: http://www.python.org/doc/current/lib/module-exceptions.html#l2h-296 > How does one tell exactly what the limitation is to the size of the > returned list of strings? you can't. it depends on how much memory you have, what your files look like (shorter lines means more string objects means more overhead), and how your operating system handles large processes. as soon as the operating system says that it cannot allocate more memory to the Python process, Python will abort the operation and raise an exception. if the operating system doesn't complain, neither will Python. From usenet at marduk.letterboxes.org Sun Nov 13 16:30:54 2005 From: usenet at marduk.letterboxes.org (marduk) Date: Sun, 13 Nov 2005 21:30:54 GMT Subject: strip not working on strings? In-Reply-To: <1131916607.467166.207550@g14g2000cwa.googlegroups.com> References: <1131916607.467166.207550@g14g2000cwa.googlegroups.com> Message-ID: <1131917453.24483.3.camel@blackwidow> On Sun, 2005-11-13 at 13:16 -0800, dan.j.weber at gmail.com wrote: > I'm using Python 2.3.5 and when I type the following in the interactive > prompt I see that strip() is not working as advertised: > > >>>s = 'p p:p' > >>>s.strip(' :') > 'p p:p' > > Is this just me or does it not work? I want to get rid of all ' ' and > ':' in the string. I've checked the doc and from what I can tell this > is what strip() is supposed to do. Thanks for any help. > According to my docs it says "Return a copy of the string with the leading and trailing characters removed." There are no leading or trailing spaces or colons in 'p p:p'. What your probably looking for is the .replace() method. -m From scott.daniels at acm.org Thu Nov 17 20:18:30 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 17 Nov 2005 17:18:30 -0800 Subject: running functions In-Reply-To: References: <1132179612.759373.130900@g43g2000cwa.googlegroups.com> Message-ID: <437d2a78@nntp0.pdx.net> Gorlon the Impossible wrote: > I have to agree with you there. Threading is working out great for me > so far. The multiprocess thing has just baffled me, but then again I'm > learning. Any tips or suggestions offered are appreciated... The reason multiprocess is easier is that you have enforced separation. Multiple processes / threads / whatever that share reads and writes into shared memory are rife with irreproducible bugs and untestable code. Processes must be explicit about their sharing (which is where the bugs occur), so those parts of the code cane be examined carefully. If you program threads with shared nothing and communication over Queues you are, in effect, using processes. If all you share is read-only memory, similarly, you are doing "easy" stuff and can get away with it. In all other cases you need to know things like "which operations are indivisible" and "what happens if I read part of this from before an update and the other after the update completes, ..... That is why threads that don't do trivial things are so scary. --Scott David Daniels scott.daniels at acm.org From eight02645999 at yahoo.com Fri Nov 4 04:01:50 2005 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 4 Nov 2005 01:01:50 -0800 Subject: help converting some perl code to python Message-ID: <1131094909.984993.32330@z14g2000cwz.googlegroups.com> hi i need help with converting a piece of perl code to python ..... my $start = '\[start\]'; my $file = '\[files\]'; my $end = '\[end\]'; .... while() #open a file { if ( /$start/ .. /$file/ ) { # if line match [start] till [files] do something with $_ } if (/$file/ .. /$end/ ) { do something with $_ } } The file looks something like: [start] ... [files] ... [end] the problem is the '..' operator in perl. Is there any equivalent in python? any suggestions ? thanks From http Mon Nov 28 16:21:58 2005 From: http (Paul Rubin) Date: 28 Nov 2005 13:21:58 -0800 Subject: FTP over TLS References: <1133208783.883436.262770@z14g2000cwz.googlegroups.com> Message-ID: <7xwtish3ih.fsf@ruckus.brouhaha.com> "adam" writes: > I'm not 100% sure whether this answers your problem, but I would ignore > getting a special TLS module and just concentrate on the ftp side of > the protocol. If your connection to your ftp server must be in TLS, you > could modify you socket module similar to how I have using this diff > (against 2.3.4) as inspiration. You could also use something like stunnel (www.stunnel.org) as an external tunnel to wrap TLS around the connection. From luca.bs at gmail.com Fri Nov 11 02:26:24 2005 From: luca.bs at gmail.com (LB) Date: 10 Nov 2005 23:26:24 -0800 Subject: ANN: P(x) 0.2 applet builder In-Reply-To: References: <86br0t6mtz.fsf@bhuda.mired.org><867jbg6zzq.fsf@bhuda.mired.org> Message-ID: <1131693984.044637.261480@g47g2000cwa.googlegroups.com> >it looks like LB has configured his browser to pass all gz files to some >ancient VRML plugin; see e.g. You are right! And now it's fixed. But till yesterday I did download of .gz file with no problems at all... Thanks, LB From twic at urchin.earth.li Tue Nov 22 20:52:59 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 23 Nov 2005 01:52:59 +0000 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: On Tue, 22 Nov 2005, Christoph Zwerschke wrote: > One implementation detail that I think needs further consideration is in > which way to expose the keys and to mix in list methods for ordered > dictionaries. > > In Foord/Larosa's odict, the keys are exposed as a public member which > also seems to be a bad idea ("If you alter the sequence list so that it > no longer reflects the contents of the dictionary, you have broken your > OrderedDict"). > > I think it would be probably the best to hide the keys list from the public, > but to provide list methods for reordering them (sorting, slicing etc.). I'm not too keen on this - there is conceptually a list here, even if it's one with unusual constraints, so there should be a list i can manipulate in code, and which should of course be bound by those constraints. I think the way to do it is to have a sequence property (which could be a managed attribute to prevent outright clobberation) which walks like a list, quacks like a list, but is in fact a mission-specific list subtype whose mutator methods zealously enforce the invariants guaranteeing the odict's integrity. I haven't actually tried to write such a beast, so i don't know if this is either of possible and straightforward. tom -- When I see a man on a bicycle I have hope for the human race. -- H. G. Wells From apardon at forel.vub.ac.be Mon Nov 28 08:38:27 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2005 13:38:27 GMT Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> Message-ID: Op 2005-11-27, Flavio schreef : > hi, > > I have an object defined with a number of hardcoded methods. > > Class soandso: > def __init__(self): > self.this = 0 > self.that = 1 > def meth1(self): > ... > def meth2(self): > ... > def custom(self): > pass > > I want to allow the user to write a python module that declares a > function so that myprogram can import it and attribute it to the custom > method of the soandso object. So far so good, that is an easy thing to > do in Python. > > import usermodule > a=soandso() > a.custom = usermodule.function > > But, what if the method had to access the self attributes (self.this > and self.that) of the soandso object? > > Can it be done? and if so, what is the most Pythonic way of doing it? You mean something like this: >>> class Foo: ... def __init__(self, v): ... self.value = v ... >>> def show(self): ... print self.value ... >>> import new >>> f = Foo(17) >>> f.show = new.instancemethod(show, f) >>> f.show() 17 -- Antoon Pardon From steve at REMOVETHIScyber.com.au Thu Nov 3 10:53:01 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 02:53:01 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> Message-ID: On Thu, 03 Nov 2005 13:35:35 +0000, Antoon Pardon wrote: > Suppose I have code like this: > > for i in xrange(1,11): > b.a = b.a + i > > Now the b.a on the right hand side refers to A.a the first time through > the loop but not the next times. I don't think it is sane that which > object is refered to depends on how many times you already went through > the loop. Well, then you must think this code is *completely* insane too: py> x = 0 py> for i in range(1, 5): ... x += i ... print id(x) ... 140838200 140840184 140843160 140847128 Look at that: the object which is referred to depends on how many times you've already been through the loop. How nuts is that? I guess that brings us back to making ints mutable. I can't wait until I can write 1 - 0 = 99 and still be correct! -- Steven. From inigoserna at terra.es Sat Nov 12 11:56:27 2005 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Sat, 12 Nov 2005 17:56:27 +0100 Subject: ANN: pynakotheka v1.0 Message-ID: <1131814587.26242.6.camel@inigo.katxi.org> Hello out there, I'm really pleased to announce the first public release of Pynakotheka. Pynakotheka is a simple GPL-licensed python script which generates static HTML photo albums to be added to web sites or to be burnt in CDs. It includes some templates and it's easy to create more. It depends on python, CheetahTemplate, EXIF and PIL. Read more and download it from: http://inigo.katxi.org/devel/pynakotheka or http://www.terra.es/personal7/inigoserna/pynakotheka Of course, all comments, suggestions etc. are welcome. Best regards, -- I?igo Serna Katxijasotzaileak -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Esta parte del mensaje est? firmada digitalmente URL: From robert.h.boyd at gmail.com Tue Nov 1 13:29:41 2005 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Tue, 1 Nov 2005 13:29:41 -0500 Subject: Python's website does a great disservice to the language In-Reply-To: References: Message-ID: On 11/1/05, CppNewB wrote: > > ... > First comment; "I hope the language is designed better than the site." The > site is readable, but is amateurish. If I had an ounce of design skills in > me, I would take a stab at it. > Does boss have a problem with java.sun.com as well? The main visual difference I see is Sun's pages have some gradients and rounded corners. The Python site is clean and to-the-point. I guess I could admin that the various Python logos look dated, but that's about it. Oh, and my browser is still not finished loading php.net in the time I wrote this. Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at atomfx.com Sun Nov 27 22:20:37 2005 From: john at atomfx.com (John Wheez) Date: Sun, 27 Nov 2005 19:20:37 -0800 Subject: How to make tkFileDialog GUI larger? Message-ID: <438A7785.9060205@atomfx.com> Hi all, I'm using teh tkFileDialog to let teh user select a directory. We have long names which make it difficult to view the directories. For some reason the GUI windows doesn;t expand on Windows like it does on OS X or Linux. Is there a method to make the widths of the tkFileDialog windows larger when using Windows XP? Thanks for any info. .JW From grante at visi.com Fri Nov 18 16:06:46 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 18 Nov 2005 21:06:46 -0000 Subject: Choose meaningful subjects for posts [was: Re: newb ?] References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> <86u0eaj5ed.fsf@bhuda.mired.org> <11nsbh2r64kb9ae@corp.supernews.com> <17278.14762.150392.942325@montanaro.dyndns.org> Message-ID: <11nsgj6250bne4e@corp.supernews.com> On 2005-11-18, Micah Elliott wrote: > On Nov 18, skip at pobox.com wrote: >> Grant> Obligatory aside: I'm completely baffled why anybody would choose >> Grant> the mailing list format over Usenet. I don't even read mailing >> Grant> lists via mailing lists. I recommend gmane.org's NNTP server for >> Grant> all your mailing list needs. >> >> For the same reason I don't like web forums as a means of >> communication. I would much rather operate in an >> interrupt-driven mode than have to remember to poll some >> external service to get my daily helping of information. > > Agreed! If I allowed news posts to interrupt me, I'd never get anything done. I limit e-mail to things that really do require fairly immediate attention. > I notice that a lot of people post here from google. Ick! Posting to usenet from google. Nasty. > I did it too before I discovered the mailing list, which I now > use because I haven't found a news reader that I like nearly > as much as mutt. There is an NNTP patch to allow you to use mutt to read Usenet via an NNTP server. Mutt users who don't do that seem to like slrn -- it has a very similar look and feel. One thing significant difference is slrn's scoring facilities: there's nothing similar in mutt. > It's quite nice to combine email and news into one. I actually prefer to keep them separate. for me, e-mail is for stuff that "needs attention", and news is more of a background thing that I glance through while waiting for a test to finish or a make to complete. > If you have any suggestions for console-based newsreaders, I'm > all ears. slrn is the definitive choice -- especially for a mutt user. :) > I have tried to setup "tin" in the past but the voluminosity > of its documentation made me give up. I used tin for a couple years back in the early 90's, but I find slrn much more efficient. -- Grant Edwards grante Yow! My pants just went to at high school in the Carlsbad visi.com Caverns!!! From istvan.albert at gmail.com Tue Nov 8 09:15:29 2005 From: istvan.albert at gmail.com (Istvan Albert) Date: 8 Nov 2005 06:15:29 -0800 Subject: PYTHON LOOSING FOR JAVA??????? In-Reply-To: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> Message-ID: <1131459329.264078.148240@g47g2000cwa.googlegroups.com> > PYTHON LOOSING FOR JAVA??????? Yes, Python is already looser than Java. From sigzero at gmail.com Thu Nov 10 10:56:49 2005 From: sigzero at gmail.com (Robert Hicks) Date: 10 Nov 2005 07:56:49 -0800 Subject: A Tcl/Tk programmer learns Python--any advice? In-Reply-To: References: <1131502967.138632.94840@g47g2000cwa.googlegroups.com> <1131552039.774736.298520@z14g2000cwz.googlegroups.com> Message-ID: <1131638209.485738.276940@z14g2000cwz.googlegroups.com> Why does there need to be OO "in the core"? That is one thing I have never understood. If you want OO, get a package that fits your style of OO and "package require" you are off and running. That probably isn't what you would be looking at Tcl for anyway. I agree about Tk and I am actually talking with someone about adding a wxTcl to the mix as well. I think wx is a much better toolkit. > It is all a question what you want to solve and how you want to solve > it. That is so true. Robert From __peter__ at web.de Sun Nov 6 05:03:18 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 06 Nov 2005 11:03:18 +0100 Subject: __new__ References: Message-ID: James Stroud wrote: > I'm running 2.3.4 > > I was reading the documentation for classes & types > http://www.python.org/2.2.3/descrintro.html > And stumbled on this paragraph: > > """ > __new__ must return an object. There's nothing that requires that it > return a new object that is an instance of its class argument, although > that is the convention. If you return an existing object, the constructor > call will still call its __init__ method. If you return an object of a > different class, its __init__ method will be called. > """ > > The quote implies that when I call carol, b.__init__ should be called. > However, this does not seem to be the case (see code below). What am I not > understanding? Shouldn't the interpreter call b.__init__ when b is > returned from carol.__new__? Here's what "Python in a Nutshell" (p84) says: """ Each new-style class has a static method named __new__. When you call C(*args, **kwds) to create a new instance of a new-style class C, Python invokes C.__new__(C, *args, **kwds). Python uses __new__'s return value x as the newly created instance. Then, Python calls C.__init__(x, *args, **kwds), but only when x is indeed an instance of C (otherwise, x's state is as __new__ had left it). Thus, for a new-style class C, the statement x=C(23) is equivlent to the following code: x = C.__new__(C, 23) if isinstance(x, C): C.__init__(x, 23) """ If the following code says what I think it does class A(object): def __init__(self): print "init A" def __new__(cls): return b class B(A): def __init__(self): print "init B" b = object.__new__(B) print "---" A() # prints 'init B' A.__init__(b) # prints 'init A' print "---" b = 42 A() # prints nothing the "Nutshell" example should be changed to x = C.__new__(C, 23) if isinstance(x, C): x.__init__(23) to comply with the current implementation (I used Python 2.4). Peter From bonono at gmail.com Fri Nov 25 04:32:31 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 25 Nov 2005 01:32:31 -0800 Subject: Making immutable instances In-Reply-To: <7x1x15dqtk.fsf@ruckus.brouhaha.com> References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> <86y83dvacs.fsf@bhuda.mired.org> <7xfyplmsmg.fsf@ruckus.brouhaha.com> <86k6exv475.fsf@bhuda.mired.org> <7x1x15dqtk.fsf@ruckus.brouhaha.com> Message-ID: <1132911151.030214.144160@g14g2000cwa.googlegroups.com> Paul Rubin wrote: > Fair enough. How's this: > > a = ImmutableObject() > b = deepcopy(a) > assert a == b # a and b start out equal > .... do stuff .... > # since a and b are immutable, they should still be equal > # no matter what has happened above > assert a == b > > If you've added attributes to a but not to b, they should compare > unequal, breaking immutability. How about this ? a=(1,[]) b=copy.deepcopy(a) assert a==b # True a[1].append(1) assert a!=b From pwatson at redlinepy.com Wed Nov 23 16:56:34 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 23 Nov 2005 15:56:34 -0600 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c Message-ID: <3uk6siF11mqgvU1@individual.net> Any ideas why ./Modules/cjkcodecs/_codecs_cn.c fails to compile? It appears that the CODEC_STATELESS macro is concatenating 'hz' with a number and text. building '_codecs_cn' extension cc -DNDEBUG -O -I. -I/home/pwatson/src/python/Python-2.4.2/./Include -I/home/pwatson/src/python/Python-2.4.2/Include -I/home/pwatson/src/python/Python-2.4.2 -c /home/pwatson/src/python/Python-2.4.2/Modules/cjkcodecs/_codecs_cn.c -o build/temp.aix-4.3-2.4/_codecs_cn.o "/home/pwatson/src/python/Python-2.4.2/Modules/cjkcodecs/_codecs_cn.c", line 431.3: 1506-206 (S) Suffix of integer constant 100_encode is not valid. "/home/pwatson/src/python/Python-2.4.2/Modules/cjkcodecs/_codecs_cn.c", line 431.3: 1506-196 (W) Initialization between types "int(*)(union {...}*,const void*,const unsigned short**,unsigned long,unsigned char**,unsigned long,int)" and "int" is not allowed. From iainking at gmail.com Tue Nov 22 04:52:40 2005 From: iainking at gmail.com (Iain King) Date: 22 Nov 2005 01:52:40 -0800 Subject: How to paste python code on wordpress? In-Reply-To: References: <311b5ce10511211717q1d1cd6e7hd622c16d0f725745@mail.gmail.com> <79021162-F73D-44DC-B621-1CE24E14F453@tangledhelix.com> <311b5ce10511212130t68f4e562g298610fae121edb7@mail.gmail.com> Message-ID: <1132653160.942320.159390@f14g2000cwb.googlegroups.com> Dan Lowe wrote: > On Nov 22, 2005, at 12:30 AM, could ildg wrote: > > > Thank you~ > > It works! > > but how can paste "<" and ">", please? > > these 2 symbols will also confuse wordpress and I can't publish > > what I want. > > Replace < with < > > Replace > with > > > (where those abbreviations stand for "less than" and "greater than") > > Before: if x < 5: > > After: if x < 5: > > Another common character in code that you "should" do similarly is > the double quote ("). For that, use " > > Before: if x == "foo": > > After: if x == "foo": > > -dan > > -- > Any society that needs disclaimers has too many lawyers. -Erik Pepke You don't *need* to replace with " However, you will need to replace any ampersands with & ( <, >, and & are characters with intrinsic qualities in html). You need to replace & before you replace anything else: if you do it after repalcing < and > you'll catch your < and >, ending up with &lt; and &gt; which is not what you want. Iain From rrr at ronadam.com Mon Nov 7 15:57:27 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 07 Nov 2005 20:57:27 GMT Subject: Tkinter- Building a message box In-Reply-To: <1131389256.633959.267940@g44g2000cwa.googlegroups.com> References: <1131387846.676519.184420@g44g2000cwa.googlegroups.com> <1131389256.633959.267940@g44g2000cwa.googlegroups.com> Message-ID: Tuvas wrote: > Do you have any info on dialogs? I've been trying to find some, without > alot of success... > Be sure and look at the examples in python24/lib/lib-tk. The Dialog.py file there does pretty much what you want. In the dialog caller example I gave, it should have been ... def domydialog(*args, **kwds): # # check or change args or kwds # d = mydialog(*args, **kwds) return d.result I left out the returned object name 'd'. Which is needed to get the result from the dialog instance. Cheers, Ron From mwilliams at mgreg.com Sun Nov 27 00:55:30 2005 From: mwilliams at mgreg.com (Michael Williams) Date: Sun, 27 Nov 2005 00:55:30 -0500 Subject: interactive prompts In-Reply-To: References: Message-ID: Hi all, I'm having an issue with environment variables and spawned commands. Specifically, I'm using "eval `ssh-agent`" and "ssh-add". My question is, how do I force the environmental variables set by one 'popen' or 'pexpect' to propagate throughout the entire Python session so that any commands called will see those env variables? Regards, Michael From steve at REMOVEMEcyber.com.au Mon Nov 7 21:30:51 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 08 Nov 2005 13:30:51 +1100 Subject: Using python for writing models: How to run models in restricted python mode? References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> <1131401624.263258.185730@z14g2000cwz.googlegroups.com> Message-ID: <43700DDB.3020009@REMOVEMEcyber.com.au> vinjvinj wrote: > While I understand 2 is very hard (if not impossible) to do in single > unix process. I'm not sure why 1 would be hard to do. Since I have > complete control to what code I can allow or not allow on my grid. Can > i not just search for certain strings and disallow the model if it > fails certain conditions. It might not be 100% secure but will it not > get me at 90%... You might be able to think of and disallow the most obvious security holes, but how confident are you that you will think of the bad code that your users will think of? Are you concerned about malicious users, or just incompetent users? I suspect your best bet might be to write a mini-language using Python, and get your users to use that. You will take a small performance hit, but security will be very much improved. What do others think? -- Steven. From peter at engcorp.com Sat Nov 5 08:50:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Nov 2005 08:50:08 -0500 Subject: Python doc problem example: gzip module (reprise) In-Reply-To: References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> Message-ID: Jeffrey Schwab wrote: > Xah Lee wrote: > >> i've read the official Python tutorial 8 months ago, have spent 30 >> minutes with Python 3 times a week since, have 14 years of computing >> experience, 8 years in mathematical computing and 4 years in unix admin >> and perl > > I can wiggle my ears. Which is almost as good as having spent, um, let's see... a grand total of 52 hours attempting to code in Python! Which is to say roughly one week with a little overtime. I've had a large number of co-op students and junior programmers come on board in a Python/agile group. I've said here before that most of them were able to code reasonably in Python after only about one week, at least enough to contribute and participate. Several took a few weeks to completely abandon their bad habits from other languages (e.g. coding "C"-style iterate-over-chars-in-a-string loops in Python). Of course, most of them had a basic competence and ability to learn, so maybe for them 52 hours was much more effective than it is for others. Still, 52 hours is "nothing"... and doing it as "30 minutes, 3 times a week, for 8 months" vastly decreases the value of those 52 hours, even if it makes it sound much more impressive. I'm not surprised now at what we keeping seeing here... -Peter From sybrenUSE at YOURthirdtower.com.imagination Sun Nov 13 08:43:36 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 13 Nov 2005 14:43:36 +0100 Subject: help make it faster please References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> <1131646601.299316.166570@g47g2000cwa.googlegroups.com> <1131647332.797580.138890@g49g2000cwa.googlegroups.com> <1131647869.950612.174670@g43g2000cwa.googlegroups.com> <1131648184.768134.89610@f14g2000cwb.googlegroups.com> <437563bc.259066337@news.oz.net> <4375c7e6.284708769@news.oz.net> Message-ID: Bengt Richter enlightened us with: > I meant somestring.split() just like that -- without a splitter > argument. My suspicion remains ;-) Mine too ;-) 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 scott.daniels at acm.org Tue Nov 15 23:36:50 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 15 Nov 2005 20:36:50 -0800 Subject: Newb ? In-Reply-To: References: <3tvpqaFv0q48U1@individual.net> Message-ID: <437ab601$1@nntp0.pdx.net> Chad Everett wrote: > "Paul Watson" wrote in message > news:3tvpqaFv0q48U1 at individual.net... > >>Chad Everett wrote: >>>high = len(message) >>>low = -len(message) >>>print >>>print message[high:low] >>>print >>>print raw_input("Please Press Enter to Exit") >> >>Are you sure that this is not a class assignment? You can search the >>messages here for the answer. > > > No, I have been out of school way too long. I am 34 trying to learn a new > trade. I searched the group for the term backwards but I did not get any > results. The problem is that negative numbers mean "count from the rightmost end of the string or list." Also, you are going high to low without any indication that you mean to go backwards. >>> message = raw_input("Enter a Message:") >>> print message[: : -1] -Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Sun Nov 27 11:56:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Nov 2005 17:56:24 +0100 Subject: passing artibrary strings into a database References: <1133109304.575556.284190@g47g2000cwa.googlegroups.com> Message-ID: schwehr at gmail.com wrote: > I was wondering if there is a helper library out there that will nicely > encode artibrary text so that I can put in into a TEXT field in a > database and then retrieve it without getting into trouble with ',",new > lines or other such things that would foul the sql insert call and or > be a security hazard? don't ever use string formatting to add values to an SQL statement. the right way to pass variables to the database engine is to use para- meters (aka bound variables): cursor.execute( "insert into table (col1, col2) values ?, ?", value1, value2 ) the exact marker depends on the database; use the paramstyle attribute to figure out what's the right parameter marker to use for your database. see the DB-API 2 spec for more information: http://www.python.org/peps/pep-0249.html From bonono at gmail.com Sat Nov 19 02:19:47 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 18 Nov 2005 23:19:47 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132376750.855932.45470@g47g2000cwa.googlegroups.com> Message-ID: <1132384787.420064.163300@g14g2000cwa.googlegroups.com> Steven D'Aprano wrote: > Why do you assume that everything you need for your list comprehension has > to go into a single line? Chances are your list comp already calls > functions, so just create one more for it to use. > > > py> def describe(cond): > ... if cond: > ... return "odd" > ... else: > ... return "even" > ... > py> L = [describe(n % 2) for n in range(8)] > py> L > ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd'] this makes me "jump" from the list comprehension to the function, harder to follow than 'in place', especially when the function is simple, it is not necessary. What is the reason for introducing list comprehension and then later, generator expression when : a=[] for x in range(8): a.append(describe(x%2)) return a and for x in range(8): yield describe(x%2) can do the same thing ? Doesn't it violate the general idiom that it better has one and only one way to do certain thing ? I believe part of the reason is that one doesn't need to "jump" up and down. > > One major advantage is that this makes it easier to test your function > describe() in isolation, always a good thing. > > Another advantage is that the idiom "call a function" is extensible to > more complex problems: > > def describe(n): > if n < 0: > return "negative " + describe(-n) > elif n == 0: > return "zero" > elif n % 2: > return "odd" > else: > return "even" > > L = [describe(n) for n in range(8)] > > if much easier to understand and follow than using ternary expressions: > > # obviously untested > L = ["zero" if n == 0 else \ > "negative " + ("odd" if n % 2 else "even") if n < 0 else \ > "odd" if n % 2 else "even" for n in range(8)] > > Yes, I've seen ternary expressions nested three and even four deep. Now that is obsession for(and bad use of) one-liner. But picking a bad example of one liner to rule out its effectiveness and readability is a stretch I would say. From fredrik at pythonware.com Sun Nov 20 16:19:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 22:19:36 +0100 Subject: Command line References: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> Message-ID: "amfr" wrote: > Hoe would I call something on the command line from python, e.g. "ls > -la"? os.system(cmd), or some relative: http://docs.python.org/lib/os-process.html http://docs.python.org/lib/os-newstreams.html#os-newstreams or http://docs.python.org/lib/module-subprocess.html ::: also note that you shouldn't use external commands for trivial things like getting a list of files or getting the size of a file; you can get a list of all files in a directory with files = os.listdir(directory) for file in files: file = os.path.join(directory, file) # full path ... or files = glob.glob(pattern) for file in files: ... and you can get information about a given file with st = os.stat(file) size = st.st_size mtime = st.st_mtime (etc) or size = os.path.getsize(file) mtime = os.path.getmtime(file) (etc) From steve at ferg.org Tue Nov 15 15:18:57 2005 From: steve at ferg.org (Steve) Date: 15 Nov 2005 12:18:57 -0800 Subject: Python training information - now on the wiki Message-ID: <1132085937.390655.191350@g49g2000cwa.googlegroups.com> I've added a page listing Python training resources to the wiki http://wiki.python.org/moin/PythonTraining From pinkfloydhomer at gmail.com Tue Nov 8 04:31:31 2005 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: 8 Nov 2005 01:31:31 -0800 Subject: Addressing the last element of a list In-Reply-To: References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> Message-ID: <1131442291.100013.177610@g44g2000cwa.googlegroups.com> So there is no way in Python to make an alias for an object? /David From pmartin at snakecard.com Mon Nov 14 15:23:25 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Mon, 14 Nov 2005 14:23:25 -0600 Subject: SnakeCard products source code References: <1131998978.863972.144880@g14g2000cwa.googlegroups.com> Message-ID: <4n6ef.10699$ih5.3476@dukeread11> I have not tested it with longhorn yet, but it works fine with XP-pro and 2000. Regards, Philippe Kris wrote: > Thanks for sharing it. I am interested in the GINA part. > > > Philippe C. Martin wrote: >> Dear all, >> >> The source code is available in the download section: www.snakecard.com >> >> Regards, >> >> Philippe From tuvas21 at gmail.com Wed Nov 23 14:05:48 2005 From: tuvas21 at gmail.com (Tuvas) Date: 23 Nov 2005 11:05:48 -0800 Subject: Tkinter Images In-Reply-To: <1132771040.564655.24510@g43g2000cwa.googlegroups.com> References: <1132771040.564655.24510@g43g2000cwa.googlegroups.com> Message-ID: <1132772748.943366.304390@f14g2000cwb.googlegroups.com> Update: I can put the image in, but it spits out errors, adding this to it: canvas.insert(pic) BTW, I noted that my code was written incorectly The function should be as follows: def change_pic(path): global pic image=Image() #I'm using PIL to use the images, but I don't think it's depended... This code's not the important one... pic=canvas.create_image(1,1,image=image, anchor=NW) Note, add the first line above and it works. The question, how do I get it to work without the error messages? From robert.kern at gmail.com Wed Nov 23 21:06:12 2005 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Nov 2005 18:06:12 -0800 Subject: wxPython installation issues on Debian In-Reply-To: <1132795557.301034.92000@o13g2000cwo.googlegroups.com> References: <1132795557.301034.92000@o13g2000cwo.googlegroups.com> Message-ID: amhoov at yahoo.com wrote: > Hi all, > > I'm trying to install wxPython on Debian using 'apt-get install > python-wxgtk2.4.' I've got both Python 2.3 and 2.4 installed with 2.4 > set as my default. For whatever reason, wxPython always installs under > /usr/lib/python2.3/site-packages. > > Does anyone know how I can force it to install in 2.4's site-packages > directory? Install the right package: python2.4-wxgtk2.4 -- 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 fakeaddress at nowhere.org Fri Nov 4 15:47:11 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 04 Nov 2005 20:47:11 GMT Subject: random number generator In-Reply-To: References: <1131041944.218053.16400@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh wrote: >>How to generate a random number in Python. Is there any build in >>function I can call? > > > >>> import random > >>> help(random) If you need crypto-quality randomness: >>> import os >>> help(os.urandom) -- --Bryan From pierre.barbier at cirad.fr Sun Nov 13 10:41:37 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sun, 13 Nov 2005 16:41:37 +0100 Subject: Proposal for adding symbols within Python In-Reply-To: References: <43762d68$0$4335$626a54ce@news.free.fr> <43770305$0$5294$636a15ce@news.free.fr> <4377247a$0$12627$636a15ce@news.free.fr> Message-ID: <43775e8f$0$21226$626a54ce@news.free.fr> Steven D'Aprano a ?crit : > On Sun, 13 Nov 2005 12:33:48 +0100, Pierre Barbier de Reuille wrote: > > >>Steven D'Aprano a ?crit : >>[...] > > > If you want to be technical, Python doesn't have variables. It has names > and objects. > > If I want a name x to be bound to an object 1, I have to define it > (actually bind the name to the object): > > x = 1 > > If I want a symbol $x$ (horrible syntax!!!) with a value 1, why shouldn't > I define it using: > > $x$ = 1 > > instead of expecting Python to somehow magically know that I wanted it? > What if somebody else wanted the symbol $x$ to have the value 2 instead? > Well, as stated, I don't care about the actual value of symbols. They *are* values. A trivial implementation of symbols are strings : $x$ <=> "x" However, that won't fit because of the scope, because it would be great to use "is" instead of "==" (even if not necessary), and as said Mike, you might want something else than a string. That's why `x` would be a good wawy to write that. > > >>>[snip] > > > I've read the discussion, and I am no wiser. > > You haven't explained why enums are not suitable to be used for symbols. > You gave two "problems", one of which was "easy to fix", as you said > yourself, and the other reason was that you don't want to define enums as > symbols. > > If you don't want to define something manually, that can only mean that > you expect them to be predefined. Or am I misunderstanding something? > Well, I suspect Python will know them, exactly as it know "without defining it" that "foo" is the string with chars f, o, o, that 3 is the number 3, that [1,2] is the list with 1 and 2, ... However, to get quicker, symbols could be created at compile-time when possible (like variables). The fact is, symbols allow compilation optimisations that you cannot get with regular types, because the language is completely free about their representations. Then, to the programmer it is a good way to have a meaningful value without caring about how to represent it in the computer. That way, while debugging, if I ask the value of file.state I will get something I can read instead of some meaningless integer or other anonymous object. So I gain in readability of my code and in debugging capacity. Pierre From mde at micah.elliott.name Tue Nov 1 13:53:14 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Tue, 1 Nov 2005 10:53:14 -0800 Subject: Python's website does a great disservice to the language In-Reply-To: References: Message-ID: <20051101185314.GJ2575@kitchen.client.attbi.com> On Nov 01, CppNewB wrote: > First comment; "I hope the language is designed better than the > site." The site is readable, but is amateurish. That's flaim bait if I ever saw it! I find the site quite lovely: very readable, no ads, well organized, nice colors, simple, easy to maintain (uses ht2html with ReST). What are you comparing it to? Have a look at homepages for ruby, java, tcl, and perl. I consider python.org superior to all of them. It is my personal benchmark for webpage usability. -- _ _ ___ |V|icah |- lliott http://micah.elliott.name mde at micah.elliott.name " " """ From amfr.org at gmail.com Mon Nov 14 17:31:17 2005 From: amfr.org at gmail.com (amfr) Date: 14 Nov 2005 14:31:17 -0800 Subject: Parse file into array References: <1132004925.481923.47520@z14g2000cwz.googlegroups.com> Message-ID: <1132007477.237649.40740@g44g2000cwa.googlegroups.com> Thanks a lot. The webserver I am writing works now :) From dreamerbin at gmail.com Mon Nov 7 18:23:54 2005 From: dreamerbin at gmail.com (dreamerbin at gmail.com) Date: 7 Nov 2005 15:23:54 -0800 Subject: Regular expression question -- exclude substring Message-ID: <1131405834.093144.206510@g43g2000cwa.googlegroups.com> Hi, I'm having trouble extracting substrings using regular expression. Here is my problem: Want to find the substring that is immediately before a given substring. For example: from "00 noise1 01 noise2 00 target 01 target_mark", want to get "00 target 01" which is before "target_mark". My regular expression "(00.*?01) target_mark" will extract "00 noise1 01 noise2 00 target 01". I'm thinking that the solution to my problem might be to use a regular expression to exclude the substring "target_mark", which will replace the part of ".*" above. However, I don't know how to exclude a substring. Can anyone help on this? Or maybe give another solution to my problem? Thanks very much. From deets at nospam.web.de Sun Nov 6 15:10:55 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 06 Nov 2005 21:10:55 +0100 Subject: Validate string as UTF-8? In-Reply-To: <*firstname*nlsnews-835F79.13585206112005@news.verizon.net> References: <*firstname*nlsnews-835F79.13585206112005@news.verizon.net> Message-ID: <3t76agFrgq0tU1@uni-berlin.de> Tony Nelson wrote: > I'd like to have a fast way to validate large amounts of string data as > being UTF-8. > > I don't see a fast way to do it in Python, though: > > unicode(s,'utf-8').encode('utf-8) > > seems to notice at least some of the time (the unicode() part works but > the encode() part bombs). I don't consider a RE based solution to be > fast. GLib provides a routine to do this, and I am using GTK so it's > included in there somewhere, but I don't see a way to call GLib > routines. I don't want to write another extension module. I somehow doubt that the encode bombs. Can you provide some more details? Maybe of some allegedly not working strings? Besides that, it's unneccessary - the unicode(s, "utf-8") should be sufficient. If there are any undecodable byte sequences in there, that should find them. Regards, Diez From christopherlmarshall at yahoo.com Fri Nov 11 10:49:21 2005 From: christopherlmarshall at yahoo.com (christopherlmarshall at yahoo.com) Date: 11 Nov 2005 07:49:21 -0800 Subject: derived / base class name conflicts In-Reply-To: <43747075$0$7344$636a55ce@news.free.fr> References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> <1131677456.966817.147470@g44g2000cwa.googlegroups.com> <43747075$0$7344$636a55ce@news.free.fr> Message-ID: <1131724161.083151.255920@g14g2000cwa.googlegroups.com> Your suggestion ('_name' -> implementation, 'name' -> API) makes sense as a convention between programmers that know a fair amount about each other's classes before using them. I don't think it is reasonable in general to only subclass from base classes you have studied the full API of, however. The double underscore is a decent solution to my problem. I imagine it must be used a lot in domains where people are making heavy use of third party python code. Chris Marshall From bignose+hates-spam at benfinney.id.au Wed Nov 16 07:46:14 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Nov 2005 23:46:14 +1100 (EST) Subject: Reinvent no more forever References: <1132142657.163928.16460@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: > Ben Finney wrote: > > On dirtSimple.org[0], PJE wrote: > > > > [...] Python code is easy to write, but hard to depend on. You > > pretty much have to: > > > > 1. limit yourself to platforms with a suitable packaging > > system, > > 2. bundle all your dependencies into your distribution, or > > For pure python modules I don't find this to be a big problem. The problem isn't whether it's Python or not; the problem is the complexity of the code base. A simple application that depends on infrastructure from five different non-standard packages becomes a right mess to distribute, is stuck with code that is peripheral to its own purpose, and can't benefit from new versions of those packages. > > [distributing a simple package via PyPI] > > > > Disadvantages: > > > > - Proliferation. What's the protocol when[1] someone else puts > > an (incompatible, differently-specified) Enum implementation > > into PyPI? > > That shouldn't be any more of a problem than the current situation. > In fact as the setuptools system becomes more established then it > should be easier for people to discover that an existing package > does what they want - rather than creating their own. I hold up all existing public source code repositories as evidence against your prediction. Reinventing the wheel is distressingly common, and a dependency tool isn't going to stop that. > > - Naming. How many ways can a package providing an Enum be > > named? I'd prefer mine to be named "Enum" or "enum", but why > > should mine be the one that claims that name? > > I think "first come - first served" is the only possible way this > can work. Perhaps so. > > - It's just a pretty simple type, with unit tests. Does this > > really justify a PyPI package? > > If it solves a common problem in an elegant way, then it's better > shared. :-) Sure. But the question was, is PyPI the place to do so? > > This is common to any repository of code. But the "automatic > > dependency" problem means that all those packages, and many more > > outside that repository, need to know how those problems are > > resolved. > > > > Operating system distributors have policies (to greater or lesser > > degrees of strictness) to ensure this kind of quality control. My > > understanding of PyPI is that there's no such policy. > > Isn't setuptools *the system* that addresses these issues ? It > provides a way to track and auto-install dependencies [...] No, setuptools is only the answer for the packages themselves; the problems I describe are inherent to the package repository. The setuptools dependency model rests on the reliability of the package repository. Not only in terms of availability but also in terms of the quality and functionality of the package set. -- \ "I went to the museum where they had all the heads and arms | `\ from the statues that are in all the other museums." -- Steven | _o__) Wright | Ben Finney From swaroopch at gmail.com Thu Nov 10 03:00:30 2005 From: swaroopch at gmail.com (Swaroop C H) Date: 10 Nov 2005 00:00:30 -0800 Subject: How to set program name in Python? ($0 in Perl) In-Reply-To: References: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> Message-ID: <1131609630.342099.301590@z14g2000cwz.googlegroups.com> Thanks Fredrik for the info. It was not a must-have, I was just curious if it was possible. Thanks, Swaroop www.SwaroopCH.info From anton.vredegoor at gmail.com Thu Nov 17 12:45:11 2005 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 17 Nov 2005 09:45:11 -0800 Subject: Python obfuscation In-Reply-To: <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> Message-ID: <1132249511.886027.93990@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > Modern equivalent of serialization (publishing one chapter at a time on > the web, the next chapter to come only if the author receives enough > payment for the previous one) have been attempted, but without much > success so far; however, the holy grail of "micropayments" might yet > afford a rebirth for such a model -- if paying for a chapter was > extremely convenient and cheap, enough people might choose to do so > rather than risk the next chapter never appearing. Remember that, by > totally disintermediating publishers and bookstores, a novelist may > require maybe 1/10th of what the book would need to gross in stores, in > order to end up with the same amount of cash in his or her pockets. > > One could go on for a long time, but the key point is that there may or > may not exist viable monetization models for all sorts of endeavours, > including the writing of novels, depending on a lot of other issues of > social as well as legal structures. Let's not be blinded by one model > that has worked sort of decently for a small time in certain sets of > conditions, into believing that model is the only workable one today or > tomorrow, with conditions that may be in fact very different. Maybe this micropayment thing is already working and active. What is the cost of a mouseclick and what is the monetarial value of the fact that someone is clicking on a link? Someone bought virtual property for real money and sold it later with a lot of profit. There are pages where one can buy pixels. Maybe me replying to you will provoke some other chain of events with payoffs for you or me (I hope positive :-) The idea of using a webservice to hide essential secret parts of your application can only work well if one makes some random alterations to the results of the queries. Like GPS signals that are deliberately made less exact. Obfuscated Python code could for example return variable precision numbers with a slight random alteration. I think such things would make it harder to reverse engineer the code behind the server. But the more one messes with the ideal output the more often the user will rather click another link. (or launch another satellite) Anton. what's the current exchange rate for clicks and dollars? From tuvas21 at gmail.com Wed Nov 9 10:56:23 2005 From: tuvas21 at gmail.com (Tuvas) Date: 9 Nov 2005 07:56:23 -0800 Subject: PIL-> Tkinter Message-ID: <1131551783.628602.3320@g14g2000cwa.googlegroups.com> Is there a way to put an image loaded from PIL into a TKinter GUI? Without converting the image to a .bmp, and using a canvas? If that's the only way it'll work, I'll take it, but... It would be nice otherwise... From steve at holdenweb.com Wed Nov 9 13:47:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 09 Nov 2005 18:47:59 +0000 Subject: Python obfuscation In-Reply-To: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> Message-ID: petantik wrote: > Are there any commercial, or otherwise obfuscators for python source > code or byte code and what are their relative advantages or > disadvantages. I wonder because there are some byte code protection > available for java and .NET, although from what i've read these seem to > be not comprehensive as protection schemes > Before adding complex protection mechanisms to your code you first need some code worth protecting, which is to say it should have some novel features or represent a lot of work that offers useful integrated functionality for a task or a skill area. Most inquiries of this nature appear to fall at that first hurdle. There are things you can do, but I'm always keenly aware that very few users of a program have both the skills and the inclination to rip off the code even when the source is distributed as part of the product. Personally I've never bothered with obfuscation, and prefer to rely on copyright when I deliver code to customers. 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 nobody at this.home.com Wed Nov 30 08:30:45 2005 From: nobody at this.home.com (Krystian) Date: Wed, 30 Nov 2005 14:30:45 +0100 Subject: python speed References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> Message-ID: >I would also like to see Half Life 2 in pure Python. or even quake1, do you think it could have any chances to run smoothly? or maybe demoscene productions... From *firstname*nlsnews at georgea*lastname*.com Thu Nov 17 22:52:14 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Fri, 18 Nov 2005 03:52:14 GMT Subject: Python Library Reference - question References: <1132217639.080443.144910@g44g2000cwa.googlegroups.com> Message-ID: <*firstname*nlsnews-3F325F.22521917112005@news.verizon.net> In article <1132217639.080443.144910 at g44g2000cwa.googlegroups.com>, bobueland at yahoo.com wrote: > The "Python LIbrary Reference" at > http://docs.python.org/lib/contents.html seems to be an important > document. I have two questions > > Q1. How do you search inside "Python LibraryReference" ? Does it exist > in pdf or chm form? ... I use Google: site:docs.python.org/lib foo bar Note that Google is pretty flexible about what is a "site". "docs.python.org/lib", "docs.python.org", and "python.org" are all "sites", so you can zoom in and out as needed. The other suggestions look good, too. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From nil at dev.nul Thu Nov 10 00:18:27 2005 From: nil at dev.nul (Christian Stapfer) Date: Thu, 10 Nov 2005 06:18:27 +0100 Subject: Floating numbers and str References: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> Message-ID: "Tuvas" wrote in message news:1131565949.678342.39890 at g44g2000cwa.googlegroups.com... >I would like to limit a floating variable to 4 signifigant digits, when > running thorugh a str command. Ei, > > > x=.13241414515 > y=str(x)+" something here" > > But somehow limiting that to 4 sign. digits. I know that if you use the > print statement, you can do something like %.4d, but how can I do this > with converting the number to a string? Thanks! from scipy import round print round(0.13241414515,4) Regards, Christian From fredrik at pythonware.com Wed Nov 2 12:59:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Nov 2005 18:59:28 +0100 Subject: where to download md5.py? References: <2387F0EED10A4545A840B231BBAAC722607F98@slcimail1.slcgov.com> Message-ID: "Bell, Kevin" wrote: > I've been looking around, but haven't found a place to download the > md5.py module. I need it to run the dupinator.py md5 is a standard Python module (written in C). it's been in Python since the early ages, so if you don't have it, your install is most likely broken (per- haps intentionally, based on this: http://eprint.iacr.org/2004/199 ) if the dupinator you're talking about is this script: http://svn.red-bean.com/bbum/trunk/hacques/dupinator.py you can probably make it work by replacing all references to the "md5" module with "sha". (if that module isn't available either, it's time to talk to your system administrators) From bonono at gmail.com Tue Nov 22 18:05:47 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 15:05:47 -0800 Subject: about sort and dictionary In-Reply-To: References: <1132653873.855348.265740@g47g2000cwa.googlegroups.com> Message-ID: <1132700747.794586.73170@g44g2000cwa.googlegroups.com> OKB (not okblacke) wrote: > Fredrik Lundh wrote: > > > bonono at gmail.com wrote: > > > >> > so what would an entry-level Python programmer expect from this > >> > piece of code? > >> > > >> > for item in a.reverse(): > >> > print item > >> > for item in a.reverse(): > >> > print item > >> > > >> I would expect it to first print a in reverse then a as it was. > >> > >> a=[1,2,3] > >> > >> I expect it to print > >> > >> 3 > >> 2 > >> 1 > >> 1 > >> 2 > >> 3 > > > > really? wouldn't > > > > 3 > > 2 > > 1 > > 3 > > 2 > > 1 > > > > make a lot more sense ? > > Yes. The unintuitive thing is that the list is sorted in place at > all. > intuitive seems to be a very subjective matter, depends on once background etc :-) From cjw at sympatico.ca Tue Nov 8 18:49:43 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 08 Nov 2005 18:49:43 -0500 Subject: Diff. between Class types and classic classes In-Reply-To: <4370ba00$0$7529$626a14ce@news.free.fr> References: <1131454786.272355.314740@z14g2000cwz.googlegroups.com> <4370ba00$0$7529$626a14ce@news.free.fr> Message-ID: bruno at modulix wrote: > venk wrote: > >>Hi, >> can some one properly explain the differences between class types and >>classic classes? ... Still face problems in identifying what is what. > > > I'm not sure I understand your question. Are you talking about the diff > between old-style and new-style classes, or the diff between classes and > metaclasses ? > "new" classes inherit from object. Classic classes do not. "new" classes have a __new__ method. Classic classes generally do not. The type of a "new" class is types.TypeType The type of a classic class is a classobj The type of an instance of a "new" class is the name of the class The type of an instnce of a classic class is an instance This is shown below: >>> class A(object): ... def __init__(self): ... pass ... >>> a= A() >>> class B: ... def __init__(self): ... pass ... >>> b= B() >>> type(A) >>> type(a) >>> type(B) >>> type(b) >>> I hope that this helps. Colin W. From samrobertsmith at gmail.com Tue Nov 15 05:58:10 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Tue, 15 Nov 2005 02:58:10 -0800 Subject: compare list In-Reply-To: <8c7f10c60511150227v297140e1n@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <1d987df30511142330t39b137fdpdc9eee56e73d6e1f@mail.gmail.com> <4379AA95.80806@cc.umanitoba.ca> <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> <8c7f10c60511150227v297140e1n@mail.gmail.com> Message-ID: <1d987df30511150258j7848d3d5o61905f5ac935a6b0@mail.gmail.com> On 11/15/05, Simon Brunning wrote: > On 15/11/05, Shi Mu wrote: > > it does not work. > > >>> len(set(lisA).intersection(set(lisB))) == 2 > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'set' is not defined > > 'set' is introduced as a built-in at Python 2.4. If you have 2.3, > there's an analogous module. > > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ > Yes, i am using python 2.3, I have used from sets import * but still report the same error: > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'set' is not defined From cito at online.de Wed Nov 23 14:38:05 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 20:38:05 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: Message-ID: Steve Holden schrieb: > Perhaps now the answer top your question is more obvious: there is by no > means universal agreement on what an "ordered dictionary" should do. > Given the ease with which Python allows you to implement your chosen > functionality it would be presumptuous of the core developers to favour > any one of the several reasonable alternatives that might be chosen. The discussion showed indeed that there are some points which are not so straightforward as I believed. But I still don't see the "several reasonable alternatives". So far all implementations I have seen are basically pretty similar. Is there any implementation that is basically different from Foord/Larosa's odict? I still don't see a principal problem here, just the problem that the existing implementations are not well enough thought-out and sophisticated enough. > Given the ease with which Python allows you to implement your chosen > functionality it would be presumptuous of the core developers to > favour any one of the several reasonable alternatives that might be > chosen. You could say the same about the idea of sets in Python, and it is probably the reason why it took so much time until they became a part of Python. I wished that had happened earlier, since sets are "the" basic mathematic structure. I'm now very happy to have sets not only in the standard lib but even as built-in types and I'm sure there hasn't been "universal agreement" on how sets should be implemented either. I don't think it was presumptuous to finally settle down on one implementation. Of course, ordered dictionaries are no candidates for becoming built-in data types, and the existing implementations are not sophisticated and mature enough to go to the standard lib right now. But principally, if an improved version is developed (maybe on the occasion of this thread) and will be tested and proven, why should it not go to the standard lib some day? BTW, somebody has suggested it could go to "collections" which sounds like the right place, but the description says the module is intended for "High-performance container datatypes", and, as has been discussed, ordered dictionaries are not used for performance or efficiency reasons, but rather for reasons of convenience. So *if* they ever go to the standard lib, I'm not sure whether "collections" would be the right place. Or collections will need a different description - maybe there are other interesting basic collection types which are chosen for convenience, not for performance (for instance, ordered sets)? -- Christoph From iddw at hotmail.com Fri Nov 18 09:14:38 2005 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 18 Nov 2005 08:14:38 -0600 Subject: Reinvent no more forever References: <1132279615.605498.258140@o13g2000cwo.googlegroups.com> Message-ID: On 17 Nov 2005 18:06:55 -0800 in comp.lang.python, "Phillip J. Eby" wrote: [...] > >Okay, so call yours "SuperEnum" or "PowerEnum" or "UltraEnum" or >"BetterEnum", "Enum-O-Matic", "Symbolitron"... ITYM "EnumOMatic" or "Enum_O_Matic". "Enum-O-Matic" is a syntax error. Or worse... Regards, -=Dave -- Change is inevitable, progress is not. From rbt at athop1.ath.vt.edu Mon Nov 28 08:40:07 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 28 Nov 2005 08:40:07 -0500 Subject: speeding up Python when using wmi Message-ID: Here's a quick and dirty version of winver.exe written in Python: http://filebox.vt.edu/users/rtilley/public/winver/winver.html It uses wmi to get OS information from Windows... it works well, but it's slow... too slow. Is there any way to speed up wmi? In the past, I used the platform and sys modules to do some of what winver.exe does and they were rather fast. However, since switching to wmi (for a more accurate representation) thinngs have gotten slow... real slow. I suppose this could be a wmi only issue not related at all to Python. Any tips or ideas? Thanks! From robert.kern at gmail.com Mon Nov 28 21:01:52 2005 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 28 Nov 2005 18:01:52 -0800 Subject: Looking for small, impressive 3D-related Python script In-Reply-To: <28E540BB-4A56-46CD-8351-68E642E948EF@sbcglobal.net> References: <28E540BB-4A56-46CD-8351-68E642E948EF@sbcglobal.net> Message-ID: Kenneth McDonald wrote: > I'm not trying to persuade my company to offer Python as a scripting > language for their product, but I am trying to give them examples of > things that Python can do easily that cannot be done easily with > their current proprietary scripting language. After that it would be > their decision. As the product is a 3D package, I'm looking for > something in this field. It sounds like the best analogy to use would be Blender. It's a 3D modeller that uses Python as its scripting language instead of a proprietary one. Your best bet might be to trawl through the various Python scripts that people have written for Blender to find something impressive. http://www.blender3d.org/cms/Python_Scripts.3.0.html Oh look, L-systems: http://jmsoler.free.fr/util/blenderfile/images/lsystem/lsystem.htm -- 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 ark at acm.org Sun Nov 27 14:02:50 2005 From: ark at acm.org (Andrew Koenig) Date: Sun, 27 Nov 2005 19:02:50 GMT Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> <1133041306.601950.213710@g43g2000cwa.googlegroups.com> Message-ID: "mojosam" wrote in message news:1133041306.601950.213710 at g43g2000cwa.googlegroups.com... > I would have to talk to a lawyer to be sure, but right now, I think I > can argue that anything I do on my own time belongs to me. I'm > technically a consultant right now (even though I'm spending 40 > hours/week with the one "client"). I can take on other clients, as > long as they don't directly compete. This means they're hiring my > expertise. If I bring my own tools, that's part of my expertise. I do > recall there was a clause in the contract that anything I did on their > time belonged to them. For my next client, I should definitely include > a clause about rereleasing open source changes. Yup. If you're not an employee (that is, if you get a 1099 form rather than a W-2 form from your client), then any work you do belongs to you *except* for what you agree in writing belongs to them. So if you write code that's not part of any deliverable, it's yours. Of course, they might object to your using their facilities, or working on their time, on stuff that isn't part of a deliverable. But that's a separate problem entirely. From nicogrubert at gmail.com Thu Nov 24 09:00:27 2005 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 24 Nov 2005 15:00:27 +0100 Subject: ftplib question - ftp.dir() returns something and ftp.nlst() does not Message-ID: <4385C77B.3060007@gmail.com> Hi there, I am using the ftplib library to connect to a ftp server. After I got connected, I can see a list of file in the current directory using ftp.dir() or ftp.retrlines('LIST'). But using ftp.nlst() returns an empty list which seems somehow strange to me. Here is, what I did: >>> from ftplib import FTP >>> HOST = 'my.server' >>> USER = 'myuser' >>> PASSWD = 'mypass' >>> ftp = FTP(HOST, USER, PASSWD) >>> ftp.set_pasv(0) # set active mode >>> ftp.dir() -r--r--r-- 1 owner group 121984 Nov 24 12:13 member.dat -r--r--r-- 1 owner group 115 Nov 24 15:53 status.dat -r--r--r-- 1 owner group 339 Nov 24 15:53 debug.txt >>> >>> ftp.retrlines('LIST') -r--r--r-- 1 owner group 121984 Nov 24 12:13 member.dat -r--r--r-- 1 owner group 115 Nov 24 15:53 status.dat -r--r--r-- 1 owner group 339 Nov 24 15:53 debug.txt '226 Transfer complete.' >>> >>> ftp.nlst() [] >>> I thought "ftp.nlst()" would return the list ['member.dat', 'status.dat', 'debug.txt']. Any idea, what is going wrong here? Nico From arkanes at gmail.com Fri Nov 25 08:50:54 2005 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 25 Nov 2005 07:50:54 -0600 Subject: Guification of console app In-Reply-To: References: <1132871970.821787.204830@g14g2000cwa.googlegroups.com> <1132909528.263090.326890@g47g2000cwa.googlegroups.com> Message-ID: <4866bea60511250550h324fbf35o202309e6148dff41@mail.gmail.com> On 11/25/05, Fredrik Lundh wrote: > "metiu" wrote: > > > you have a compression utility that works as a standard *nix filter, so > > it takes something from stdin and gives it back compressed to stdout > > you like to use it as such, because it's nice to call it from the > > command line > > > > now someone finds your utility quite nice, and says it would be nice to > > have a GUI that shows you, for example, how long it will take to > > compress... > > > > one way for sure it would be to fork your app, but this would be a > > waste of time > > > > you'd like to reuse the compression library you've already written for > > your GUI and your console, but: > > - you'd like to have your console app clean and simple, such as: > > > > import sys > > import CompressLib > > > > data = sys.stdin.read() > > cdata = CompressLib.compress(data) > > print cdata > > > > but you'd like the GUI to show some progress and status info. > > here's a simple, stupid, and portable solution. the first script simulates > your compression utility: > > # compress.py (simulator) > > import time, sys > > for i in range(100): > sys.stdout.write(".") > sys.stderr.write("%d%% done\r" % i) > sys.stderr.flush() > time.sleep(0.1) > > (it prints "N% done" messages to stderr during the compression) > > the second script simulates your GUI. the stuff in the while loop should > be run by a timer/alarm function, at regular intervals: > > import re, subprocess, time, os > > class monitor: > # looks for "N% done" messages in the output stream > def __init__(self, tfile): > # could use dup/reopen instead > self.file = open(tfile.name, "r") > def poll(self): > pos = self.file.tell() > data = self.file.read() > if data: > data = re.findall("(\d+)% done", data) > if not data: > self.file.seek(pos) > else: > return int(data[-1]) > def close(self): > self.file.close() > > ifile = open("in.txt", "rb") > ofile = open("out.dat", "wb") > tfile = open("out.tmp~", "wb") > > p = subprocess.Popen( > "python compress.py", > stdin=ifile, stdout=ofile, stderr=tfile, > ) > > m = monitor(tfile) > > while 1: > # this should be placed in a background task that's called > # every second or so > if p.poll() is not None: > print "DONE" > break > status = m.poll() > if status is not None: > # update status monitor > print status, "PERCENT DONE" > # wait a while before calling the background task again > print "." > time.sleep(0.5) > > # clean up > ifile.close() > ofile.close() > m.close() > name = tfile.name > tfile.close() > os.remove(name) > > if you limit yourself to Unix only, you can simplify things quite a bit (e.g. > using a pipe instead of the temporary file and use select to poll it, or use > dup/reopen tricks to avoid opening the temporary file twice; if you do > the latter, you can also use safe tempfile creation methods (see the > "tempfile" method for details. etc). > > hope this helps! > > > > If you are using wxPython, you can skip writing this scaffolding yourself and use wx.Execute and wx.Process, which will allow you to execute other processes and re-direct thier input and output. The wxPython demo has an example. > > -- > http://mail.python.org/mailman/listinfo/python-list > From bonono at gmail.com Wed Nov 9 08:20:05 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 05:20:05 -0800 Subject: append to non-existing list In-Reply-To: References: <4371EFBC.1030502@sitasoftware.lu> Message-ID: <1131542405.897583.245160@g49g2000cwa.googlegroups.com> If PHP is heavily influenced by Perl(as I read some where), the variable name determine it I believe. @myvar is an array ? s... at pobox.com wrote: > I don't know php, but would also have to wonder how it knows to create a > list instead of an integer (for example). > Skip From *firstname*nlsnews at georgea*lastname*.com Sun Nov 6 13:50:02 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Sun, 06 Nov 2005 18:50:02 GMT Subject: ? MDI depreciated References: <1131294807.907281.58980@g47g2000cwa.googlegroups.com> <1131301424.814634.237230@f14g2000cwb.googlegroups.com> Message-ID: <*firstname*nlsnews-01E8E8.13500406112005@news.verizon.net> In article <1131294807.907281.58980 at g47g2000cwa.googlegroups.com>, "LenS" wrote: > Hate to ask this dum question (since I've been hiding under a rock). > But if the MDI UI model is/was depreciated. What is the new UI model. > > Would love some links that explain in gerneral and specific terms. In article <1131301424.814634.237230 at f14g2000cwb.googlegroups.com>, "Brendan" wrote: > This is probably a question better suited for a wxPython or MSDN > newsgroup. What OS are you referring to? What GUI toolkit are you > using? > > Microsoft's office on Windows has moved to a model where every document > has its own toolbar, menubar, and taskbar entry. Windows developers > tend to mimic MS Office, so many are also moving to this model. Mac > apps have never had MDI. MS also uses a "Tabbed" version of MDI where only one document at a time is visible. Sometimes this is /implemented/ using the MDI APIs (and they also have some MDI apps that don't use the APIs; go figure). Gnome uses Tabbed windows as well; see Gedit, which opens documents in tabs, though they can be dragged out into their own windows. In GTK, at least, the Tabbed interface is easily done as a Notebook. MacOS apps used MDI from the beginning of Multifinder; it just worked better than on MSWindows because instead of a grey background you got to see the rest of the desktop and the other apps. On MacOS, MDI was referred to as "Layers". If on MSWindows MDI windows were always maximized, had no grey background, and hid the MDI Frame when not in front, they would be almost exactly what MacOS did. MOSX, being a version of NextOS and NextStep, has the more "advanced" no-layer, no-MDI UI, and Apple recommends that each app should have only one window. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From nnorwitz at gmail.com Tue Nov 22 23:52:17 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 22 Nov 2005 20:52:17 -0800 Subject: 2.4.2 on AIX 4.3 make fails on threading In-Reply-To: <3uhddoF1145hiU1@individual.net> References: <3uhddoF1145hiU1@individual.net> Message-ID: <1132721537.091089.35380@g47g2000cwa.googlegroups.com> Paul Watson wrote: > When I try to build 2.4.2 on AIX 4.3, it fails on missing thread > objects. I ran ./configure --without-threads --without-gcc. > > Before using --without-threads I had several .pthread* symbols missing. Perhaps you need to add -lpthread to the link line. This should be able to work. What is the link line output from make? > Can anyone > suggest a configuration or some change that I can make to cause this to > build correctly? Thanks. > > ld: 0711-317 ERROR: Undefined symbol: ._PyGILState_NoteThreadState I think that problem has been fixed. Try downloading this file and replace the one in your build directory: http://svn.python.org/projects/python/branches/release24-maint/Python/pystate.c n From graham.abbott at gmail.com Fri Nov 4 02:41:46 2005 From: graham.abbott at gmail.com (Graham) Date: 3 Nov 2005 23:41:46 -0800 Subject: Class Variable Access and Assignment In-Reply-To: <436AD833.8090808@REMOVEMEcyber.com.au> References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <1131049615.656278.24270@g47g2000cwa.googlegroups.com> <864q6tihcw.fsf@bhuda.mired.org> <1131069731.637117.104530@g43g2000cwa.googlegroups.com> <436AD833.8090808@REMOVEMEcyber.com.au> Message-ID: <1131090106.194854.151340@g14g2000cwa.googlegroups.com> Once again, many thanks, your explainations are very detailed and i think i'm in full understanding of the what/when/why of it all. And with further introspection i can see why its done this way from a language processing point of view rather than programming one. I also now realize that . is there so that you dont have to type .__class__. all the time. Once again many thanks, i hadn't expected nearly this type of response. Graham. From belred at gmail.com Fri Nov 25 12:13:05 2005 From: belred at gmail.com (Bryan) Date: Fri, 25 Nov 2005 09:13:05 -0800 Subject: Python as Guido Intended In-Reply-To: <1132863273.378601.323870@f14g2000cwb.googlegroups.com> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> Message-ID: > But suppose someone came up with a Python compiler. It > would compile any Python program but there would be no > speed benefit unless you carefully wrote the code to not use > many of Python's dynamic features, so that either by type > inferencing or programmer supplied static declarations, the > compiler could generate efficient native machine code > that executes at near C speeds. > Obviously this would require changes (mostly additions?) > to the Python language, though these changes would still > allow today's style dynamic code to be written and run > (though just as slow as today's runs). > The payout would be that things written as C-extensions > today, would be writable in (a restricted form of) Python. > Would the Python orthodoxy favor such a development? > Or would that be turning Python into a screwdriver? > > i agree with you... pyrex should be part of the python distribution :) bryan From mwm at mired.org Fri Nov 11 03:08:07 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Nov 2005 03:08:07 -0500 Subject: LARGE numbers References: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> Message-ID: <86k6ff4nfc.fsf@bhuda.mired.org> "Tuvas" writes: > I've been thinking about writing a program to generate the world's > largest prime numbers, just for the fun of it. This would require being > able to hold an 8000000 digit number into memory (25 megabits, or a > little over 3 megs of memory for just one variable...) I would also > need several smaller variables. This came about as I optimised a prime > number generator more and more, until I came with the idea to try to > find the largest ever, using python. Any ideas? I'll probably try to > run this on a mainframe eventually, although they might not like it > very much... I'll run it on my home computer to first test it. Anyways, > let me know if there's a way to make python support numbers so high. Python already supports numbers that large: >>> math.log(10 ** 8000000) 18420680.743952367 >>> However, you probably want to look into something like gmpy, as you'll get better performance out of it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Sat Nov 26 03:30:30 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 26 Nov 2005 19:30:30 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <1h6lmts.1fr63yddwj4y4N%aleax@mail.comcast.net> Message-ID: On Fri, 25 Nov 2005 20:17:15 -0800, Alex Martelli wrote: > Steven D'Aprano wrote: > >> On Thu, 24 Nov 2005 17:43:22 +0100, Martin P. Hellwig wrote: >> >> > if I owned a company >> > making profit on software sales (sale =! support) you sign a death wish >> > for using GPL >> >> Apart from Microsoft, and possibly Quark (makers of Quark Express desktop >> packaging software), and perhaps a few console game developers, is there >> any company making a profit on software sales? > > I believe Oracle is doing fine (and they appear to be trying to buy up > most everybody else -- other companies which used to make profits from > software sales before they got gobbled up). I think SAP and Adobe > aren't doing badly, either, but I haven't checked up on them in a while. My understanding is that both Oracle and SAP make most of their money through consulting and customization rather than licencing or sales. I don't know anyone who has bought a SAP solution that didn't spend an awful lot of money having it customized -- and unless I'm very mistaken, you don't own the customizations you pay for. Adobe, I'm not sure -- I suspect their biggest source of income is royalties on Postscript for laser printers, but I could be wrong. I don't even know anyone who uses Pagemaker any more -- it seems to have been almost completely overshadowed by Quark Xpress. > I'd be surprised if there weren't many relative minnows that I didn't > think of, beyond the few "obvious" big fishes above listed. Yes, there are a few -- Quickbooks and MYOB, although arguably their main income comes from subscription/upgrades rather than sales. But still, consider the sheer size of the software industry, and the fact that apart from the 800lb gorilla of Microsoft, almost nobody can make a profit from selling software. -- Steven. From bokr at oz.net Wed Nov 30 22:00:35 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 01 Dec 2005 03:00:35 GMT Subject: How to list currently defined classes, methods etc References: <1133401234.314572.315550@g47g2000cwa.googlegroups.com> Message-ID: <438e66e7.356479220@news.oz.net> On Wed, 30 Nov 2005 20:55:46 -0500, Peter Hansen wrote: >Deep wrote: >> If i start a python shell. Is there a way to list the currently defined >> classes, methods, >> variables? > >Does this work? > > >>> dir() > >>> help(__name__) might be interesting for the OP too ;-) Regards, Bengt Richter From mwm at mired.org Thu Nov 10 21:01:24 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 21:01:24 -0500 Subject: Command-line tool able to take multiple commands at one time? References: Message-ID: <86acgc54ej.fsf@bhuda.mired.org> Peter A. Schott writes: > Per subject - I realize I can copy/paste a line at a time into an interactive > session when I'm trying to debug, but was wondering if there is any tool out > there that allows me to copy sections of working Python scripts to paste into my > interactive console and let those run so I don't have to copy line-by-line. Um, just curious - doesn't copying multiple lines at a time work now? That works fine for me on both OS X and Unix. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jes at nl.demon.net Tue Nov 1 20:55:22 2005 From: jes at nl.demon.net (Jim Segrave) Date: Wed, 02 Nov 2005 01:55:22 -0000 Subject: If Statement Error (Tic Tac Toe) References: <1130878530.389205.179640@g43g2000cwa.googlegroups.com> Message-ID: <11mg74a6arsfo02@corp.supernews.com> In article <1130878530.389205.179640 at g43g2000cwa.googlegroups.com>, wrote: >Greetings! I am trying to make a multiplayer (no AI, 2 person) game of >tic tac toe in Python. So far it has been pretty simple. My only >concern is with the win checking to see if a person has won. At first >it looked like it was working, but now it sometimes assigns a win when >you enter an X or O (doesn't matter) on certain tiles (row 1, column 1 >won't be an error, but row 2, column 3 will be...). If you can find >the problem, I'd be very thankful! Here's the code: I see one of the reponses directs you to a web site about how to ask questions and expect answers - there's some very good advice there. Nonetheless, I'll give you the benefit of the doubt and assume that you are _very_ new to programming. I hope I haven't redone your homework for you, but if I have, I would suggest you don't submit my answer, I think it might be recognised as not being your own. The biggest problem with asking someone for help with a program like this is that it's very large (not in and of itself a problem) and, even to the most rapid glance, the program contains huge swathes of essentially the same code repeated over and over with only tiny changes. When I see that, all the warning bells start ringing. My first hint would be that anytime you find yourself typing exactly the same (or almost exactly the same thing) over and over, you are probably doing something wrong. In your original code, you have a whole section for handling player X, then you have virtually identical code, for player O. You should almost never need to do this. There are a couple of easy ways to save retyping the same code: 1) create a function. The function body will have all the identical code, the function arguments will indicate what's different between the two sections. I think this is a hint from Kernighan and Pike from a book dating back to the late 1960's - subroutines are used to show what code has in common, the arguments are used to show what's different. or 2) put the duplicated code inside a loop and let the loop variable be used to make the small changes. That's what I did in the hasty rework of your program below. Then, when we look at the code for a single player, you have 9 separate tests to see if a cell is occupied: if row == 2 and column == 1: if gameboard[3] != ('O' or 'X'): gameboard[3] = ('O') else: print "This cell is already filled." turnnumber = turnnumber - 1 For each row and column, you know which cell to look at, so why have tests for every possible input, when only one test will apply for any given user input? The cell you want is: gameboard[3 * (row - 1 ) + (column - 1)] so one test can replace 9. In reworking this, I calculate this location once and save it as 'loc', since I'll be needing the location later. Then there's the question of the test if the cell is occupied: if gameboard[3] != ('O' or 'X'): This doesn't test if the cell contains an 'O' or an 'X', what it actually tests is whether the cell contains an 'O'. The reason for this is that Python sees the 'or' operator and tests if the left hand side is True, which, since it is a string, tests if the string is empty, which it isn't. Python, when given EXPR or EXPR returns the left hand EXPR if it is True, otherwise it returns the right hand expression. Also, since you know that unoccupied cells contain a space, why not test for the cell containing a space, instead of testing that it doesn't contain an 'O' and it doesn't contain an 'X'?, no 'or' operator required? If you must use 'or', then you'd have to write: if gameboard[3] == 'O' or gameboard[3] == 'X': print "This cell is already filled." The next point is the entire user input section. You have a while loop waiting until the game is won, which gets the user input at the top and goes through the entire rest of the code on every user input. It's clearer to handle the user input within a smaller loop which runs forever (while 1:) prompting for input and which uses the 'break' statement to drop out of the loop when the input is valid. If I were writing this myself, I'd probably extract it into a function, simply to separate it from the game playing code. You display the current board with a very lengthy print statement, naming each cell to be printed and surrounding it with individual ']''s. But this is the sort of job computers do well. What you actually want to do is print three lines, one for board[0] through board[2], another for board[3] through board[5] and the last for board[6] through board[8]. print "[%s][%s][%s]" % (board[0], board[1], board[2]) etc. would work in three clearer lines, but we may as well let the computer do the calculation of the indices using a for loop. A final pair of improvements is to not type the [%s] 3 times, nor the name of the board 3 times. We can get the format string using the "" * n notation: '[%s]' * 3 We can get the cells to print as a string slice: tuple(board[r : r + 3]) I leave it to you to find out why the tuple() call is needed. When getting the input, you use the function input(), which sounds reasonable, given the name, but in fact is not at all what you want. This function gets a line of input from the user and evaluates it, returning the result. You could enter '1+2' for the row and Python would return 3. If you type an invalid expression or a letter, Python will terminate your program, which seems a bit drastic. Instead, I used raw_input, which simply gets a string, then checked if the string was one of '1', '2', or '3', using the 'in' operator on the sequence of valid values. While not the sort of validation you'd use in may places, when the number of accptable inputs is this small, the resulting code becomes instantly understandable. You can now type almost anything except control-C and it will not stop the program. After validating the input, you check that the cell is free, but, since you don't have a loop to get the input, you have to reset the player and drop to the bottom of the program just to go back to the main while loop. Keeping all the validation in a single loop you can't leave until you come up with a good location. The final part (and the one you originally asked about) was the pair of if statements you wrote to check if the game had been one. Once again, you misunderstood the logical operators, 'and' in this case. The result of the expression (gameboard[3] and gameboard[4] and gameboard[5]) == 'O' is not a test of whether the three cells all contain 'O', it is a test of whether the first two cells contain a non-empty string _and_ the last cell contains 'O'. Naming the 8 possible ways to win at tictactoe in a single if statement seems wrong. The statment borders on the unreadable. Instead, consider what winning means: you have three identical cells not containing spaces either horizontally ( in board[i], board[i + 1] and board[i +2] for values of i of 0, 3, or 6. Another way of winning is to have three identical non-space cells in a column = board[i], board[i + 3], board[i + 6] for values of i of 0, 1, or 2. The third way to win is to have a diagonal set of three identical non-space cells = board[0], board[4], board[8] or board[2], board[4], board[6] The first two types of wins cry out for a for loop to try the horizontal or vertical wins, with a little simple work, the same for loop over values of 0, 1, 2 can do both types. I'm too lazy to think up a clever way of doing the two diagonals. The actual test looks like: board[i] == board[i + 1] == board[i + 2] and board[i] != ' ' taking advantage of the way Python handles multiple '=='s strung out together ( in effect a == b == c is treated as a == b and b == c ). The resulting rework of the program follows - it's by no means optimal but it's 1/3 the length and, in my opinion, much more readable. It still suffers from having too many while loops depending on break statements, but changing that would require me writing it over from scratch. # TIC TAC TOE # Started: 10/31/05 # Ended: still in progress # There's no need for the variable 'loop' while 1: print "TIC TAC TOE" print "1 - Play Multiplayer" print "2 - Quit" option = raw_input("> ") if option == '2': break if option != '1': continue # MAIN GAME LOOP print "Rules: You will alternate turns." print "On your turn, you can place your letter (O = Player 1 or X = Player 2)", print "in any unoccupied square." print "The first to get 3 in a row wins. Good luck!" board = [' ',' ',' ',' ',' ',' ',' ',' ',' '] turns = 0 player = 0 win = 0 # loop until the board is full while turns < 9: # loop until we have valid input while 1 : print " " print "Player %d" % (player + 1) print " " for r in range(0, 9, 3): print "[%s]" * 3 % tuple(board[r : r + 3]) row = raw_input("Row: ") column = raw_input("Column: ") if row not in ['1', '2', '3' ] or \ column not in ['1', '2', '3']: print "Invalid selection, please try again" continue # convert row and column to array index loc = 3 * (int(row) - 1) + int(column) - 1 if board[loc] == ' ': break print "This cell is already filled." # now we have a valid location, fill it in board[loc] = ['X', 'O'][player] for i in range(3): # check for horizontal win if board[3 * i] == board[ 3 * i + 1] == board[3 * i + 2] and \ board[3 * i] != ' ': win = 1 break if board[i] == board[i + 3] == board[i + 6] and \ board[i] != ' ': win = 1 break else: # no horizontal or vertical win yet # test the diagonals if (board[0] == board[4] == board[8] or board[2] == board[4] == board[6]) and board[4] != ' ': win = 1 if win: break # if we reach here, the game isn't over, flip players turns += 1 player = (player + 1) % 2 # the game has finished if win: print "\nPlayer %d wins!" % player for r in range(0, 9, 3): print "[%s]" * 3 % tuple (board[r : r + 3]) print else: print "Tie" -- Jim Segrave (jes at jes-2.demon.nl) From bokr at oz.net Wed Nov 2 15:12:03 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 02 Nov 2005 20:12:03 GMT Subject: Hexadecimal Conversion in Python References: <1130963306.183112.3720@g49g2000cwa.googlegroups.com> Message-ID: <43691cbd.1643077740@news.oz.net> On 2 Nov 2005 12:28:26 -0800, "DaBeef" wrote: >Hello, I am reading in a socket message from a server and am only >receiving this '....'. Now obviously it is in the wrong format. How >would I convert these bys in Python, I have looked everywhere but I do >not see much documentation on converting ptyhon types to other data >types. >Any Help would be appreciated. > print repr(msg) where msg is what you _actually_ read (and tell us how you got the message in, BTW) and show us a copy/pasted copy from your screen. Unless you are very very good at descriptions, it's hard to beat presentation of machine representations of what you are talking about ;-) Regards, Bengt Richter From mwm at mired.org Mon Nov 7 21:53:03 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 07 Nov 2005 21:53:03 -0500 Subject: how to modify code while debugging it without having to stop and then restart debugger References: Message-ID: <86vez397g0.fsf@bhuda.mired.org> "python" writes: > i am a long time windows user and have had a great way to learn new api. There's a better way. See below. > to write some code and then run it. > if there is an error, the debugger will load. > then i can figure out what the eror is, just touch up the ocde and continue to run the code. > i do not have to stop the code, modify the code, rerun the code. > often an error will only happen after a complex set of conditions and not have to completely stop the app is a fantastic > way to debug. Yup. It's been around for decades. The cooler implementations will interpose a stage that offers you a set of proposed fixes as well as the ability to get to the debugger. > so how can i use python to debug code and change that code without having to restart the code. Well, as James mentioned, you can use "reload" to reload your modules. But in general, this kind of thing doesn't work very well in OO languages in general, and in Python in particular. Here's an example of why: >>> def f(): ... print "Version 1" ... >>> fp = f: >>> def f(): ... print "Version 2" ... >>> f() Version 2 >>> fp() Version 1 >>> I changed the function f on the fly - just like you want to - but all the existing references to it will still refer to the *old* version of the function(*). To do the right thing, you need to fix all the references to the old code to refer to the new code as well. Unless your language has some ability to capture a code reference - first class functions, closures, or objects - that won't be a problem. But Python ha all those things, and every one of them causes problems like this. So you really can't "continue" your program from the debugger; you need to restart it to get everything that references code to reference the edited code. But if the point is to learn an API, then there's something a lot better than tweaking code inside a debugger. That's testing code inside the interpreter. When writing web scraping software with BeautifulSoup, writing the first guess at the scrape sequence and then tweaking it in the debugger would be ok. But being able to get the soup object in the interpreter, and try scrape sequences to see what they return directly is even better. Doing it in an Emacs buffer means I have a complete log of what I did to create the scrape, so I can reconstruct even complicated sequences if the need arises. If you hang out in this group long enough, you'll hear a lot about "unit testing". It's an excellent idea, and I recommend it highly. However, it's always struck me as a very batch oriented approach. A more interactive approach is "exploratory proramming", which is closer to what you're describing, and is appropriate when you don't know the problem space very well, or if - as when learning a new api - you don't know the tool set very well. Python is an excellent tool for this. It's not exactly like what you described, but different isn't necessarily inferior. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dcrespo at gmail.com Fri Nov 18 14:44:27 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 18 Nov 2005 11:44:27 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> Message-ID: <1132343067.439012.121560@g47g2000cwa.googlegroups.com> Oh... Well, thanks for that information. I'll do this then: def TernaryOperation(condition,true_part,false_part): if condition: return True-part else: return False-part a = {'Huge': TernaryOperation(quantity>90,True,False)} Thank you From samrobertsmith at gmail.com Mon Nov 21 07:12:26 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 21 Nov 2005 04:12:26 -0800 Subject: sort the list In-Reply-To: References: Message-ID: <1d987df30511210412x31ea5f58s71e508e35c910a1c@mail.gmail.com> On 11/21/05, Daniel Sch?le wrote: > Shi Mu wrote: > > I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list > > based on the second value in the item? > > That is, > > I want the list to be: > > [[3,2],[1,4],[2,5],[3,9]] > > > >>> lst = [[1,4],[3,9],[2,5],[3,2]] > >>> lst > [[1, 4], [3, 9], [2, 5], [3, 2]] > >>> > >>> > >>> lst.sort(cmp = lambda x,y: cmp(x[1], y[1])) > >>> lst > [[3, 2], [1, 4], [2, 5], [3, 9]] > >>> > > works for Python 2.4 > in earlier Pythons just let cmp = .. away > > Regards, Daniel what does let cmp = .. away mean? From stefan.rank at ofai.at Tue Nov 8 12:34:43 2005 From: stefan.rank at ofai.at (Stefan Rank) Date: Tue, 08 Nov 2005 18:34:43 +0100 Subject: Newbie Alert: Help me store constants pythonically In-Reply-To: <1131468014.050802.12690@g44g2000cwa.googlegroups.com> References: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> <1131468014.050802.12690@g44g2000cwa.googlegroups.com> Message-ID: <4370E1B3.6030404@ofai.at> on 08.11.2005 17:40 Brendan said the following: [snip config/properties file needs] > > I've checked out ConfigParser, ConfigObj, Pickle, PyYaml and > gnossis.xml.serialize, and none meet all the above criteria (though > they're all neat). > > So I've decide to use ...drumroll please.... plistlib ( > http://svn.python.org/projects/python/trunk/Lib/plat-mac/plistlib.py ). like myriads of others, i went through the same dance as you did (several times, several programming languages), and sadly, i did not come across plistlib.py in the python case. as a first glance inspires liking and the lib does not seem to require anything mac-specific, i would like to ask why it is not in the standard python distribution? > So away I go. If anyone can suggest reasons I should avoid this > approach, please let me know before I get too invested. Otherwise, > this might be a reasonable avenue for standardizing Python. > I second that. stefan From steve at REMOVEMEcyber.com.au Mon Nov 7 22:35:09 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 08 Nov 2005 14:35:09 +1100 Subject: PYTHON LOOSING FOR JAVA??????? References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> <1h5o6j6.ikzaeu11af7rpN%aleax@mail.comcast.net> Message-ID: <43701CED.5070105@REMOVEMEcyber.com.au> Alex Martelli wrote: > Since Sun's existing StarOffice supports Python, _and_ Google is well > known as an enthusiastic endorser of Python > (http://www.python.org/Quotes.html etc etc), why would any possible > cooperation between Sun's Office apps, and Google, cause anybody to > _worry_ about "the future of ... Python"?! Taking a leaf from the various publishers and author's guilds out there... Obviously Google is threatening the profitability of programmers and their ability to make a honest day's living. Why would people hire programmers to create new innovative solutions, when they can just use Google to search teh Interweb for source code which Google has stolen from the rightful owners??? *wink* -- Steven. From fredrik at pythonware.com Sun Nov 27 05:51:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Nov 2005 11:51:51 +0100 Subject: Comparison problem References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Actually, it's not so much baroque as it is safe... item[0] will fail if > the string is empty, while item[0:1] will return '' in that case. > > Of course, as you point out, .startswith() is the better approach anyway. $ timeit -s "s = 'abc'" "s[:1] == 'a'" 1000000 loops, best of 3: 0.852 usec per loop $ timeit -s "s = 'abc'; w ='a'" "s[:len(w)] == w" 1000000 loops, best of 3: 1.27 usec per loop $ timeit -s "s = 'abc'; c=s.startswith" "c('a')" 1000000 loops, best of 3: 1.75 usec per loop $ timeit -s "s = 'abc'" "s.startswith('a')" 100000 loops, best of 3: 2.28 usec per loop From deets at nospam.web.de Tue Nov 15 11:40:58 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 Nov 2005 17:40:58 +0100 Subject: Inheritance in nested classes In-Reply-To: References: Message-ID: <3tuhcoFu85g8U1@uni-berlin.de> Martin Skou wrote: > I'm experimenting with using Python for a small web interface, using > Mark Hammond's nice win32 extensions. > > I use a small class hierarchy which uses inheritance and nested classes. > > Here are a small extract of the code: > > class page: > > def __init__(self): > self.head=[] > > def __str__(self): > ... > > class simple_tag: > ... > > class p(simple_tag): > ... > > class table: > ... > > class row: > ... > > class data: > ... > ... > > > Will this type of code perform noticable slower than unnested classes? I'm not aware that there is much runtime penalty here - a quick test reveals that: import time class Foo: def __init__(self, baz): self.baz = baz def unnested(): o = Foo(10) def nested(): class Foo: def __init__(self, baz): self.baz = baz then = time.time() for i in xrange(100000): unnested() print time.time() - then then = time.time() for i in xrange(100000): nested() print time.time() - then Yields 0.839588165283 0.817638158798 for me. But I hope you are aware that nested classes aren't quite the same as they are in java, are you? Regards, Diez From vinjvinj at gmail.com Mon Nov 7 23:43:00 2005 From: vinjvinj at gmail.com (vinjvinj) Date: 7 Nov 2005 20:43:00 -0800 Subject: Using python for writing models: How to run models in restricted python mode? In-Reply-To: <7xy83z232j.fsf@ruckus.brouhaha.com> References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> <1131401624.263258.185730@z14g2000cwz.googlegroups.com> <43700DDB.3020009@REMOVEMEcyber.com.au> <7x4q6nvogt.fsf@ruckus.brouhaha.com> <1131418706.748711.296820@g43g2000cwa.googlegroups.com> <1131422029.740753.144460@o13g2000cwo.googlegroups.com> <7xy83z232j.fsf@ruckus.brouhaha.com> Message-ID: <1131424980.009652.62080@g44g2000cwa.googlegroups.com> This can not be done at compile time but can be cought at execution time on linux by the following recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 vinjvinj From eurleif at ecritters.biz Thu Nov 10 19:50:58 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 11 Nov 2005 00:50:58 GMT Subject: Recompile AST? In-Reply-To: <1131657716.197347.167740@g47g2000cwa.googlegroups.com> References: <1131657716.197347.167740@g47g2000cwa.googlegroups.com> Message-ID: chrisspen at gmail.com wrote: > Is it possible to recompile the AST generated by compiler.parse, back > into code or an executable code object? Into a bytecode object: >>> from compiler.pycodegen import ModuleCodeGenerator >>> from compiler.misc import set_filename >>> from compiler import parse >>> >>> tree = parse('foo = 42') >>> set_filename('', tree) >>> code = ModuleCodeGenerator(tree).getCode() >>> exec code >>> foo 42 Into Python source code: . From finite.automaton at gmail.com Thu Nov 10 13:40:18 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Nov 2005 10:40:18 -0800 Subject: help make it faster please References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> Message-ID: <1131648018.390959.80610@f14g2000cwb.googlegroups.com> You're making a new countDict for each line read from the file... is that what you meant to do? Or are you trying to count word occurrences across the whole file? -- In general, any time string manipulation is going slowly, ask yourself, "Can I use the re module for this?" # disclaimer: untested code. probably contains typos import re word_finder = re.compile('[a-z0-9_]+', re.I) def count_words (string, word_finder = word_finder): # avoid global lookups countDict = {} for match in word_finder.finditer(string): word = match.group(0) countDict[word] = countDict.get(word,0) + 1 return countDict f = open(filename) for i, line in enumerate(f.xreadlines()): countDict = count_words(line) print "Line %s" % i for word in sorted(countDict.keys()): print " %s %s" % (word, countDict[word]) f.close() From bonono at gmail.com Tue Nov 22 23:12:20 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 20:12:20 -0800 Subject: about sort and dictionary In-Reply-To: <1h6g1t6.qxc6tnag2skbN%aleax@mail.comcast.net> References: <1132493880.591426.224140@g49g2000cwa.googlegroups.com> <1132651818.348370.117450@g49g2000cwa.googlegroups.com> <1132653873.855348.265740@g47g2000cwa.googlegroups.com> <1132700747.794586.73170@g44g2000cwa.googlegroups.com> <1h6g1t6.qxc6tnag2skbN%aleax@mail.comcast.net> Message-ID: <1132719140.781847.251410@z14g2000cwz.googlegroups.com> Alex Martelli wrote: > bonono at gmail.com wrote: > ... > > intuitive seems to be a very subjective matter, depends on once > > background etc :-) > > That's a strong point of Ruby, actually -- allowing an exclamation mark > at the end of a method name, which conventionally is always used to > indicate that the method is a mutator. So, you can have a.reverse [NOT > mutating a since no !] _and_ a.reverse! [mutating a]. Probably too much > of a change even for Python 3000, alas... but, it DOES make it obvious > when an object's getting mutated, and when not... > And I doubt if it should be added because of the history of python. As that would effectively mean changing the meaning of a function because of version, where old codes means differently for people who learn the new syntax. From stefan.kanev at gmail.com Thu Nov 3 04:26:40 2005 From: stefan.kanev at gmail.com (Aquarius) Date: 3 Nov 2005 01:26:40 -0800 Subject: Python and MySQL In-Reply-To: References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: <1131006108.832085.216500@g44g2000cwa.googlegroups.com> I am also have _mysql.c that has to be compiled. I downloaded 1.2.0 from here http://sourceforge.net/project/showfiles.php?group_id=22307&package_id=15775 (the .tar.gz). Do you mean, that if I drop the import _mysql and from _mysql import ... lines everything will work OK? I "private install" would be great for me, if it works :D From bonono at gmail.com Wed Nov 23 23:38:58 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 20:38:58 -0800 Subject: Python as Guido Intended In-Reply-To: <86u0e2zmwb.fsf@bhuda.mired.org> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1132800973.008501.34090@g14g2000cwa.googlegroups.com> <867jay1ybk.fsf@bhuda.mired.org> <1132805759.799632.265850@f14g2000cwb.googlegroups.com> <86u0e2zmwb.fsf@bhuda.mired.org> Message-ID: <1132807138.648558.234880@g47g2000cwa.googlegroups.com> Mike Meyer wrote: > "bonono at gmail.com" writes: > >> Maybe Python attracts people who share that belief. After all, TRTFTJ > >> is implies TSBOOWTDI, and vice versa. > > I was not talking about the believe, I was talking about the way you > > presented it. You are setting up an "imaginary" me, which is not me. > > And that is the kind of arguments I saw, I believe this many times are > > done unconciously. > > You're doing that yourself. But we don't have a real other person to > work with - the best we can do is work with our model of that other > person. That's life. > In what way am I doing it myself ? It could be unconciously too but I always welcome if it could be pointed out. From pythonnew at gmail.com Sat Nov 12 23:51:04 2005 From: pythonnew at gmail.com (Ben Bush) Date: Sat, 12 Nov 2005 20:51:04 -0800 Subject: circle and point Message-ID: <8c11e4350511122051hc4ae8b9tc4ef54818ba44318@mail.gmail.com> is there any code to decide whether a point is located within the circle by three other points? Thanks! B. Bush -------------- next part -------------- An HTML attachment was scrubbed... URL: From stygian at tesco.net Mon Nov 28 14:10:05 2005 From: stygian at tesco.net (Glen) Date: Mon, 28 Nov 2005 19:10:05 +0000 Subject: How to stop a linux process Message-ID: When I used the following line to play a midi file in linux, return_value = os.system('timidity test.mid') I have encountered two problems. 1. The python script halts until timidity has finished. 2. If I had control of the script, I can't think how I would stop timidity. Any advice on the 'area' of python I should be looking at would be greatly appreciated. Thanks. From aleax at mail.comcast.net Fri Nov 11 21:38:28 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 11 Nov 2005 18:38:28 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> <1131517112.247477.35030@g14g2000cwa.googlegroups.com> <1h5rxho.nxmo0z15zne5jN%aleax@mail.comcast.net> <1h5su7m.vwmk96qm9qplN%aleax@mail.comcast.net> <1131690799.409160.36930@g49g2000cwa.googlegroups.com> <1h5up32.1fa670mkz6a6bN%aleax@mail.comcast.net> Message-ID: <1h5vkwi.t1jopc1cgx7nfN%aleax@mail.comcast.net> David Gutierrez wrote: > Include me in your list, please. Uh, what list? If you mean gmpy-commits, you subscribe to it on gmpy.sf.net -- if you mean the general Python list, on www.python.org. Alex From mwm at mired.org Thu Nov 24 03:14:49 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 03:14:49 -0500 Subject: wxPython Licence vs GPL References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> Message-ID: <86hda2zcli.fsf@bhuda.mired.org> "bonono at gmail.com" writes: > Steve Holden wrote: >> Whether or not some fragments of code remain unchanged at the end of >> your project, if you start out with a piece of source code lifted from >> wxPython then what you have created is definitely a "derivative work" >> and, as such, you must take into account the wxPython license in your >> licensing of the derivative work. > Is that true ? What if I remove/replace the copyright doubtful portion > with another implementation ? I believe this happens all the time in > commerical software sue too. In general, if you can show you removed all the licensed code that was in your code, and replaced it with software from another source, you're cool. That's how the BSD distributions came about - Berkeley's Computer Systems Research Group rewrote pretty much all of Unix. However, you're still liable to be sued. CSRG was, which is part of why BSD languished while Linux was taking off. It's also why the previous paragraph is a gross oversimplification. The court case didn't establish a real precedent, as it turned out AT&T was distributing code that belonged to CSRG in violation of the BSD license. So they reached a settlement in which CSRG was allowed to distribute a tape that had most of a Unix sytem on it, a few key files that AT&T claimed as their own being withheld. This is the "BSD Lite" distribution that the *BSD systems and parts of OS X are based on. All this backstory made the SCO barratry much more entertaining. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From everettcc at hotmail.com Tue Nov 15 23:21:29 2005 From: everettcc at hotmail.com (Chad Everett) Date: Tue, 15 Nov 2005 22:21:29 -0600 Subject: Newb ? References: <3tvpqaFv0q48U1@individual.net> Message-ID: "Paul Watson" wrote in message news:3tvpqaFv0q48U1 at individual.net... > Chad Everett wrote: >> Hello all, >> >> Have a problem here with a challenge from a book I am reading. >> Any help is much appreciated. >> >> I am trying to run a program that asks the user for a statement and then >> prints it out backwards. >> this is what I have. >> It does not print anything out. I assume that I have something out of >> whack with my high and low statements. >> >> Thanks for you help. >> >> >> print "\n\nWelcome to the Backwards Message Display." >> print >> message = raw_input("\nPlease Enter a Message.") >> >> high = len(message) >> low = -len(message) >> print >> print message[high:low] >> print >> print raw_input("Please Press Enter to Exit") > > Are you sure that this is not a class assignment? You can search the > messages here for the answer. No, I have been out of school way too long. I am 34 trying to learn a new trade. I searched the group for the term backwards but I did not get any results. From simon.brunning at gmail.com Tue Nov 8 05:54:57 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 8 Nov 2005 10:54:57 +0000 Subject: what the %?.... In-Reply-To: <20051107200405.25840.qmail@web35905.mail.mud.yahoo.com> References: <20051107200405.25840.qmail@web35905.mail.mud.yahoo.com> Message-ID: <8c7f10c60511080254p6ff058bck@mail.gmail.com> On 07/11/05, john boy wrote: > Hey can somebody tell me what the "%" function does...I am not math > illiterate...its just a new symbol for me....is it a divisor? remainder > something another?? For numeric values, it's the modulo operator - see and . Over strings, '%' performs string formatting. See . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From mwm at mired.org Tue Nov 1 15:28:37 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 01 Nov 2005 15:28:37 -0500 Subject: Xah's edu corner: the Journey of Foreign Characters thru Internet References: <1130852975.525590.145080@f14g2000cwb.googlegroups.com> <1130874345.236356.248110@g14g2000cwa.googlegroups.com> Message-ID: <86d5lk15ai.fsf@bhuda.mired.org> svenn.are at bjerkem.de writes: > Interesting opinions this man has, I must say. A Sith of Computing he > may be? No. Sith are competent but evil. Xah Leh is incompetent, but apparently well-intentioned. Some of his opinions are correct, but that appears to be more by accident than anything else, and there's no easy way to distinguish those from his usual work. He has been accurately described as "stupider than spam". Please help Google find him that way by adding an appropriater link to your web site: stupider than spam http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From iddw at hotmail.com Fri Nov 18 18:48:28 2005 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 18 Nov 2005 17:48:28 -0600 Subject: How to do "new_variable = (variable) ? True : False; " (php) on python? References: <1132338596.452441.139200@g44g2000cwa.googlegroups.com> <437e50f6$1@nntp0.pdx.net> Message-ID: On Fri, 18 Nov 2005 14:15:06 -0800 in comp.lang.python, Scott David Daniels wrote: > > >Don't try to force everything to the type you expect, >use things as they are; embrace duck-typing. > Wrong, the grammar you have. Do not Everything to the type you expect force. Do or do not, there is no try. Things as they are use. Duck-typing embrace. >:-) Ditto. Regards, -=Dave -- Change is inevitable, progress is not. From uche.ogbuji at gmail.com Tue Nov 29 10:56:35 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 29 Nov 2005 07:56:35 -0800 Subject: Move xml.sax.saxutils.*? In-Reply-To: <1132949881.719999.162010@g44g2000cwa.googlegroups.com> References: <1132949881.719999.162010@g44g2000cwa.googlegroups.com> Message-ID: <1133279795.036940.91610@g44g2000cwa.googlegroups.com> """ It seems like functions such as xml.sax.saxutils.escape and unescape are generally useful, and not at all tied to the xml.sax module. Would it make sense to move them somewhere else, like to xml? """ It would be useful to allow from xml import escape, unescape But as an alias, rather than a replacement for the current import. -- 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 mwm at mired.org Sun Nov 20 03:39:51 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 20 Nov 2005 03:39:51 -0500 Subject: Where can I find string.translate source? References: <1132472291.390282.82380@g43g2000cwa.googlegroups.com> Message-ID: <86lkzjhfvs.fsf@bhuda.mired.org> bobueland at yahoo.com writes: > Inside the file string.py I couldn't find the source code for > translate. Where could it be? Object/stringmodule.c in the python source distribution. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From suma_37 at yahoo.com Wed Nov 9 05:46:24 2005 From: suma_37 at yahoo.com (sumi) Date: 9 Nov 2005 02:46:24 -0800 Subject: Hi, from my login i want to login as a other user , Message-ID: <1131533184.096101.49940@g49g2000cwa.googlegroups.com> Hi, from my login i want to login as a other user , how can i do it using python. From juho.schultz at helsinki.fi Wed Nov 2 10:20:11 2005 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Wed, 02 Nov 2005 17:20:11 +0200 Subject: * TypeError - Need help passings args In-Reply-To: <1130944044.311979.145660@g49g2000cwa.googlegroups.com> References: <1130944044.311979.145660@g49g2000cwa.googlegroups.com> Message-ID: Ernesto wrote: > My program is below. I'm trying to use two Windows ".exe" files with > my command line python interface. I get user input, then call > "launchWithoutConsole". This was working OK until I introduced the > 'args' part. Now I get the following error everytime I call > "launchWithoutConsole": > > return subprocess.Popen([command] + args, > startupinfo=startupinfo).wait() > > TypeError: can only concatenate list (not "str") to list > > I'm not sure if it's the WAY I'm passing it or if it's the function > itself (which I retrieved from > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409002 > ) > > Please help. Thanks! > [command] is a list. So also "args" should be a list, otherwise [command] + args produces an error. Add a few square brackets to the calls, just like in the link. From bhv1 at psu.edu Wed Nov 23 13:56:04 2005 From: bhv1 at psu.edu (Brian Victor) Date: Wed, 23 Nov 2005 18:56:04 GMT Subject: python gui using boa References: <1132637738.473190.311620@g43g2000cwa.googlegroups.com> <1132771693.777165.63860@g43g2000cwa.googlegroups.com> Message-ID: ash wrote: > Thanks Steve, i found out the solution to the problem. but a good > tutorial on sizers is still missing. Try this article I wrote a while back. It should at least help you get started. The code samples are written in C++, but they are trivially translated to python. (Change -> to ., change this to self, get rid of "new" and *) http://neume.sourceforge.net/sizerdemo/ -- Brian From steve at REMOVEMEcyber.com.au Sun Nov 20 23:15:18 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 21 Nov 2005 15:15:18 +1100 Subject: Aproximative string matching References: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> <1132543801.861940.146530@g43g2000cwa.googlegroups.com> Message-ID: <438149D6.5090403@REMOVEMEcyber.com.au> elbertlev at hotmail.com wrote: > This algorithm is called soundex. Here is one implementation example. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52213 > > here is another: > http://effbot.org/librarybook/soundex.htm Soundex is *one* particular algorithm for approximate string matching. It is optimised for matching Anglo-American names (like Smith/Smythe), and is considered to be quite old and obsolete for all but the most trivial applications -- or so I'm told. Soundex will not match arbitrary changes -- it will match both cat and cet, but it won't match cat and mat. A more sophisticated approximate string matching algorithm will use the Levenshtein distance. You can find a Useless implementation here: http://www.uselesspython.com/download.php?script_id=108 Given a function levenshtein(s1, s2) that returns the distance between two strings, you could use it for approximate matching like this: def approx_matching(strlist, target, dist=1): """Matches approximately strings in strlist to a target string. Returns a list of strings, where each string matched is no further than an edit distance of dist from the target. """ found = [] for s in strlist: if levenshtein(s, target) <= dist: found.append(s) return s -- Steven. From dewclaws at gmail.com Wed Nov 23 01:32:59 2005 From: dewclaws at gmail.com (Rsrany) Date: 22 Nov 2005 22:32:59 -0800 Subject: Problems with threaded Hotkey application Message-ID: <1132727579.268059.60120@g47g2000cwa.googlegroups.com> I've been working on a few gtk applications and need to tie a hot key catcher into a thread. I am currently finding threaded user32.GetMessageA do not work. I have included two programs: 1) a non-threaded version that works 2) a threaded version that doesnt work. Any constructive suggestions would be helpful ######################################################### Working non-threaded version: ######################################################### import sys from ctypes import * from ctypes.wintypes import * # Define the Windows DLLs, constants and types that we need. user32 = windll.user32 WM_HOTKEY = 0x0312 MOD_ALT = 0x0001 MOD_CONTROL = 0x0002 MOD_SHIFT = 0x0004 class MSG(Structure): _fields_ = [('hwnd', c_int), ('message', c_uint), ('wParam', c_int), ('lParam', c_int), ('time', c_int), ('pt', POINT)] # Register a hotkey for Ctrl+Shift+P. hotkeyId = 1 if not user32.RegisterHotKey(None, hotkeyId, MOD_CONTROL | MOD_SHIFT, ord('P')): sys.exit("Failed to register hotkey; maybe someone else registered it?") # Spin a message loop waiting for WM_HOTKEY. while 1 : msg = MSG() while user32.GetMessageA(byref(msg), None, 0, 0) != 0: if msg.message == WM_HOTKEY and msg.wParam == hotkeyId: print "Yay" windll.user32.PostQuitMessage(0) user32.TranslateMessage(byref(msg)) user32.DispatchMessageA(byref(msg)) ################################################# And here is the Non Working Threaded version : ################################################# import sys from ctypes import * from ctypes.wintypes import * import threading # Define the Windows DLLs, constants and types that we need. user32 = windll.user32 WM_HOTKEY = 0x0312 MOD_ALT = 0x0001 MOD_CONTROL = 0x0002 MOD_SHIFT = 0x0004 class MSG(Structure): _fields_ = [('hwnd', c_int), ('message', c_uint), ('wParam', c_int), ('lParam', c_int), ('time', c_int), ('pt', POINT)] # Register a hotkey for Ctrl+Shift+P. hotkeyId = 1 if not user32.RegisterHotKey(None, hotkeyId, MOD_CONTROL | MOD_SHIFT, ord('P')): sys.exit("Failed to register hotkey; maybe someone else registered it?") class KeyCatch(threading.Thread): def run(self): print "TESTING TO MAKE SURE THREAD IS RUNNING!" # Spin a message loop waiting for WM_HOTKEY. while 1 : msg = MSG() while user32.GetMessageA(byref(msg), None, 0, 0) != 0: if msg.message == WM_HOTKEY and msg.wParam == hotkeyId: print "Yay" windll.user32.PostQuitMessage(0) user32.TranslateMessage(byref(msg)) user32.DispatchMessageA(byref(msg)) GetKey = KeyCatch() GetKey.start() while 1: pass From samrobertsmith at gmail.com Sat Nov 12 05:52:21 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 02:52:21 -0800 Subject: about array,arange Message-ID: <1d987df30511120252w3b07b187l71db482bffe35a11@mail.gmail.com> i got confused by the use of array and arange. arange get array and range get list, why we need the two different types? From rurpy at yahoo.com Tue Nov 22 12:01:15 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 22 Nov 2005 09:01:15 -0800 Subject: examining python objects References: <1132339687.048155.252160@g47g2000cwa.googlegroups.com> <437ef75a$0$32754$626a14ce@news.free.fr> <1132413271.287391.66790@g43g2000cwa.googlegroups.com> Message-ID: <1132678875.457219.46900@g49g2000cwa.googlegroups.com> Colin J. Williams wrote: > rurpy at yahoo.com wrote: > > Bruno Desthuilliers wrote: > > > >>rurpy at yahoo.com a ?crit : > >> > >>>Is there a function/class/module/whatever I can use to > >>>look at objects? I want something that will print the object's > >>>value (if any) in pretty-printed form, and list all it's attributes > >>>and their values. And do all that recursively. > >>>I want to be able to find out everything about an object that > >>>Python can introspectively find out. > >> > >>Then check the inspect module > > > > > > I want a callable, ready-to-use class or function. > > Inspect provides soime funtions that would be useful for wrinting > > such a class or function, but does not provide one. > > > > I seems that nobody who has written or used such a tool reads > > this group, or feels like responding. > > > > FWIW, (for anyone looking for something similar in the future) > > I found http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/137951 > > which will format and print an object's attributes. By combining that > > and pprint in the Python distrib, I think can coble up what I am > > looking > > for. > > > > Still, it is discouraging that such a basic thing is not provided with > > python, or at lleast easily available in some library. > > > In the interactive mode, you might try >> help(object) I want all the information about the object I can get through introspection. help() give some (a lot more than I realized, so thanks) but not everything. From bignose+hates-spam at benfinney.id.au Tue Nov 15 17:55:17 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Nov 2005 09:55:17 +1100 (EST) Subject: Shutdown hook References: <1132094726.985460.97110@g14g2000cwa.googlegroups.com> Message-ID: Steve wrote: > Does any one know if python has the ability to run a shutdown hook. When the Python runtime system wants to exit, it raises a SystemExit exception. Catch that exception at the top level of your code, and do whatever you like. (It might be polite to actually exit at some point, of course. sys.exit(exitcode) will do so -- raising another SystemExit exception.) -- \ "I took it easy today. I just pretty much layed around in my | `\ underwear all day. ... Got kicked out of quite a few places, | _o__) though." -- Bug-Eyed Earl, _Red Meat_ | Ben Finney From tim.leeuwvander at nl.unisys.com Sun Nov 27 12:16:27 2005 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 27 Nov 2005 09:16:27 -0800 Subject: Estimating memory use? In-Reply-To: References: Message-ID: <1133111787.251543.325140@g44g2000cwa.googlegroups.com> Hi, What is your 'static' data (database), and what is your input-data? Those 200.000 probes are your database? Perhaps they can be stored as pickled compiled regexes and thus be loaded in pickled form; then you don't need to keep them all in memory at once -- if you fear that memory usage will be too big. I don't know if perhaps other string-matching techniques can be used btw; you don't need the full power of regexes I guess to match DNA string patterns. Perhaps you should investigate that a bit, and do some performance tests? cheers, --Tim From trepca at gmail.com Tue Nov 22 12:56:54 2005 From: trepca at gmail.com (Sebastjan Trepca) Date: Tue, 22 Nov 2005 18:56:54 +0100 Subject: Dictionary string parser In-Reply-To: References: Message-ID: Wow, this helps a LOT! It's just what I needed, thank you very much! :) Sebastjan On 22/11/05, Fredrik Lundh wrote: > Sebastjan Trepca wrote: > > > is there any library or some way to parse dictionary string with list, > > string and int objects into a real Python dictionary? > > > > For example: > > > > >>> my_dict = dict_parser("{'test':'123','hehe':['hooray',1]}") > > > > I could use eval() but it's not very fast nor secure. > > it's definitely slower than eval (which is written in C, after all), but it's > definitely more limited, and hopefully also more secure: > > import cStringIO > import tokenize > > def _parse(token, src): > if token[1] == "{": > out = {} > token = src.next() > while token[1] != "}": > key = _parse(token, src) > token = src.next() > if token[1] != ":": > raise SyntaxError("malformed dictionary") > value = _parse(src.next(), src) > out[key] = value > token = src.next() > if token[1] == ",": > token = src.next() > return out > elif token[1] == "[": > out = [] > token = src.next() > while token[1] != "]": > out.append(_parse(token, src)) > token = src.next() > if token[1] == ",": > token = src.next() > return out > elif token[0] == tokenize.STRING: > return token[1][1:-1].decode("string-escape") > elif token[0] == tokenize.NUMBER: > try: > return int(token[1], 0) > except ValueError: > return float(token[1]) > else: > raise SyntaxError("malformed expression") > > def myeval(source): > src = cStringIO.StringIO(source).readline > src = tokenize.generate_tokens(src) > return _parse(src.next(), src) > > print myeval("{'test':'123','hehe':['hooray',0x10]}") > {'test': '123', 'hehe': ['hooray', 16]} > > hope this helps! > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.kern at gmail.com Wed Nov 9 07:47:18 2005 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 Nov 2005 04:47:18 -0800 Subject: triangulation In-Reply-To: <1d987df30511090414m1864e236jdcd51e58a1d153ab@mail.gmail.com> References: <1d987df30511090414m1864e236jdcd51e58a1d153ab@mail.gmail.com> Message-ID: Shi Mu wrote: > is there any sample code to triangulation? many thanks! Triangulation of what? Scattered points in a plane? 2D manifolds embedded in a 3D space? Delaunay triangulations? Constrained triangulations? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bokr at oz.net Sun Nov 6 16:19:15 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 06 Nov 2005 21:19:15 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <436c2709.154756898@news.oz.net> Message-ID: <436e631b.301206381@news.oz.net> On Sun, 06 Nov 2005 12:23:02 -0500, Christopher Subich wrote: >Bengt Richter wrote: >> On Fri, 04 Nov 2005 10:28:52 -0500, Christopher Subich wrote: > >>>is very much within the language specification. Indeed, the language >>>specification dictates that an instance variable b.a is created if one >>>didn't exist before; this is true no matter if type(b.a) == int, or if >>>b.a is some esoteric mutable object that just happens to define >>>__iadd__(self,type(other) == int). >> >> But if it is an esoteric descriptor (or even a simple property, which is >> a descriptor), the behaviour will depend on the descriptor, and an instance >> variable can be created or not, as desired, along with any side effect you like. > >Right, and that's also language-specification. Voodoo, yes, but >language specification nonetheless. :) I guess http://docs.python.org/ref/augassign.html is the spec. I notice its example at the end uses an old-style class, so maybe it's understandable that when it talks about getattr/setattr, it doesn't mention the possible role of descriptors, nor narrow the meaning of "evaluate once" for a.x to exclude type(a).x in the setattr phase of execution. I.e., if x is a descriptor, "evaluate" apparently means only type(a).x.__get__(a, type(a)) since that is semantically getting the value behind x, and so both of the ".x"s in type(a).x.__set__(a, type(a).x.__get__(a, type(a)).__add__(1)) # (or __iadd__ if defined, I think ;-) don't count as "evaluation" of the "target" x, even though it means that a.x got evaluated twice (via getattr and setattr, to get the same descriptor object (which was used two different ways)). I think the normal, non-descriptor case still results in (optimized) probes for type(a).x.__get__ and type(a).x.__set__ before using a.__dict__['x']. ISTM also that it's not clear that defining __iadd__ does _not_ prevent the setattr phase from going ahead. I.e., a successful __iadd__ in-place mutation does not happen "instead" of the setattr. Regards, Bengt Richter From tim.golden at viacom-outdoor.co.uk Thu Nov 10 04:29:54 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 10 Nov 2005 09:29:54 -0000 Subject: Looking Python script to compare two files Message-ID: <9A28C052FF32734DACB0A288A3533991044D230B@vogbs009.gb.vo.local> [david] > I want to compare PDF-PDF files and WORD-WORD files. OK. Well, that's clear enough. > It seems that the right way is : > First, extract text from PDF file or Word file. > Then, use Difflib to compare these text files. When you say "it seems that the right way is..." I'll assume that this way meets your requirements. It wouldn't be the right way if, for example, you wanted to treat different header levels as different, or to consider embedded graphics as significant etc. > Would you please give me some more information > about the external diff tools? Well, I could mention the name of the ones which I might use (WinMerge and GNU diff), but I'm sure there are many of then around the place, and you're far better off doing this: http://www.google.co.uk/search?q=diff+tools In case you didn't realise, the "difflib" I referred to is a Python module from the standard library: Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import difflib >>> `difflib` "" >>> > There some Python scripts that can extract text > from PDF or WORD file? Well, I'm sure there are, but my honest opinion is that, unless you've got some compelling reason to do this in Python, you're better off using, say: + antiword: http://www.winfield.demon.nl/ + pdf2text from xpdf: http://www.foolabs.com/xpdf/home.html If you really wanted to go with Python (for the learning experience, if nothing else) then the most obvious candidates are: + Word: use the pywin32 modules to automate Word and save the document as text: http://pywin32.sf.net/ Something like this (assumes doc called c:\temp\test.doc exists): import win32com.client word = win32com.client.gencache.EnsureDispatch ("Word.Application") doc = word.Documents.Open (FileName="c:/temp/test.doc") doc.SaveAs (FileName="c:/temp/test2.txt", FileFormat=win32com.client.constants.wdFormatText) word.Quit () del word text = open ("c:/temp/test2.txt").read () print text + PDF: David Boddie's pdftools looks like about the only possibility: (ducks as a thousand people jump on him and point out the alternatives) http://www.boddie.org.uk/david/Projects/Python/pdftools/ Something like this might do the business. I'm afraid I've no idea how to determine where the line-breaks are. This was the first time I'd used pdftools, and the fact that I could do this much is a credit to its usability! from pdftools.pdffile import PDFDocument from pdftools.pdftext import Text def contents_to_text (contents): for item in contents: if isinstance (item, type ([])): for i in contents_to_text (item): yield i elif isinstance (item, Text): yield item.text doc = PDFDocument ("c:/temp/test.pdf") n_pages = doc.count_pages () text = [] for n_page in range (1, n_pages+1): print "Page", n_page page = doc.read_page (n_page) contents = page.read_contents ().contents text.extend (contents_to_text (contents)) print "".join (text) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From noway at sorry.com Thu Nov 24 20:29:13 2005 From: noway at sorry.com (Giovanni Bajo) Date: Fri, 25 Nov 2005 01:29:13 GMT Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> <871x15vcdc.fsf@lucien.dreaming> <86u0e1va6q.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: >> Bj?rn Lindstr?m wrote: >> Why do you think we have a frozenset, for instance? By Mike's >> argument, we shouldn't have it. > > Not *my* arguments, certainly. Not unless you're seriously > misinterpreting them. Sorry then, I probably am. There must be a misunderstanding somewhere. What is your position about frozenset? By my understanding of your arguments, it is a hand-cuffed version of set, which just prevents bugs that could still be caught by testing. The same applies for the arbitrary restriction of not allowing sets to be key dictionaries (with their hash value being their id). -- Giovanni Bajo From ark at acm.org Tue Nov 29 12:47:29 2005 From: ark at acm.org (Andrew Koenig) Date: Tue, 29 Nov 2005 17:47:29 GMT Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com><1133041306.601950.213710@g43g2000cwa.googlegroups.com> Message-ID: "Robert Kern" wrote in message news:mailman.1248.1133119309.18701.python-list at python.org... > Andrew Koenig wrote: >> I'm pretty sure that there was a change to the copyright laws a few years >> ago (perhaps as part of the DMCA), that made it clear that you own >> everything you produce, unless you're a W-2 employee or there is a >> written >> agreement to the contrary. > > The US Copyright Office does not agree with you. > > http://www.copyright.gov/circs/circ09.pdf Well, it comes pretty close to agreeing with me--the only issue is whether the definition of "employee" extends beyond the notion of "W-2 employee" and that issue is not really relevant to the original posting. Here's the relevant quote: If a work is created by an employee, part 1 of the statutory definition applies, and generally the work would be considered a work made for hire. Important: The term "employee" here is not really the same as the common understanding of the term; for copyright purposes, it means an employee under the general common law of agency. This is explained in further detail below. Please read about this at "Employer-Employee Relationship Under Agency Law." If a work is created by an independent contractor (that is, someone who is not an employee under the general common law of agency), then the work is a specially ordered or commissioned work, and part 2 of the statutory definition applies. Such a work can be a work made for hire only if both of the following conditions are met: (1) it comes within one of the nine categories of works listed in part 2 of the definition and (2) there is a written agreement between the parties specifying that the work is a work made for hire. The reason I say that the distinction between W-2 employment and agency employment isn't really relevant is that in the kind of situation we're talking about, there is generally a written agreement specifying scope and nature of work. So I'll amend my statement slightly: If someone pays you to produce a specific piece of work, or you're an employee, any work you do for hire belongs to your employer. Otherwise, it's yours unless there's a written agreement to the contrary. I think that's a fair paraphrase of the paragraph I cited. If you disagree, please say why. From javuchi at gmail.com Tue Nov 22 20:58:28 2005 From: javuchi at gmail.com (javuchi) Date: 22 Nov 2005 17:58:28 -0800 Subject: Anyway to clarify this code? (dictionaries) Message-ID: <1132711108.860281.59900@g49g2000cwa.googlegroups.com> I've been searching thru the library documentation, and this is the best code I can produce for this alogorithm: I'd like to return a dictionary which is a copy of 'another' dictionary whoes values are bigger than 'x' and has the keys 'keys': def my_search (another, keys, x): temp = another.fromkeys(keys) return dict([[k,v] for k in temp.keys() for v in temp.values() if v>=x]) Is there any way to improve this code? I want to avoid converting the dictionary to a list and then to a dictionay. Are there speed penalties for such a conversion? Bye. From deets at nospam.web.de Wed Nov 23 18:11:12 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Nov 2005 00:11:12 +0100 Subject: Mixed types and variants In-Reply-To: <1132781170.172321.321750@z14g2000cwz.googlegroups.com> References: <1132781170.172321.321750@z14g2000cwz.googlegroups.com> Message-ID: <3ukb8gF11ov5tU1@uni-berlin.de> > If this is not possible, such variants don't look very useful in > general for SS. > > My possible answers: > - "Value" types only can be better than nothing, because such variants > can be used to make mixed dicts, those mixed lists, etc. Some > functionality reduction is better than an even bigger functionality > reduction. > - Maybe the boost::variant sourcecode can be modified to allow such > functionality too, or part of it. But this may require a LOT of work on > the C++ implementation (Mark's idea: maybe a better solution would be > to fall back to CPython classes somehow to implement variants...). > - Maybe someone here can suggest some other variant type, or some other > solution. The problem is that C++ has no means of a dynamic method invocation. So I guess the only thing that helps is to use some variant that has a PyObject-type, and where calls on values of that type are basically translated to python C-Api calls, delegating the execution to python itself. Problem: return types aren't known - either handle them as PyObjects, or have some cast/hinting in place that reduces them to known native types like uniform lists. my .2? Diez From mwm at mired.org Thu Nov 17 23:27:45 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Nov 2005 23:27:45 -0500 Subject: Importing a class without knowing the module References: <867jb6n7cw.fsf@bhuda.mired.org> <86veyqlnrn.fsf@bhuda.mired.org> <1h66rw8.wlp7nb19e5629N%aleax@mail.comcast.net> Message-ID: <86k6f6lgvy.fsf@bhuda.mired.org> aleax at mail.comcast.net (Alex Martelli) writes: > Mike Meyer wrote: >> >> How about adding Foo.__file__ to the serialized data? >> > I thought about it, but it would make the XML file depend on the >> > machine... no more portability... >> They already depend on the machine. You can't take them to an arbitary >> machine and reconstruct them: it has to have the classes the XML file >> depends on somewhere on it. You can use the module name if you have it >> available. If not, deriving the module name from the file name is >> about the best you can do. > I disagree with the last sentence. From a filepath of > '/zip/zap/zop/zup.py', it's VERY hard to say whether the module name is > to be zup, zop.zup, or zap.zop.zup -- it depends on which directories > are on sys.path and which have __init__.py, which is impossible to tell > at unmarshaling time. If you use Foo.__module__, you should get the > *module* name correctly, independently from sys.path or __init__.py's, > or .pth files for that matter -- so, I do NOT agree that using __file__ > is "about the best you can do" for this use case. You should read the next-to-last sentence, which says to use the module name if you have it. The last sentence starts "If not" - meaning you don't have the module name. *That's* the case for which the file name is about the best you can do. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fredrik at pythonware.com Tue Nov 8 04:36:53 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Nov 2005 10:36:53 +0100 Subject: image References: <1d987df30511080018h1111aaa0t79e885438f8e2956@mail.gmail.com> Message-ID: > > File "C:\Python23\lib\lib-tk\Tkinter.py", line 2882, in image_create > > return self.tk.call( > > TclError: image "pyimage4" doesn't exist > > works for me, when running it from a stock CPython interpreter. > > have you tried running the script outside the pywin environment? btw, the error message indicates that the problem is that PythonWin doesn't clean things up between runs, so you end up creating new Tk objects every time you try the script. but when you call PhotoImage, it uses the default root window (which was created the first time you called Tk), so you get back an image that's associated with another Tk instance. it's really an issue with PythonWin, but if you cannot switch to an IDE that runs your scripts in a separate process, you can work around the problem by passing in an explicit master to the PhotoImage factory: photo=PhotoImage(file='...', master=root) From randall_burns at hotmail.com Thu Nov 3 17:40:57 2005 From: randall_burns at hotmail.com (randall_burns at hotmail.com) Date: 3 Nov 2005 14:40:57 -0800 Subject: Python Framework that works with IIS/SQL Server? Message-ID: <1131057657.036689.170840@g47g2000cwa.googlegroups.com> I'd like to find a web framework that works with IIS and SQL Server on Windows(I know-but I didn't make that decision). Anyhow, I've looked at Turbogears, Django, subway and didn't see any evidence that anyone had made these work in that configuration. Any suggestions? From bokr at oz.net Fri Nov 4 21:11:51 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 05 Nov 2005 02:11:51 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <86irv8hg74.fsf@bhuda.mired.org> Message-ID: <436c0f2c.148647453@news.oz.net> On 4 Nov 2005 11:09:36 GMT, Antoon Pardon wrote: [...] > >Take the code: > > lst[f()] += 1 > >Now let f be a function with a side effect, that in succession >produces the positive integers starting with one. > >What do you think this should be equivallent to: > > t = f() > lst[t] = lst[t] + 1 > >or > > lst[f()] = lst[f()] + 1 > >If you think the environment can change between references then I >suppose you prefer the second approach. > I am quite sympathetic to your probe of python semantics, but I don't think the above is an argument that should be translated to attribute assignment. BTW, ISTM that augassign (+=) is a red herring here, since it's easy to make a shared class variable that is augassigned apparently as you want, e.g., >>> class shared(object): ... def __init__(self, v=0): self.v=v ... def __get__(self, *any): return self.v ... def __set__(self, _, v): self.v = v ... >>> class B(object): ... a = shared(1) ... >>> b=B() >>> b.a 1 >>> B.a 1 >>> b.a += 2 >>> b.a 3 >>> B.a 3 >>> vars(b) {} >>> vars(b)['a'] = 'instance attr' >>> vars(b) {'a': 'instance attr'} >>> b.a 3 >>> b.a += 100 >>> b.a 103 >>> B.a 103 >>> B.a = 'this could be prevented' >>> b.a 'instance attr' >>> B.a 'this could be prevented' The spelled out attribute update works too >>> B.a = shared('alpha') >>> b.a 'alpha' >>> b.a = b.a + ' beta' >>> b.a 'alpha beta' >>> B.a 'alpha beta' But the instance attribute we forced is still there >>> vars(b) {'a': 'instance attr'} You could have shared define __add__ and __iadd__ and __radd__ also, for confusion to taste ;-) Regards, Bengt Richter From luca.tavoletti at gmail.com Tue Nov 29 14:54:16 2005 From: luca.tavoletti at gmail.com (lux) Date: 29 Nov 2005 11:54:16 -0800 Subject: wxGrid and Focus Event References: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> <438CACF1.1020909@ulmcnett.com> Message-ID: <1133294056.952406.108890@g44g2000cwa.googlegroups.com> Can you try this code? If you press only the TAB key the focus go from the TextCtrl to the Grid (I suppose) but onGridFocus in not called. any idea? Luca. ################## import wx import wx.grid app = wx.PySimpleApp() f = wx.Frame(None, -1, "") p = wx.Panel(f, -1) s = wx.BoxSizer(wx.VERTICAL) t1 = wx.TextCtrl(p) s.Add(t1) g = wx.grid.Grid(p, -1) g.CreateGrid(2, 2) s.Add(g, 1, wx.EXPAND) def onGridFocus(evt): print "onGridFocus" evt.Skip() def onCellSelected(evt): print "onCellSelected" evt.Skip() g.Bind(wx.grid.EVT_GRID_SELECT_CELL, onCellSelected) g.Bind(wx.EVT_SET_FOCUS, onGridFocus) p.SetSizer(s) f.Show() app.MainLoop() ################## From claudio.grondi at freenet.de Thu Nov 17 09:37:27 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 17 Nov 2005 14:37:27 -0000 Subject: How to - import code not in current directory References: <1132233527.222443.139470@g14g2000cwa.googlegroups.com> Message-ID: <3u3fddFurbi3U2@individual.net> This question seems to come up in this newsgroup quite often, so looking through past threads will sure provide more details. Here from "Re: how to import a module from a arbitraty path?" posted to comp.lang.python by Simon Brunning on May 26, 2005 09:20 : " > I have a program which is going to dynamicly load components from some > arbitrary defined paths. How to do that? You can locate them with os.walk and fnmatch. Then you can temporarily add the directory to sys.path, and import using __import__(). " so this should work in your case: import sys sys.path.append("C:\some\other\directory") import bar Claudio "py" schrieb im Newsbeitrag news:1132233527.222443.139470 at g14g2000cwa.googlegroups.com... > I have a python script that I want to test/debug. It contains a class > which extends from some other class which is located in some other > python file in a different directory. > > For example: > > [script to test] > c:\python_code\foo.py > > [needed python files] > c:\some\other\directory\bar.py > > ...so I want to test/debug foo.py, which needs bar.py. foo.py imports > bar.py ...but in order to test out foo (in the python shell) I normally > copy bar.py into the same directory as foo.py...but this is painful. > Is there some way that I can have python know about the directory where > bar.py is located, like a system variable, etc? If so, how do I set > that up? > > Thanks. > From bonono at gmail.com Wed Nov 9 08:03:25 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 05:03:25 -0800 Subject: append to non-existing list In-Reply-To: References: Message-ID: <1131541405.947990.296750@g47g2000cwa.googlegroups.com> I am afraid you have to either go back to php or whatever programming language that fits your style or change your style to fit python. There is a lot I don't like about python but if you have to use it, you have to cope with it. Yves Glodt wrote: > My question is: Is there no way to append to a non existing list? > > I am lazy for declaring it first, IMHO it bloats the code, and (don't > know if it's good to say that here) where I come from (php) I was used > to not-needing it... > > > regards, > Yves From __peter__ at web.de Tue Nov 29 03:05:27 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Nov 2005 09:05:27 +0100 Subject: nesting for statements? References: <1133114314.033077.104970@g14g2000cwa.googlegroups.com> <3uukiiF135t04U1@individual.net> <1133188025.546435.188370@g44g2000cwa.googlegroups.com> Message-ID: tpcolson at gmail.com wrote: > Hi. Thanks for the tip. However, implementing that example, the script > will only generate the second output "file", (or it's overwriting the > first one), so all I get when run is "fileb". I think your looping code has the structure for x in ["a", "b", "c"]: pass print x This will print x once after the loop has completed. By then the value of x is "c". To fix it, move the code from /after/ the loop /into/ the loop: for x in ["a", "b", "c"]: print x In the code you give that would mean that you have to indent the try: # ... except: # ... statement one more level. Inside that loop you want a filename and an integer value in lockstep. The simplest way to get that is zip(): >>> for Disc, suffix in zip(xrange(2, 6, 2), "abcdefghijklmnopqrstuvwxyz"): ... Out_Dem = "out" + suffix ... print Disc, Out_Dem ... 2 outa 4 outb Again, you have to replace the print statement by your try...except. If you fear that you will eventually run out of suffices, here is a function that "never" does: >>> def gen_suffix(chars): ... for c in chars: ... yield c ... for c in gen_suffix(chars): ... for d in chars: ... yield c + d ... >>> for i, s in zip(range(20), gen_suffix("abc")): ... print i, s ... 0 a 1 b 2 c 3 aa 4 ab 5 ac 6 ba 7 bb 8 bc 9 ca 10 cb 11 cc 12 aaa 13 aab 14 aac 15 aba 16 abb 17 abc 18 aca 19 acb That said, reading the tutorial or an introductory book on Python never hurts... Peter From calad.sigilon at gmail.com Sun Nov 13 18:43:37 2005 From: calad.sigilon at gmail.com (calad.sigilon at gmail.com) Date: 13 Nov 2005 15:43:37 -0800 Subject: Python Book In-Reply-To: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> References: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> Message-ID: <1131925417.463282.260350@g43g2000cwa.googlegroups.com> Have you tried the tutorial on python.org? It's pretty good, even for seasoned programmers. Calad Sigilon David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? > > /David From Dennis.Benzinger at gmx.net Wed Nov 9 11:17:47 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 09 Nov 2005 17:17:47 +0100 Subject: parse data In-Reply-To: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> References: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> Message-ID: <43722126$1@news.uni-ulm.de> py schrieb: > I have some data (in a string) such as.... > > person number 1 > > Name: bob > Age: 50 > > > person number 2 > > Name: jim > Age: 39 > > ...all that is stored in a string. I need to pull out the names of the > different people and put them in a list or something. Any > suggestions...besides doing data.index("name")...over and over? > > thanks! > Use the re module: import re your_data = """person number 1 Name: bob Age: 50 person number 2 Name: jim Age: 39""" names = [] for match in re.finditer("Name:(.*)", your_data): names.append(match.group(1)) print names Bye, Dennis From jes at nl.demon.net Mon Nov 14 16:07:23 2005 From: jes at nl.demon.net (Jim Segrave) Date: Mon, 14 Nov 2005 21:07:23 -0000 Subject: how do i use "tkinter.createfilehandler" with a regular c program? References: Message-ID: <11nhv4bj0sqdf86@corp.supernews.com> In article , Jo Schambach wrote: >I am trying to write a GUI with tkinter that displays the stdout from a >regular C/C++ program in a text widget. >The idea i was trying to use was as follows: > >1) use "popen" to execute the C/C++ program >2) then use "tkinter.createfilehandler" to create a callback that would >be called when the C/C++ program creates output on stdout. > >Somehow, I can't get this to work. here is what I have tried so far: > >import sys,os >from Tkinter import * > >root = Tk() >mainFrame = Frame(root) >textBox = Text(mainFrame) >textBox.pack(fill=BOTH, expand=YES) >mainFrame.pack(fill=BOTH, expand=YES) > >fh = os.popen('/homes/jschamba/tof/pcan/pcanloop') > >def readfh(filehandle, stateMask): > global textBox > newText = filehandle.read() > textBox.insert(END, newText) > >tkinter.createfilehandler(fh, tkinter.READABLE, readfh) >root.mainloop() Changingfilehandle.read() to filehandle.readline() and running a separate output generator, this seems to work, although the Text widget fills rapidly: ========= test generator - creates a pipe and writes the time once/second #!/usr/local/bin/python import os, time try: pipe = os.mkfifo('./pipe', 0660) except OSError, (errno): if errno == 17: pass fh = open('./pipe', 'w') rh = open('./pipe', 'r') # keep the pipe having a reader while True: fh.write("%s\n" % time.asctime(time.localtime())) fh.flush() time.sleep(1) ========== read the output and put in a Text widget: #!/usr/bin/python import sys,os from Tkinter import * root = Tk() mainFrame = Frame(root) textBox = Text(mainFrame) textBox.pack(fill=BOTH, expand=YES) mainFrame.pack(fill=BOTH, expand=YES) fh = os.popen('/bin/cat /tmp/pipe', 'r', 1) def readfh(filehandle, stateMask): global textBox newText = filehandle.readline() textBox.insert(END, newText) tkinter.createfilehandler(fh, tkinter.READABLE, readfh) root.mainloop() -- Jim Segrave (jes at jes-2.demon.nl) From m.amenchar1 at chello.nl Fri Nov 4 18:34:59 2005 From: m.amenchar1 at chello.nl (Mostapha Amenchar) Date: Sat, 5 Nov 2005 00:34:59 +0100 Subject: Python Exercises for Newbee Message-ID: <000901c5e198$609ce220$f708a33e@tadkant91wjg77> http://www.upriss.org.uk/python/PythonCourse.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From timothy at open-networks.net Thu Nov 10 16:54:23 2005 From: timothy at open-networks.net (Timothy Smith) Date: Fri, 11 Nov 2005 07:54:23 +1000 Subject: Python obfuscation In-Reply-To: <1131639786.958533.45070@z14g2000cwz.googlegroups.com> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131639786.958533.45070@z14g2000cwz.googlegroups.com> Message-ID: <4373C18F.7080702@open-networks.net> > Reliability is >important but so is protecting your code in an effective manner > > there is no way to prevent people disassembling your code compiled or otherwise. once you give then the program they can easily take it apart. no if's, no but's; do NOT rely on binary's for security. > >the big software companies might say 'trusted computing will save us' >but I for one will never truly trust it. > > trusted computing it about your computer not trusting YOU. the computer you pay for will decied based on some other company's whim's what you are and are not allowed to do. >Perhaps a comprehensive protection for interpreted languages can never >be built because of their high level nature? > > i repeat. there is no such thing as protected code. i've seen people de construct exe's written in C. From fredrik at pythonware.com Tue Nov 29 09:34:45 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Nov 2005 15:34:45 +0100 Subject: Why I need to declare import as global in function References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com><1133265470.979764.157620@g14g2000cwa.googlegroups.com> Message-ID: Duncan Booth wrote: > That is unlikely to help. The execfile target seems to have been > TU_05_010.py, but the file which cannot access math is TU_05_tools.py > accessed by a normal import, so adding some globals to the execfile call > won't really do anything useful. > > Isn't it fun trying to guess the problem in the absence of the code? given that the NameError occurs on line 2 of the file, inside a function, this is probably just a misunderstanding of how namespaces work in Python... From mediocre_person at hotmail.com Sat Nov 19 10:04:44 2005 From: mediocre_person at hotmail.com (Terrance N. Phillip) Date: Sat, 19 Nov 2005 09:04:44 -0600 Subject: Tkinter from Vis. BASIC Message-ID: <437f3e9f$0$6383$a82e2bb9@reader.athenanews.com> In VB, an easy way I indicate progress is something like do while lblNotify.foreground = randomcolor lblNotify.refresh <----------- loop I want to do the same thing in Python/Tkinter: # Wait for network to recognize the workstation: while os.system("slist") != 0: self.notify["fg"] = randcolor() # how do I refresh label l3 at this point? time.sleep(3) I've tried self.notify.grid() (I'm using the grid geometry manager throughout), but that didn't work, and there is no redraw() or refresh() method that I can see. From cookedm+news at physics.mcmaster.ca Sun Nov 20 00:45:51 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Sun, 20 Nov 2005 00:45:51 -0500 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: Peter Hansen writes: > Steven D'Aprano wrote: >> Dealing with numeric literals with lots of digits is >> a real (if not earth-shattering) human interface problem: it is hard for >> people to parse long numeric strings. > > I'm totally unconvinced that this _is_ a real problem, if we define > "real" as being even enough to jiggle my mouse, let alone shattering the > planet. > > What examples does anyone have of where it is necessary to define a > large number of large numeric literals? Isn't it the case that other > than the odd constants in various programs, defining a large number of > such values would be better done by creating a data file and parsing > it? One example I can think of is a large number of float constants used for some math routine. In that case they usually be a full 16 or 17 digits. It'd be handy in that case to split into smaller groups to make it easier to match with tables where these constants may come from. Ex: def sinxx(x): "computes sin x/x for 0 <= x <= pi/2 to 2e-9" a2 = -0.16666 66664 a4 = 0.00833 33315 a6 = -0.00019 84090 a8 = 0.00000 27526 a10= -0.00000 00239 x2 = x**2 return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10)))) (or least that's what I like to write). Now, if I were going to higher precision, I'd have more digits of course. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From grante at visi.com Thu Nov 3 16:49:30 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 03 Nov 2005 21:49:30 -0000 Subject: reading internet data to generate random numbers. References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> <11mj21gr6rjgc65@corp.supernews.com> <86ll06jr79.fsf@bhuda.mired.org> <4369B2CF.70201@REMOVEMEcyber.com.au> <11mkcg2l9d89qff@corp.supernews.com> Message-ID: <11ml1faafst1h3c@corp.supernews.com> On 2005-11-03, Peter Hansen wrote: >>>I've never heard of anybody using the data as source of >>>entropy. >> >> Me neither, but the original poster did ask how to read every >> nth byte of "the Internet stream", so I assumed he had >> something like that in mind. > > And to think that if you'd just waited for the OP to explain > what the heck he meant by "the Internet stream", you'd have > saved ever so much time. ;-) > > (But then, if we always did that Usenet wouldn't be any fun.) That's for sure. The real questions are rarely as interesting and the imagined ones. -- Grant Edwards grante Yow! Well, O.K. I'll at compromise with my visi.com principles because of EXISTENTIAL DESPAIR! From steve at holdenweb.com Sun Nov 27 15:30:54 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 27 Nov 2005 20:30:54 +0000 Subject: Fractal curve In-Reply-To: References: Message-ID: Steve Heyburn wrote: > Hello there, > > I am studying programming at University and we are basing the course on Python. > We are currently looking at fractal curves and I was wondering if you could > email me code for a dragon curve please, or a similar fractal curve. > http://www.google.com/search?q=dragon+curve+python -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From aleax at mail.comcast.net Fri Nov 18 12:02:18 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 18 Nov 2005 09:02:18 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> <1132249511.886027.93990@g14g2000cwa.googlegroups.com> <1h662eo.95qjyvd1bcnuN%aleax@mail.comcast.net> <437d0b86.63834689@news.oz.net> <1132325798.806457.91170@g47g2000cwa.googlegroups.com> Message-ID: <1h67rkl.1rkx0mm1hpdql9N%aleax@mail.comcast.net> Anton Vredegoor wrote: ... > What was mostly on my mind (but I didn't mention it) is that for > something to be commercially viable there should be some kind of > pricing strategy (NB in our current economic view of the world) where a > better paying user gets a vip interface and poor people get the > standard treatment. Some fields work well with such market segmentation, but others work perfectly well without it. iTunes songs are 99 cents (for USA residents; there IS some segmentation by national markets, imposed on Apple by the music industry) whoever is buying them; I personally think it would hurt iTunes' business model if the 99-cents song was a "cheap version" and you could choose to "upgrade" to a better-sounding one for extra money -- giving the mass-market the perception that they're getting inferior goods may adversely hurt sales and revenue. Market segmentation strategies and tactics are of course a huge field of study, both theoretical and pragmatic (and it's as infinitely fascinating in the theoretical view, as potentially lucrative or ruinous in practical application). It's definitely wrong to assume, as in your statement above, that uniform pricing (no segmentation, at least not along that axis) cannot work in a perfectly satisfactory way. > If the heuristic always gives the same answer to the same problem it > would be easier to predict the results. Oh no, now some mathematician > surely will prove me wrong :-) "Easier" need not be a problem; even assuming that the heuristic uses no aspect whatever of randomness, you may easily think of real-world cases where ``reverse engineering'' the heuristic from its results is computationally unfeasible anyway. Take the problem of controlling a NC saw to cut a given set of shapes out of a standard-sized wood plank, which is one of the real-world cases I mentioned. It doesn't seem to me that trying to reverse-engineer a heuristic is any better than trying to devise one (which may end up being better) from ingenuity and first principles, even if you had thousands of outputs from the secret heuristic at hand (and remember, getting each of this output costs you money, which you have to pay to the webservice with the heuristic). > Ok. Although it's a bit tricky to prove this by using an example where > the randomness is already in the problem from the start. If one groups > very chaotic processes in the same category as random processes of > course. Well, economically interesting prediction problems do tend to deal with systems that are rich and deep and complex enough to qualify as chaotic, if not random -- from weather to the price of oil, etc etc. But problems of optimization under constraint, such as the NC saw one, hardly qualify as such, it seems to me -- no randomness nor necessarily any chaotic qualities in the problem, just utter computational unfeasibility of algorithmic solutions and the attendand need to look for "decently good" heuristics instead. > > >Deliberately giving predictions worse than I could have given, in this > > >context, seems a deliberate self-sabotage without any return. > > Not always, for example with a gradient in user status according to how > much they pay. Note that I don't agree at all with such practice, but > I'm trying to explain how money is made now instead of thinking about > how it should be made. Money is made in many ways, essentially by creating (perceived) buyer advantage and capturing some part of it -- but market segmentation is just one of many ways. IF your predictions are ENORMOUSLY better than those the competition can make, then offering for free "slightly damaged" predictions, that are still better than the competition's despite the damage, MIGHT be a way to market your wares -- under a lot of other assumptions, e.g., that there is actual demand for the best predictions you can make, the ones you get paid for, so that your free service doesn't undermine your for-pay one. It just seems unlikely that all of these preconditions would be satisfied at the same time; better to limit your "free" predictions along other axes, such as duration or location, which doesn't require your predictions' accuracy advantage to be ENORMOUS _and_ gives you a lot of control on "usefulness" of what you're supplying for free -- damaging the quality by randomization just seems to be unlikely to be the optimal strategy here, even if you had determined (or were willing to bet the firm that) marked segmentation is really the way to go here. Analogy: say you make the best jams in the world and want to attract customers by showing them that's the case via free samples. Your randomization strategy seems analogous to: damage your jam's free samples by adding tiny quantities of ingredients that degrade their flavor -- if your degraded samples are still much better than the competitors' jam, and there's effective demand for really "perfect" jam, this strategy MIGHT work... but it seems a very, very far-fetched one indeed. The NORMAL way to offer free samples to enhance, not damage, the demand for your product, would be to limit the samples along completely different axes -- damaging your product's quality deliberately seems just about the LAST think you'd want to do; rather, you'd offer, say, only tiny amounts for sampling, and already spread on toast so they need to be tasted right on the spot, enticing the taster to purchase a jar so they can have the amount of jam they choose at the time and place of their choosing. I hope this analogy clarifies why, while I don't think deliberate damage of result quality can be entirely ruled out, I think it's extremely unlikely to make any sense compared to ofher market segmentation tactics, even if you DO grant that it's worth segmenting (free samples are an extremely ancient and traditional tactic in all kind of food selling situations, after all, and when well-designed and promoting a product whose taste is indeed worth a premium price, they have been repeatedly shown to be potentially quite effective -- so, I'm hoping there will be no debate that the segmentation might perfectly well be appropriate for this "analogy" case, whether it is or isn't in the originally discussed case of selling predictions-via-webservices). Alex From klaus at seistrup.dk Fri Nov 4 14:59:09 2005 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Fri, 4 Nov 2005 19:59:09 +0000 (UTC) Subject: How do you do this in python? References: <1131133960.765700.7440@g14g2000cwa.googlegroups.com> Message-ID: casioculture at gmail.com wrote: > perl -e 'print "Hello, world\n"' python -c 'print "Hello, world"' Cheers, -- Klaus Alexander Seistrup Copenhagen, Denmark http://seistrup.dk/ From mde at micah.elliott.name Tue Nov 22 11:07:39 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Tue, 22 Nov 2005 08:07:39 -0800 Subject: after sorted from the lists In-Reply-To: <8c11e4350511220649h3d3dcb41i1e8fafac5c4b9201@mail.gmail.com> References: <8c11e4350511220649h3d3dcb41i1e8fafac5c4b9201@mail.gmail.com> Message-ID: <20051122160739.GA15193@kitchen.client.attbi.com> On Nov 22, Ben Bush wrote: > I have a list: > [[1,2],[2,1],[3,1],[1,4],[3,3],[1,4]] > How to remove all the duplicate or same after sorted from the lists? > That is, [1,2] and [2,1] are the same after sorting them. > I want the result to be: > [[1,2],[3,1],[1,4],[3,3]] You've described the code in words. Next time show the code you tried. Here's one possible solution. First sort each sublist. >>> L1 = [[1,2],[2,1],[3,1],[1,4],[3,3],[1,4]] >>> for i in L1: ... i.sort() ... >>> L1 [[1, 2], [1, 2], [1, 3], [1, 4], [3, 3], [1, 4]] Then add L1's unique items to a new list L2. >>> L2 = [] >>> for i in L1: ... if i not in L2: ... L2.append(i) ... >>> L2 [[1, 2], [1, 3], [1, 4], [3, 3]] This is not identical to your said output, but it sounds like [1,3] == [3,1] for your purposes. -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From jeff at schwabcenter.com Sun Nov 20 19:30:01 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Mon, 21 Nov 2005 00:30:01 GMT Subject: ownership problem? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Jeffrey Schwab wrote: > > >>>Is it correct to say that the typical ownership problem, which >>>frequently arises in C++, does not occur normally in Python? >> >>What "typical ownership problem" do you feel frequently arises in C++? >>If you are referring to the sometimes difficult task of determining >>which object owns a particular resource, why would it occur less in >>Python than in C++? > > > the problem isn't determining who owns it, the problem is determining > who's supposed to release it. that's not a very common problem in a > garbage-collected language... Yes it is. Memory is only one type of resource. There are still files and sockets to close, pipes to flush, log messages to be printed, GDI contexts to free, locks to release, etc. In C++, these things are generally done by destructors, which are called automatically and deterministically. I am not a Python Guru, but in Perl, Java, and other languages that have built-in garbage collectors, these tasks have to be done explicitly. I find that this forces a procedural approach, even in an otherwise object-oriented program. If you want something like automatic garbage collection in C++, I recommend the use of Factories with destructors that release the Factories' products. The zeitgeist in c.l.c++.moderated seems to prefer the use of smart (reference-counted) pointers, which also rely on destructors to release resources automatically. Plentry of free, open-source implementations are available. From bdesth.quelquechose at free.quelquepart.fr Tue Nov 1 21:17:41 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 02 Nov 2005 03:17:41 +0100 Subject: expanding dictionary to function arguments In-Reply-To: <1130894220.903211.102720@f14g2000cwb.googlegroups.com> References: <1130894220.903211.102720@f14g2000cwb.googlegroups.com> Message-ID: <436817d5$0$16713$626a14ce@news.free.fr> Noah a ?crit : > I have a dictionary that I would like to expand to satisfy a > function's agument list. I can used the ** syntax to pass a dictionary, > but > this only works if each key in the dictionary matches an argument. > I cannot pass a dictionary that has more keys than the function has > arguments. If you have control over the API functions declarations, makes them so: def my_api_func(arg1='', arg2='whatever', **kwargs): code_here From erick_bodine at comcast.net Thu Nov 17 11:15:12 2005 From: erick_bodine at comcast.net (erick_bodine at comcast.net) Date: 17 Nov 2005 08:15:12 -0800 Subject: creating package question References: <1132169418.759267.265090@o13g2000cwo.googlegroups.com> <1132170392.599721.326710@o13g2000cwo.googlegroups.com> <437ba4f7$0$16720$636a15ce@news.free.fr> Message-ID: <1132244112.827579.145460@g49g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > erick_bodine at comcast.net a ?crit : > > I think I have an answer to my own question. In the > > WindowsComponents/__init__.py file, I have the following, that feels > > like a better answer for the problem. Is there a better answer than > > this? > > > > import os, sys > > sys.path.append(os.path.join(os.getcwd(), 'Common')) > > > > Err... if the script is called from somewhere else, this won't work. > replace os.getcwd() with os.path.dirname(os.path.realpath(__file__)) > Right, I anticipate the script(s) won't be called from elsewhere, but.... > > Or better, use a .pth or add the needed path in your PYTHONPATH THis would be ideal if I could gaurantee that the users (other software testers) would install the *.pth file. thanks for all the suggestions. From google0 at lazytwinacres.net Mon Nov 21 09:01:14 2005 From: google0 at lazytwinacres.net ('Dang' Daniel Griffith) Date: Mon, 21 Nov 2005 14:01:14 +0000 Subject: Raw string fu References: <1130354873.546887.271850@z14g2000cwz.googlegroups.com> Message-ID: <32knn151f7fpphib732tkkn25loiljm0i1@4ax.com> On 26 Oct 2005 12:27:53 -0700, "Paul McGuire" wrote: >"Raw string fu"? A new martial art? For the udon-aware. --dang From pwatson at redlinepy.com Mon Nov 21 09:41:54 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Mon, 21 Nov 2005 08:41:54 -0600 Subject: Web-based client code execution In-Reply-To: <43818716.5060903@jessikat.fsnet.co.uk> References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> <1132402656.285350.146460@z14g2000cwz.googlegroups.com> <43813A11.6090606@redlinepy.com> <43818716.5060903@jessikat.fsnet.co.uk> Message-ID: <4381DCB2.3050704@redlinepy.com> Robin Becker wrote: > Paul Watson wrote: > ...... > >>> -- David >> >> >> >> This looks interesting, but looks even more fragile than CrackAJAX. >> >> http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework >> >> >> All of this comes down to Javascript which will still not allow me to >> read local, client files. Right? > > > I think reading files is easy; just get the client browser to submit a > form with the file as an upload. Hard part is getting the path(s) right. I need to walk the directory tree to find which files are of interest. It sounds like a client application (not browser) will be required. From samrobertsmith at gmail.com Fri Nov 11 17:55:31 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 11 Nov 2005 14:55:31 -0800 Subject: about widget construction kit In-Reply-To: References: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com> <1d987df30511111400m19f02d25had206df638c1bc0a@mail.gmail.com> Message-ID: <1d987df30511111455t1e96e536j68c2b952470ed83a@mail.gmail.com> On 11/11/05, Fredrik Lundh wrote: > Shi Mu wrote: > > > > > I tried to install WCK(Widget Construction Kit (WCK)): > > > > > > > > C:\Python23>python tkinter3000-1.0-20031212\setup.py install > > > > Traceback (most recent call last): > > > > File "tkinter3000-1.0-20031212\setup.py", line 23, in ? > > > > WCK_VERSION = setuplib.find_version("WCK/__init__.py") > > > > File "C:\wget2\tkinter3000-1.0-20031212\setuplib.py", line 74, in find_version > > > > for line in open(filename).readlines(): > > > > IOError: [Errno 2] No such file or directory: 'WCK/__init__.py' > > > > > > > > I checked my files and found there is a __init__.py and got confused > > > > why the error came out? > > > > > > if you're using windows, please use a prebuilt version of the WCK. > > > > > > I also recommend using the 1.1b1 release; it's a lot better than 1.0. > > > > > > if you really want to build it yourself, and you have the right compilers > > > and all Tcl/Tk build files in the right places, change to the source directory > > > before running the setup script. > > > if I run python command, I need to go > > to the directory where python is installed, so how can I change to the > > source directory at the same time? > > you're 100% sure that you have a working compiler and the right Tcl/Tk > build files in the right place, but you don't know how to run an executable > from another directory? > > hmm. > > here are three ways: > > 1. pass in the full path to the executable: > > cd tkinter3000-1.0-20031212 > c:\python23\python setup.py install > > 2. add the python installation directory to the path. random > google link: > > http://www.computerhope.com/issues/ch000549.htm > > when you've updated the environment, open up a new command > window, and do > > cd tkinter3000-1.0-20031212 > python setup.py install > > 3. if you used a python.org installer, it's likely that you can run > the setup.py file directly: > > cd tkinter3000-1.0-20031212 > setup.py install > still confused by th first way you mentioned. If I cd tkinter3000-1.0-20031212, i will be enter the directory witht hte setup.py; for example, it is located as c:\temp\tkinter3000-1.0-20031212\setup.py However, I need to use c:\python23\python setup.py install to process the installation, how did python know where the file of "setup.py" located? From onurb at xiludom.gro Thu Nov 10 07:42:18 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 10 Nov 2005 13:42:18 +0100 Subject: iterate over class variables In-Reply-To: References: <43733767.1040205@sitasoftware.lu> Message-ID: <4373402c$0$30556$636a15ce@news.free.fr> Yves Glodt wrote: > Yves Glodt wrote: > >> Hello list, >> >> I need to iterate over a class and get all her variable names and >> values, e.g. considering this example: >> >> >> class testclass: >> var1 = 'ab' >> var2 = 'cd' >> var3 = 'ef' Take care, these are *class* variables, not instance variables. >> test = testclass() >> >> Then I wanna do sonmething like this: >> >> for name,value in test: >> print name >> print value >> (snip) > > sorry for selfreplying, but I found a solution: > > for key in dir(test): > if '__' not in key: > value = getattr(test,key) > print key, value > > Does anything speak about this? 1/ dir() doesn't necessary returns all the attributes of an object: """ dir(...) dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: """ But I don't think this is a problem here. 2/ everything being an object, dir() also returns methods (a method being a - callable - attribute of the object's class). If you're only interested in data attributes, you may want to try this: for key in dir(test): if not key.startswith('__'): value = getattr(test,key) if not callable(value): print key, value You can also check inspect.getmember() -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ldo at geek-central.gen.new_zealand Sat Nov 12 04:54:45 2005 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 12 Nov 2005 22:54:45 +1300 Subject: JAPH Message-ID: import sys charset = " .JPacehknorstuy" modulo = 17 s = 69859911049503515105680510599913390885187193231927247909305172858127641629 num = iter(range(2, 9999)) while s != 1 : n = num.next() if s % n == 0 : sys.stdout.write("%s" % charset[(n - 1) % modulo]) s /= n #end if #end while sys.stdout.write("\n") From steve at REMOVEMEcyber.com.au Mon Nov 14 02:05:32 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 14 Nov 2005 18:05:32 +1100 Subject: Abstract Base Classes References: Message-ID: <4378373C.1070204@REMOVEMEcyber.com.au> Ben Finney wrote: > Ben Finney wrote: > >>I want my modules to (sometimes) define an abstract base exception >>class, that all other exceptions in that module inherit from. > > > [re-posting with the implementation properly foo-ified] Isn't the proper Python idiom to use Monty Python concepts, e.g. spam, vikings, parrots, after dinner mints (wafer thin or otherwise), gumby, etc.? As well as being Pythonic, it annoys the Lisp, Perl and C developers even more than ... sarcasm. *wink* > Not a whole lot of feedback on this, so here's the implementation I > decided upon. [snip] Seems good to me. -- Steven. From pwatson at redlinepy.com Thu Nov 24 11:50:05 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Thu, 24 Nov 2005 10:50:05 -0600 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <4385788a$0$24921$9b622d9e@news.freenet.de> References: <3uk6siF11mqgvU1@individual.net> <4384ec18$0$25871$9b622d9e@news.freenet.de> <438505AA.8000105@redlinepy.com> <43850790$0$4066$9b622d9e@news.freenet.de> <3ukk91F11t5c5U1@individual.net> <4385788a$0$24921$9b622d9e@news.freenet.de> Message-ID: <4385EF3D.8000103@redlinepy.com> Martin v. L?wis wrote: > Paul Watson wrote: > >> It appears that _ALL_SOURCE gets defined in the >> /usr/include/standards.h file. If we could #define _ANSI_C_SOURCE or >> _POSIX_SOURCE, it appears that it would eleminate _ALL_SOURCE. > > > Ah, ok - this should be easy enough. Python would normally define > _POSIX_SOURCE (through _XOPEN_SOURCE), but configure(.in) has this > block: > > # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == > 500 but > # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not > defined > # or has another value. By not (re)defining it, the defaults come in > place. > AIX/4) > define_xopen_source=no;; > AIX/5) > if test `uname -r` -eq 1; then > define_xopen_source=no > fi > ;; > > which causes _XOPEN_SOURCE (and subsequently probably _POSIX_SOURCE) not > to be defined. What AIX version are you using? Can you try removing > the fragment from configure(.in), rerun configure, verify that > _XOPEN_SOURCE is defined in pyconfig.h, and then try building again? > > If this works, this might be a solution. Otherwise, we need to put > something like this into _codecs_cn.c: > > #ifdef hz > /* On AIX version such-and-such, hz is defined because _ALL_SOURCE is > defined, this in turn is defined because _XOPEN_SOURCE is not. > As _XOPEN_SOURCE cannot be enabled (see configure.in), we just > work around by removing the hz definition again. */ > #undef hz > #endif > > Regards, > Martin Commenting out the section in configure(.in) did not cause it to work. It still ended up with '100_encode' complaint. Using '#undef hz' in ./Modules/cjkcodecs/_codecs_cn.c does cause it to compile. However, it will not pass ./Lib/test/test_codecsencoding_cn.py or ./Lib/test/test_codecmaps_cn.py. The others (_hk, _jp, _kr, and _tw) do pass the test. I also note that compiles occurring after the complaint about not finding Tcl/Tk do not appear to get the OPT= setting I specified on the 'make' command line. It starts with compilation of structmodule.c and includes the _codecs_??.c files. Does this have any significance? Is it possible that there are other settings not being used? $ python test_codecencodings_cn.py test_chunkcoding (__main__.Test_GB2312) ... ERROR test_customreplace (__main__.Test_GB2312) ... ERROR test_errorhandle (__main__.Test_GB2312) ... ERROR test_streamreader (__main__.Test_GB2312) ... ERROR test_streamwriter (__main__.Test_GB2312) ... ERROR test_xmlcharrefreplace (__main__.Test_GB2312) ... ERROR test_chunkcoding (__main__.Test_GBK) ... ERROR test_customreplace (__main__.Test_GBK) ... ERROR test_errorhandle (__main__.Test_GBK) ... ERROR test_streamreader (__main__.Test_GBK) ... ERROR test_streamwriter (__main__.Test_GBK) ... ERROR test_xmlcharrefreplace (__main__.Test_GBK) ... ERROR test_chunkcoding (__main__.Test_GB18030) ... ERROR test_customreplace (__main__.Test_GB18030) ... ERROR test_errorhandle (__main__.Test_GB18030) ... ERROR test_streamreader (__main__.Test_GB18030) ... ERROR test_streamwriter (__main__.Test_GB18030) ... ERROR test_xmlcharrefreplace (__main__.Test_GB18030) ... ERROR ====================================================================== ERROR: test_chunkcoding (__main__.Test_GB2312) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb2312 ====================================================================== ERROR: test_customreplace (__main__.Test_GB2312) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb2312 ====================================================================== ERROR: test_errorhandle (__main__.Test_GB2312) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb2312 ====================================================================== ERROR: test_streamreader (__main__.Test_GB2312) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb2312 ====================================================================== ERROR: test_streamwriter (__main__.Test_GB2312) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb2312 ====================================================================== ERROR: test_xmlcharrefreplace (__main__.Test_GB2312) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb2312 ====================================================================== ERROR: test_chunkcoding (__main__.Test_GBK) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gbk ====================================================================== ERROR: test_customreplace (__main__.Test_GBK) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gbk ====================================================================== ERROR: test_errorhandle (__main__.Test_GBK) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gbk ====================================================================== ERROR: test_streamreader (__main__.Test_GBK) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gbk ====================================================================== ERROR: test_streamwriter (__main__.Test_GBK) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gbk ====================================================================== ERROR: test_xmlcharrefreplace (__main__.Test_GBK) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gbk ====================================================================== ERROR: test_chunkcoding (__main__.Test_GB18030) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb18030 ====================================================================== ERROR: test_customreplace (__main__.Test_GB18030) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb18030 ====================================================================== ERROR: test_errorhandle (__main__.Test_GB18030) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb18030 ====================================================================== ERROR: test_streamreader (__main__.Test_GB18030) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb18030 ====================================================================== ERROR: test_streamwriter (__main__.Test_GB18030) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb18030 ====================================================================== ERROR: test_xmlcharrefreplace (__main__.Test_GB18030) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pwatson/usr/lib/python2.4/test/test_multibytecodec_support.py", line 27, in setUp self.codec = codecs.lookup(self.encoding) LookupError: unknown encoding: gb18030 ---------------------------------------------------------------------- Ran 18 tests in 0.015s FAILED (errors=18) Traceback (most recent call last): File "test_codecencodings_cn.py", line 60, in ? test_main() File "test_codecencodings_cn.py", line 57, in test_main test_support.run_suite(suite) File "/home/pwatson/usr/lib/python2.4/test/test_support.py", line 274, in run_suite raise TestFailed(msg) test.test_support.TestFailed: errors occurred; run in verbose mode for details 10:38 pwatson [ kbs80:/home/pwatson/src/python/Python-2.4.2/Lib/test ] 672 $ python test_codecencodings_hk.py test_chunkcoding (__main__.Test_Big5HKSCS) ... ok test_customreplace (__main__.Test_Big5HKSCS) ... ok test_errorhandle (__main__.Test_Big5HKSCS) ... ok test_streamreader (__main__.Test_Big5HKSCS) ... ok test_streamwriter (__main__.Test_Big5HKSCS) ... ok test_xmlcharrefreplace (__main__.Test_Big5HKSCS) ... ok ---------------------------------------------------------------------- Ran 6 tests in 0.063s OK From bretthoerner at gmail.com Wed Nov 2 22:47:45 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 2 Nov 2005 19:47:45 -0800 Subject: Python for .NET and IronPython In-Reply-To: <1130979633.835814.251720@g47g2000cwa.googlegroups.com> References: <1130979633.835814.251720@g47g2000cwa.googlegroups.com> Message-ID: <1130989665.539157.139370@o13g2000cwo.googlegroups.com> hrh1818 wrote: > For more information on Iron Python see http://www.ironpython.com/ > My take on Iron Python is the new job the develolper of Iron Python > started last year takes up just about all of his time and the developer > is currently spending very little time actively developing Iron Python. Actually, he just stopped updating ironpython.com (a bad idea, imo) apparently. Last release was 10/13 through Microsoft, http://www.microsoft.com/downloads/details.aspx?FamilyID=c6a7fee3-6495-427f-8b1f-768a2715170c&DisplayLang=en If that link doesn't work you can just search "IronPython" on microsoft.com Brett From tuvas21 at gmail.com Wed Nov 23 13:37:20 2005 From: tuvas21 at gmail.com (Tuvas) Date: 23 Nov 2005 10:37:20 -0800 Subject: Tkinter Images Message-ID: <1132771040.564655.24510@g43g2000cwa.googlegroups.com> I've been trying to use a canvas to display different pictures on a Tkinter interface. However, it doesn't seem to update the information. Ei, I have something like this. canvas=Canvas(master,blah...) canvas.pack() def change_pic(path): global pic image=Image() #I'm using PIL to use the images, but I don't think it's depended... This code's not the important one... canvas.create_image(1,1,image=image, anchor=NW) change_pic("test1.jpg") I have written a simple scipt that just displays an image, without any problems. However, when I try to change the image dynamically, it doesn't work. If needed I can put the real code, however, it's a bit complicated to do so, this computer doesn't support copying from the terminal to the web browser. Thanks for the help! From aleax at mail.comcast.net Thu Nov 24 18:21:59 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 24 Nov 2005 15:21:59 -0800 Subject: defining the behavior of zip(it, it) References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> <1132712643.968300.151010@g49g2000cwa.googlegroups.com> <1132713954.040591.120660@f14g2000cwb.googlegroups.com> <1132718374.960509.206800@z14g2000cwz.googlegroups.com> <1132778601.776080.80100@g44g2000cwa.googlegroups.com> <1h6hzbn.1ww7x45cvcp7vN%aleax@mail.comcast.net> <1132872219.800028.244770@o13g2000cwo.googlegroups.com> Message-ID: <1h6jebv.1paz231x51aarN%aleax@mail.comcast.net> wrote: ... > > >>> d=deque([1,2,3]) > > >>> d[:] > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: sequence index must be integer > > >>> deque(d) > > deque([1, 2, 3]) > > >>> > > > > I.e., NOT all sequences implement the unreadable x[:] form. > > > > The way that DOES work with all sequences is typeyouwant(sequence). > > I'm sorry, I don't understand. Does deque return a sequence? There is no universally accepted definition of what "is a sequence" in Python, but the deque type meets most criteria. > The doc says it returns a deque object, and without further info > I would not expect [:] to work. Is it a sequence because it has > the same methods as a sequence? Workable definitions are usually operational ones, yes. > Whatever, I gather my old book is outdated and the blessed > way now to (shallow) copy a sequence is (as you say) > "typeyouwant(sequence)" which I will make a note of. > > Thanks for updating me. You're welcome, but be aware that this is MY thesis and not all accept it. somesequencetype(someiterable) is a general way to make a new instance of type 'somesequencetype' and accepts a wide variety of types for arguments, namely all iterables. list(somelist) is slightly less compact than somelist[:] when you know you start with a list instance and want a shallow copy thereof, but I see no good reason to specialcase this occurrence AND use an unreadable idiom in it, when the nice, general, readable idiom is perfectly serviceable. Alex From steve at holdenweb.com Tue Nov 15 20:28:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 Nov 2005 01:28:36 +0000 Subject: HTTP Keep-Alive with urllib2 In-Reply-To: <43786620$0$2103$edfadb0f@dtext02.news.tele.dk> References: <43786620$0$2103$edfadb0f@dtext02.news.tele.dk> Message-ID: David Rasmussen wrote: > Someone once asked about this an got no answer: > > http://groups.google.dk/group/comp.lang.python/browse_frm/thread/c3cc0b8d7e9cbc2/ff11efce3b1776cf?lnk=st&q=python+http+%22keep+alive%22&rnum=84&hl=da#ff11efce3b1776cf > > Maybe I am luckier :) > > Does anyone know how to do Keep-Alive with urllib2, that is, how to get > a persistent HTTP connection, instead of a new connection being opened > for every request? > This would imply the answer is "it's not possible": sholden at bigboy ~/Projects/pycon $ grep -i keep-alive /lib/python2.4/urllib*.py 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 nick at craig-wood.com Thu Nov 10 07:30:14 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 10 Nov 2005 06:30:14 -0600 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> <1131517112.247477.35030@g14g2000cwa.googlegroups.com> <1h5rxho.nxmo0z15zne5jN%aleax@mail.comcast.net> Message-ID: I tested gmpy cvs as of now on Debian/testing/x86 with python2.3. It compiled perfectly, ran all of its unit tests and also all my test programs - Well done! My test program seemed to run at the same speed with both versions (not suprising really since both are using the same libgmp.so on the system). Thanks and look forward to the release Nick -- Nick Craig-Wood -- http://www.craig-wood.com/nick From theaney at cablespeed.com Mon Nov 21 08:02:44 2005 From: theaney at cablespeed.com (Tim Heaney) Date: Mon, 21 Nov 2005 08:02:44 -0500 Subject: Aproximative string matching References: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> Message-ID: "javuchi" writes: > I'm searching for a library which makes aproximative string matching, > for example, searching in a dictionary the word "motorcycle", but > returns similar strings like "motorcicle". > > Is there such a library? I kind of like the one at http://www.personal.psu.edu/staff/i/u/iua1/python/apse/ which you might use something like >>> import Apse >>> ap = Apse.Approx('motorcycle', edit=1) >>> ap.match(['motorcycle', 'motorcicle', 'motorscooter']) ['motorcycle', 'motorcicle'] That page mentions several alternatives, as well. I hope this helps, Tim From samrobertsmith at gmail.com Sun Nov 6 21:29:40 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 18:29:40 -0800 Subject: click event Message-ID: <1d987df30511061829t59d5402alecae025e7c65062c@mail.gmail.com> I have the following workable code and every time i click on the canvas, the coordinates are reported. i wonder how i can draw the lines when i click the canvas using these coordinates? from Tkinter import * root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) def click(event): print event.x, event.y frame = c c.bind('',click) c.pack() root.mainloop() From peter at engcorp.com Wed Nov 23 23:13:16 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Nov 2005 23:13:16 -0500 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <1132803762.570118.253770@o13g2000cwo.googlegroups.com> References: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> <1132803762.570118.253770@o13g2000cwo.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Which is also my initial puzzle, items() and iteritems() already gives > you the tuples, why such gurantee or the others ? Doesn't that violate > the general idiom that if we can do certain thing in one way, there > better be one and only one way. > > Are there other usage scenarios that would be benefit from this as the > example given is not convincing for me. As Jeff's reply emphasizes, the "examples" show tuples with *value* and then *key*, not the other way around which is what .items() and .itemitems() gives you. Anyway, you didn't ask for good examples of use, just "why is it guaranteed", and that's all I was showing you. Whether it was a good idea might be an interesting discussion, but probably not a particularly useful one given once again that it's unlikely this particular feature could be undone now that code exists (we can assume) which is dependent on it. -Peter From pwatson at redlinepy.com Wed Nov 23 19:13:30 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 23 Nov 2005 18:13:30 -0600 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <4384ec18$0$25871$9b622d9e@news.freenet.de> References: <3uk6siF11mqgvU1@individual.net> <4384ec18$0$25871$9b622d9e@news.freenet.de> Message-ID: <438505AA.8000105@redlinepy.com> Martin v. L?wis wrote: > Paul Watson wrote: > >> Any ideas why ./Modules/cjkcodecs/_codecs_cn.c fails to compile? It >> appears that the CODEC_STATELESS macro is concatenating 'hz' with a >> number and text. > > > More likely, hz is already defined to be 100, then forming 100_encode. > > It would be best if you could find out what AIX header file defines > hz to be 100, and whether there is any way to supress that definition. > > Regards, > Martin Here are the /usr/include/*.h files that include sys/m_param.h $ grep sys/m_param $(find . -name "*.h") ./sys/pthdebug.h:#include /* _NGPRS, _NFPRS */ ./sys/context.h:#include ./sys/mstsave.h:#include /* for machine dependent defines*/ ./sys/param.h:#include ./sys/proc.h:#include ./sys/sched.h:#include Can we #undef _ALL_SOURCE for _codecs_cn.c compilation? There is a description in sys/context.h that seems to suggest that it is an internal vs. external definition issue. +44 /* +45 * XPG4.2 requires structures and structure elements to be defined such +46 * that they do not pollute the namespace. _ALL_SOURCE contains the +47 * kernel version, while not _ALL_SOURCE contains the sanitized versions. +48 */ From jzgoda at o2.usun.pl Wed Nov 2 14:04:12 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 02 Nov 2005 20:04:12 +0100 Subject: Xah's edu corner: the Journey of Foreign Characters thru Internet In-Reply-To: References: <1130852975.525590.145080@f14g2000cwb.googlegroups.com><1130874345.236356.248110@g14g2000cwa.googlegroups.com><86d5lk15ai.fsf@bhuda.mired.org> <1130895395.648837.9440@g43g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh napisa?(a): >>>>And if anyone wants to take the responsibiblity to warn the general >>>>public that it is troll so innocent readers may not be tempted into >>>>one, at least do it privately >>> >>>huh? >> >>Don't fed the troll, don't give him any public audience. Easy. > > by sending private mail to anyone who might have seen his posts? If you absolutely, positively must do something about that... But anyway it's stupid idea. Private feeding is not much better than in public. -- Jarek Zgoda http://jpa.berlios.de/ From bonono at gmail.com Wed Nov 9 08:23:54 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 05:23:54 -0800 Subject: append to non-existing list In-Reply-To: References: Message-ID: <1131542634.357504.305000@g44g2000cwa.googlegroups.com> Juho Schultz wrote: > Yves Glodt wrote: > > Hello, > > > > if I do this: > > > > for row in sqlsth: > > ________pkcolumns.append(row[0].strip()) > > ________etc > > > You mean you want to type "pkcolumns" only once to keep your code short? > Would something like this be useful? > > pkcolumns = [row.strip() for row in sqlsth] I don't think this is the same as his original code though. There is an "etc" there. Your version is cleaner and easier to understand but it can mean another extra pass to go through the result and if sqlsth is an iterable, it needs to be saved away before iterating it. From samrobertsmith at gmail.com Sun Nov 20 07:12:32 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 04:12:32 -0800 Subject: about dictionary In-Reply-To: References: Message-ID: <1d987df30511200412y11ca55c5n3c63dd75ffd0713a@mail.gmail.com> On 11/20/05, Peter Otten <__peter__ at web.de> wrote: > przemek drochomirecki wrote: > > > Uzytkownik "Shi Mu" napisal w wiadomosci > > news:mailman.888.1132484139.18701.python-list at python.org... > > I have have the following code: > >>>> a=[3,5,8,0] > >>>> b={} > >>>> > > How I can i assign each item in a as the key in the dictionary b > > simultaneously? > > that is, > > b={3:[],5:[],8:[],0:[]} > > Thanks! > > > > > > Other solution: > > b.fromkeys(a,[]) > > Be warned that all keys share the same value. > > >>> a = [3, 5, 8, 0] > >>> b = dict.fromkeys(a, []) > >>> b[3].append(42) > >>> b > {8: [42], 0: [42], 3: [42], 5: [42]} > > Probably not what you want... > > Peter how to do with it? From claudio.grondi at freenet.de Tue Nov 22 03:16:33 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 22 Nov 2005 08:16:33 -0000 Subject: Any royal road to Bezier curves...? References: Message-ID: <3ufuvpF10ooqlU1@individual.net> http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm has a Python example implementation of qubic Bezier curves available. Claudio "Warren Francis" schrieb im Newsbeitrag news:dlrin7$mtg$1 at charm.magnus.acs.ohio-state.edu... > I'm fairly new to Python (2-3 months) and I'm trying to figure out a simple > way to implement Bezier curves... So far I've tried the following: > > http://runten.tripod.com/NURBS/ > ...which won't work because the only compiled binaries are for Windows 2000, > python 2.1. I'm on Windows XP (for now), using Python 2.4. I downloaded > the source distribution, but the header files aren't included, so I'm not > sure how to compile it. > > It appears there's some bezier functionality in the python that comes > Blender... but I'm not savvy enough yet to try and extract whatever makes > beziers work there, to make it work in my general-purpose Python programs. > > Basically, I'd like to specify a curved path of an object through space. 3D > space would be wonderful, but I could jimmy-rig something if I could just > get 2D... Are bezier curves really what I want after all? > > Any thoughts would be much appreciated. I've got some ideas I want to test, > but if I can't find a simple implementation of curves, I'm going to get so > bogged down in trying to do that part, I'll never get to what I'm excited > about. :-P > > Warren > > From steve at holdenweb.com Thu Nov 17 15:01:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 Nov 2005 20:01:13 +0000 Subject: is parameter an iterable? In-Reply-To: <20051117162701.GA6912@kitchen.client.attbi.com> References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1h62slm.up4s2tqyk1gjN%aleax@mail.comcast.net> <437C36EA.8010600@REMOVEMEcyber.com.au> <20051117162701.GA6912@kitchen.client.attbi.com> Message-ID: <437CE189.8000903@holdenweb.com> Micah Elliott wrote: > On Nov 17, Duncan Booth wrote: > >>Steven D'Aprano wrote: >> >>>What should I do when I can't rely on functions that >>>don't exist in older versions of Python? > > >> sys.exit('Archaic Python not supported, please upgrade') > > > +1 QOTW. > > I recently gave up on trying to support (backport to) pre-2.2 in my > projects. It's been ~3 years since 2.2 released and that seem like a > pretty reasonable support window. I wound up with HACK and > PORTABILITY comments all over the place and too much boilerplate. Now > I go with a startup check on sys.hexversion, and exit with similar > wording. > We could all take an example from Fredrik Lundh, who still regularly releases products that run on everything back to Python 1.5.2. Kudos to the effbot! 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 utabintarbo at gmail.com Thu Nov 17 17:52:36 2005 From: utabintarbo at gmail.com (utabintarbo) Date: 17 Nov 2005 14:52:36 -0800 Subject: os.spawnl error In-Reply-To: <437CE2A1.60705@websafe.com> References: <1132257061.597353.70670@g43g2000cwa.googlegroups.com> <437CE2A1.60705@websafe.com> Message-ID: <1132267956.318916.53500@f14g2000cwb.googlegroups.com> I have found the judicious use of os.path.normpath(path) to be quite useful as well. Bob From pkilambi at gmail.com Thu Nov 10 12:53:33 2005 From: pkilambi at gmail.com (pkilambi at gmail.com) Date: 10 Nov 2005 09:53:33 -0800 Subject: help make it faster please Message-ID: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> I wrote this function which does the following: after readling lines from file.It splits and finds the word occurences through a hash table...for some reason this is quite slow..can some one help me make it faster... f = open(filename) lines = f.readlines() def create_words(lines): cnt = 0 spl_set = '[",;<>{}_&?!():-[\.=+*\t\n\r]+' for content in lines: words=content.split() countDict={} wordlist = [] for w in words: w=string.lower(w) if w[-1] in spl_set: w = w[:-1] if w != '': if countDict.has_key(w): countDict[w]=countDict[w]+1 else: countDict[w]=1 wordlist = countDict.keys() wordlist.sort() cnt += 1 if countDict != {}: for word in wordlist: print (word+' '+ str(countDict[word])+'\n') From steve at REMOVETHIScyber.com.au Wed Nov 16 16:22:35 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 17 Nov 2005 08:22:35 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <437a5980$0$18815$636a55ce@news.free.fr> <437A9320.7040308@REMOVEMEcyber.com.au> <11nmeb7ma7nnuba@corp.supernews.com> Message-ID: On Wed, 16 Nov 2005 13:51:35 +0000, Ed Jensen wrote: > Steven D'Aprano wrote: >> I'm not sure if that is meant to be a rhetorical >> question or not, but something of the order of 95% of >> all software written is never distributed to others, >> and so copyright or the lack of copyright is not an issue. > > Can you cite your source(s) for this information? Not easily, but I will try. If it helps, I will clarify what I was talking about -- in hindsight it is a little unclear. Most software written (I think about 95%) is by companies for in-house use only. Since it never gets distributed outside of the company using it, copyright is of little additional value. -- Steven. From carsten at uniqsys.com Thu Nov 10 17:07:51 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 Nov 2005 17:07:51 -0500 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131639786.958533.45070@z14g2000cwz.googlegroups.com> Message-ID: <1131660471.26926.157.camel@dot.uniqsys.com> On Thu, 2005-11-10 at 16:53, Steven D'Aprano wrote: > Dude, a comprehension protection for *any* software can never be built > because of the fundamental nature of computers. Trying to stop bytes from > being copyable is like trying to stop water from being wet, and once > copied, all copies are identical and therefore indistinguishable. +1 QOTW! -- Carsten Haese - Software Engineer | Phone: (419) 794-2531 Unique Systems, Inc. | FAX: (419) 893-2840 1687 Woodlands Drive | Cell: (419) 343-7045 Maumee, OH 43537 | Email: carsten at uniqsys.com From durumdara at mailpont.hu Wed Nov 30 05:03:55 2005 From: durumdara at mailpont.hu (durumdara at mailpont.hu) Date: Wed, 30 Nov 2005 11:03:55 +0100 Subject: sha1,256,512 on files Message-ID: <438D790B.8080505@mailpont.hu> Hi ! I have a problem in Windows. I need to get the filelist in HDD-s, with sha-N value for every file (to see what changed in the past). 1. I see that Python supports the sha-1. But I need to make sha value in big files to (swap file, iso-s, etc.). Possible that file size more than 2 GB, so I cannot read as string... How to get the sha value of a file ? If python not supports that, please give me a link with freeware command line utility that can do it,and can pass to python. 2. How to generate sha-256, or sha-512 values ? Thanx for every help: dd From mwm at mired.org Tue Nov 8 17:30:27 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 17:30:27 -0500 Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131455018.179436.230410@g44g2000cwa.googlegroups.com> Message-ID: <86u0em7oxo.fsf@bhuda.mired.org> "Xah Lee" writes: > Newsgroups: comp.lang.perl.misc > PS: I won't cross-post as I'm not subscribed to the Python group. Very wisely done. Then from Xah Lee, we get; > I have cross posted it for you. Proving once again that he's stupider than spam. Please help google find him that way by adding this link to your pages: stupider than spam thank you, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jeff at schwabcenter.com Tue Nov 8 12:56:26 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Tue, 08 Nov 2005 17:56:26 GMT Subject: which feature of python do you like most? In-Reply-To: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: zelzel.zsu at gmail.com wrote: > which feature of python do you like most? > > I've heard from people that python is very useful. > Many people switch from perl to python because they like it more. > > I am quite familiar with perl, I've don't lots of code in perl. > Now, I was curious and interested in the python people. > They certainly made their best choice from perl to python. > > but i have no interesting python experence before, thought i've read a > few chapters > of a python tutorial book. The things are much like the perl one. > > I have no idea why people are so facinating with python. > So I post this question: What do you use in your dairy work with > python? > what is the thing that python makes you happy? > > > I certainly don't want to miss a language if it's so great! > can anyone share your happy experence with python? > I love Perl. I have started using Python more, partially because it's in vogue, but largely because hastily written code seems to come out "cleaner." One certainly can write clear, maintainable code in Perl, but doing so in Python feels a bit more natural. For example: - Object orientation was a design goal of Python, but had to be retrofitted onto Perl. - Every module I write in Perl contains: use warnings; # Should have been the default. use strict; # Check for dubious constructs. # Probably some export code like this: our @ISA = qw( Exporter ); our @EXPORT_OK = ( # ... ); # "Real" code. # ... 1 # Return good value on import. In Python, none of this is necessary. - Python knows what indentation means, so I get to skip a lot of curly braces. For one-liners, I still use Perl, specifically because: - I don't have to import "os" and "sys" modules just to basic tasks like issuing system commands. - Perl will auto-vivify variables with reasonable default values. E.g., if I ++$count, Perl has enough intuition to know that I wanted $count initialized to zero. - Perl lets me use very clean syntax for subroutine invocation, e.g. by skipping parentheses and being aware of (list or scalar) context. Hope this helps. From steve at REMOVETHIScyber.com.au Sat Nov 26 05:01:52 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 26 Nov 2005 21:01:52 +1100 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: On Fri, 25 Nov 2005 11:30:46 -0800, mojosam wrote: > I guess I don't care too much about how other people use it. Then probably the best licence to use is just to follow the lead of Python. For that sort of small program of limited value, I put something like this in the code: Copyright (c) 2005 Steven D'Aprano. Released under the same license as used by Python 2.3.2 itself. See http://www.python.org/psf/license.html for details, and http://www.python.org/2.3.2/license.html for the full text of the license. I use that as a no-brainer licence: it is weaker than but compatible with the GPL, and requires less documentation. > I will be doing the bulk of the coding on my own time, because I need to > be able to take these tools with me when I change employers. However, > I'm sure that in the course of using these tools, I will need to spend > time on the job debugging or tweaking them. I do not want my current > employer to have any claim on my code in any way. Usually if you > program on company time, that makes what you do a "work for hire". I > can't contaminate my code like that. Does that mean the GPL is the > strongest defense in this situation? Not at all. I am not a lawyer and this is not legal advice, but I suggest that your *only* defence will be to get your employer to sign a legal agreement acknowledging that you own the code. If you like, offer them a perpetual royalty-free non-exclusive licence to use the code, and explain how using your own code will make you more productive in their time. If they refuse, then you must absolutely keep a cast-iron barrier between what you develop in your own time and what you develop in theirs. To be safe, I wouldn't even *use* that code in their time: if your productivity suffers, that's their choice. As an alternative, consider that who owns the copyright doesn't matter. If your employer insists on keeping the copyright, get permission from them to distribute the code under an open source licence. Then you can take it with you when you leave, and still use it. Unless you explicitly sign them away (and even that is legally dubious) you still retain the "moral rights" to the code, even if copyright is owned by your employer: you can still say "I wrote this". Please note that merely putting the code under a GPL or other OSS licence is NOT sufficient -- they must agree to let you DISTRIBUTE the code. Merely being under the GPL does not make it compulsory to distribute the code, and if you distribute software copyrighted by your employer without their permission, the fact that is GPLed is not going to save you. Getting permission to put it up on the corporate website might be sufficient, but if it were me, I'd insist on an agreement allowing me to take the code with me when I leave. (This is only necessary if your employer owns the copyright.) It need not be a complicated agreement: I recently signed a copyright transfer agreement for some employees who left the company to start their own company. The agreement was less than two pages long. -- Steven. From dudufigueiredo at gmail.com Thu Nov 17 20:48:06 2005 From: dudufigueiredo at gmail.com (Dudu Figueiredo) Date: 17 Nov 2005 17:48:06 -0800 Subject: Rename files with numbers In-Reply-To: <20051113201629.10B3.0.NOFFLE@dieschf.news.arcor.de> References: <1130776390.085587.116270@g43g2000cwa.googlegroups.com> <1130784747.373637.108040@g14g2000cwa.googlegroups.com> <20051113201629.10B3.0.NOFFLE@dieschf.news.arcor.de> Message-ID: <1132278486.296425.145420@z14g2000cwz.googlegroups.com> thanks, i'll take a look ;] From darkpaladin79 at gmail.com Thu Nov 3 21:35:46 2005 From: darkpaladin79 at gmail.com (Ivan Shevanski) Date: Thu, 3 Nov 2005 21:35:46 -0500 Subject: putting an Icon in "My Computer" In-Reply-To: <1131071329.475037.289140@g47g2000cwa.googlegroups.com> References: <1131071030.209405.37800@z14g2000cwz.googlegroups.com> <1131071329.475037.289140@g47g2000cwa.googlegroups.com> Message-ID: <17d4ae400511031835w58e245baufc5f2f1656b22d6@mail.gmail.com> On 3 Nov 2005 18:28:49 -0800, Brett Hoerner wrote: > > > I've been asked by my boss to put an Icon in WinXP's "My Computer" for > > a utility we use around the shop. My tool of choice is of course > > Python and therefore what I am using to attempt my given task. I have > > no trouble putting Icons in the WinXP Toolbar using Python, but have > > totally failed to get an Icon to appear in My Computer. Any Idea on > > why and maybe how to get around this using Python? > > I'm pretty sure the My Computer menu is limited to devices and special > Windows folders like My Documents, etc. I've never seen a program add > an icon there, and I don't think its allowed through the API. > > -- > http://mail.python.org/mailman/listinfo/python-list > If this can be achieved at all, it would be through the windows registry. I know you can change all the icons for the recycle bin and special folders through it. . .I would figure adding folders might even be under the same key. Try google. -Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: From nephish at xit.net Wed Nov 2 15:21:11 2005 From: nephish at xit.net (nephish at xit.net) Date: 2 Nov 2005 12:21:11 -0800 Subject: question about urllib and parsing a page In-Reply-To: <1130960613.557180.6800@g43g2000cwa.googlegroups.com> References: <1130957593.322210.185450@o13g2000cwo.googlegroups.com> <1130960613.557180.6800@g43g2000cwa.googlegroups.com> Message-ID: <1130962871.754444.179810@g43g2000cwa.googlegroups.com> well, i think thats the case, looking at the code, there is a long string of math functions in page, java math functions. hmmmm. i guess i'm up that famous creek. thanks for the info, though shawn From fredrik at pythonware.com Tue Nov 8 05:39:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Nov 2005 11:39:32 +0100 Subject: Sorting Documentation References: <1131445649.614209.180310@g14g2000cwa.googlegroups.com> Message-ID: pinkfloydhomer at gmail.com wrote_ >I want to read a little bit about sorting in Python (sorted() and > method sort()). But I can't seem to find anything in the documentation > at the homepage? sorted() is a function that works on arbitrary sequences, and is described in the "built-in functions" chapter: http://www.python.org/doc/current/lib/built-in-funcs.html sort() is a list method, and is documented under sequences: http://www.python.org/doc/current/lib/typesseq-mutable.html From steve at REMOVETHIScyber.com.au Tue Nov 8 09:00:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 09 Nov 2005 01:00:26 +1100 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> Message-ID: On Tue, 08 Nov 2005 01:31:31 -0800, pinkfloydhomer at gmail.com wrote: > So there is no way in Python to make an alias for an object? Yes, sort of. Bind two names to the same mutable object: py> x = ["Something mutable"] py> y = x py> y.append("this way comes.") py> print x ['Something mutable', 'this way comes.'] Note that this only works with mutable objects like lists and dicts, and is a side effect of mutability, rather than a deliberate "alias". In general, you can bind multiple names to the same object. The one liner x = y = 1 is the same as the two liner x = 1 y = x Both create two names, x and y, and sets them both to the same int 1. Because ints are immutable, if you rebind one name, the other one will NOT change: py> x += 1 py> print x, y 2, 1 -- Steven. From dont at spam.me Sun Nov 6 22:03:35 2005 From: dont at spam.me (Bugs) Date: Sun, 06 Nov 2005 19:03:35 -0800 Subject: PyFLTK - an underrated gem for GUI projects In-Reply-To: References: Message-ID: Peter Hansen wrote: > > The wxPython program below, py2exe'd on my machine (1.6GHz Pentium M), > comes to only 12MB (2-3MB of which is Python itself), and takes 1-2 > seconds to load (actually less than one second after the first > invocation following a fresh reboot). > And even 12MB seems heavy, unless I created my exe with py2exe incorrectly... I created the singlefile gui demo app that comes with py2exe (test_wx) and it's only 4.6MB on my WinXP machine, 3.6MB when compressed with UPX. Anyone else get the same results? From david.rasmussen at gmx.net Mon Nov 14 05:25:44 2005 From: david.rasmussen at gmx.net (David Rasmussen) Date: Mon, 14 Nov 2005 11:25:44 +0100 Subject: HTTP Keep-Alive with urllib2 Message-ID: <43786620$0$2103$edfadb0f@dtext02.news.tele.dk> Someone once asked about this an got no answer: http://groups.google.dk/group/comp.lang.python/browse_frm/thread/c3cc0b8d7e9cbc2/ff11efce3b1776cf?lnk=st&q=python+http+%22keep+alive%22&rnum=84&hl=da#ff11efce3b1776cf Maybe I am luckier :) Does anyone know how to do Keep-Alive with urllib2, that is, how to get a persistent HTTP connection, instead of a new connection being opened for every request? /David From bignose+hates-spam at benfinney.id.au Sun Nov 20 16:59:04 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 21 Nov 2005 08:59:04 +1100 (EST) Subject: ownership problem? References: Message-ID: Gabriel Zachmann wrote: > Is it correct to say that the typical ownership problem, which > frequently arises in C++, does not occur normally in Python? Could you explain what you mean by "the typical ownership problem"? -- \ "Jealousy: The theory that some other fellow has just as little | `\ taste." -- Henry L. Mencken | _o__) | Ben Finney From fredrik at pythonware.com Wed Nov 23 15:09:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 21:09:15 +0100 Subject: Reading binary data References: <1132769538.319905.272190@z14g2000cwz.googlegroups.com> <1132773947.735958.240450@g49g2000cwa.googlegroups.com> Message-ID: "David M" wrote: > What are u_ini16_t and comp_t? comp_t is explained in the file you posted: > /* > comp_t is a 16-bit "floating" point number with a 3-bit base 8 > exponent and a 13-bit fraction. See linux/kernel/acct.c for the > specific encoding system used. > */ > > typedef u_int16_t comp_t; as the comment says, comp_t is a 16-bit value. you can read it in as an integer, but you have to convert it to a floating point according to the encoding mentioned above. the typedef says that comp_t is stored as a u_int16_t, which means that it's 16-bit value too. judging from the name, and the fields using it, it's safe to assume that it's an unsigned 16-bit integer. > And what about the enum section? it just defines a bunch of symbolic values; AFORK is 1, ASU is 2, etc. > enum > { > AFORK = 0x01, /* Has executed fork, but no exec. */ > ASU = 0x02, /* Used super-user privileges. */ > ACORE = 0x08, /* Dumped core. */ > AXSIG = 0x10 /* Killed by a signal. */ > }; at this point, you should be able to do a little experimentation. read in a couple of bytes (64 bytes should be enough), print them out, and try to see if you can match the bytes with the description above. import struct f = open(filename, "rb") data = f.read(64) # hex dump print data.encode("hex") # list of decimal byte values print map(ord, data) # struct test (keep adding type codes until you're sorted everything out) format = "BHHHHHH" print struct.unpack(format, struct.calcsize(format)) From http Thu Nov 24 18:50:00 2005 From: http (Paul Rubin) Date: 24 Nov 2005 15:50:00 -0800 Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> <871x15vcdc.fsf@lucien.dreaming> Message-ID: <7xsltlk3mf.fsf@ruckus.brouhaha.com> bkhl at stp.lingfil.uu.se (Bj?rn Lindstr?m) writes: > As I said before, I think you're confusing the (in Python pretty > non-existent) concept of encapsulation with Python's immutable types, > which are immutable because the implementation demands it. (A fact I > hope will disappear at some point.) What implementation demand? If Python's designers wanted mutable strings or tuples, Python could have them. Python strings and tuples are immutable by design, not by accident of implementation. Wanting to make immutable class instances out of the same design considerations is perfectly reasonable. From mwm at mired.org Tue Nov 8 21:02:18 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 21:02:18 -0500 Subject: Goto XY References: <1131499644.561039.16420@g14g2000cwa.googlegroups.com> Message-ID: <861x1qa89h.fsf@bhuda.mired.org> ale.of.ginger at gmail.com writes: > Is there some command in python so that I can read a key's input and > then use a gotoxy() function to move the cursor on screen? e.g.: > (psuedo-code) > > When the right arrow is pushed, cursor gotoxy(x+1,y) You want curses. A version is included in the standard library if you're on Unix. If you're on Windows, there are third party curses libraries. You should be able to install that and then build the curses module against it. If you're not on either of those two - tell us what you're using, and maybe someone who knows that system will answer you. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From apardon at forel.vub.ac.be Fri Nov 4 04:07:38 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 09:07:38 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> Message-ID: Op 2005-11-03, Steven D'Aprano schreef : > On Thu, 03 Nov 2005 13:35:35 +0000, Antoon Pardon wrote: > >> Suppose I have code like this: >> >> for i in xrange(1,11): >> b.a = b.a + i >> >> Now the b.a on the right hand side refers to A.a the first time through >> the loop but not the next times. I don't think it is sane that which >> object is refered to depends on how many times you already went through >> the loop. > > Well, then you must think this code is *completely* insane too: > > py> x = 0 > py> for i in range(1, 5): > ... x += i > ... print id(x) > ... > 140838200 > 140840184 > 140843160 > 140847128 > > Look at that: the object which is referred to depends on how many times > you've already been through the loop. How nuts is that? It is each time the 'x' from the same name space. In the code above the 'a' is not each time from the same namespace. I also think you new very well what I meant. -- Antoon Pardon From bonono at gmail.com Tue Nov 8 05:17:57 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 8 Nov 2005 02:17:57 -0800 Subject: Addressing the last element of a list In-Reply-To: <1131443023.638868.212340@f14g2000cwb.googlegroups.com> References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> Message-ID: <1131445077.629327.312670@g47g2000cwa.googlegroups.com> If you want to do what you want(though I don't know why without a concrete example), just store a mutable object at lst[42]["pos"], like this : lst[42]["pos"] = [1] a = lst[42]["pos"] a[0] = 2 assert(lst[42]["pos"][0] == 2) pinkfloydhomer at gmail.com wrote: > But if lst[42]["pos"] happens to hold an integer value, then > > a = lst[42]["pos"] > > will _copy_ that integer value into 'a', right? Changing 'a' will not > change the value at lst[42]["pos"] From mclaugb at nospm.yahoo.com Wed Nov 9 06:49:15 2005 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Wed, 9 Nov 2005 11:49:15 -0000 Subject: debugger References: <1131474688.096736.173480@z14g2000cwz.googlegroups.com> <1131476294.676867.161230@f14g2000cwb.googlegroups.com> Message-ID: is there a way to only look at specific variable names in Winpdb? It takes forever to debug something when i constantly have to search for variables. wrote in message news:1131476294.676867.161230 at f14g2000cwb.googlegroups.com... > > Benji York wrote: >> robert.dowell at gmail.com wrote: >> > Benji York wrote: >> >>You might like Winpdb: >> >>http://www.digitalpeers.com/pythondebugger/ >> > >> > Not Found >> > >> > The requested URL /pythondebugger/-- was not found on this server. >> > Apache/2.0.52 (Red Hat) Server at www.digitalpeers.com Port 80 >> >> Works for me. >> -- >> Benji York > > Yeah, for some reason my browser was appending /-- to the link. I > figured that out (little slow today) and pulled my post. > From bobueland at yahoo.com Sat Nov 12 12:10:43 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 12 Nov 2005 09:10:43 -0800 Subject: newbie how do I interpret this? Message-ID: <1131815443.308190.198850@g14g2000cwa.googlegroups.com> Here's a small session >>> import re >>> p=re.compile('[a-z]+') >>> m=p.match('abb1a') >>> dir(m) ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start'] >>> help(m.groups) Help on built-in function groups: groups(...) >>> My question is. How do I interpret the hiven help info groups(...) alt1. Tough luck. There's no help. People are to busy to write reference manuals. alt 2. There are no parameters. The only possibility is m.groups() alt3. Something else Thanks Bob From mwm at mired.org Fri Nov 18 18:37:29 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 18 Nov 2005 18:37:29 -0500 Subject: Choose meaningful subjects for posts References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> <86u0eaj5ed.fsf@bhuda.mired.org> <11nsbh2r64kb9ae@corp.supernews.com> <17278.14762.150392.942325@montanaro.dyndns.org> Message-ID: <868xvljznq.fsf@bhuda.mired.org> Micah Elliott writes: > On Nov 18, skip at pobox.com wrote: >> Grant> Obligatory aside: I'm completely baffled why anybody would choose >> Grant> the mailing list format over Usenet. I don't even read mailing >> Grant> lists via mailing lists. I recommend gmane.org's NNTP server for >> Grant> all your mailing list needs. >> For the same reason I don't like web forums as a means of >> communication. I would much rather operate in an interrupt-driven >> mode than have to remember to poll some external service to get my >> daily helping of information. > Agreed! That's actually how I decide which form I want to use. Mail lists for thigns I want to interrupt me, newsgroups for things I want to poll. > If you have any suggestions for console-based newsreaders, I'm all > ears. I have tried to setup "tin" in the past but the voluminosity of > its documentation made me give up. Gnus. Not only will it run in a console, but when run in an X environment, it'll give you (user-configurable) menu bars, tool bars, and clickable articles. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From maillist at roomity.com Fri Nov 4 17:15:45 2005 From: maillist at roomity.com (shenanigans) Date: Fri, 4 Nov 2005 14:15:45 -0800 (PST) Subject: [OTAnn] Groups:New Developments at Roomity Message-ID: <24210046.151131142545493.JavaMail.tomcat5@slave1.roomity.com> I was interested in getting feedback from current communities of Roomity.com and let you know the recent improvements we are working on for better interface. Roomity.com v 1.5 is a web 2.01/RiA poster child community webapp. This new version adds broadcast video, social networking such as favorite authors and html editor. Its likely already you have groups and content you are already using but aggregated and safer, including technology, Java, etc., but it only works on broadband. S. *This is not spam! I work for Roomity and are trying to find better ways to enhance our members' experience. -------------------------------------------------------------------------------------------------------------------------------------------------------- Broadband interface (RIA) + mail box saftey = Python_General_Discussion_List.roomity.com *Your* clubs, no sign up to read, ad supported; try broadband internet. ~~1131142545482~~ -------------------------------------------------------------------------------------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Nov 23 12:21:45 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 18:21:45 +0100 Subject: strange behaviour when writing a large amount of data on stdout References: Message-ID: Manlio Perillo wrote: > So, it's seem to be a specific problem of Windows XP(?). > > Nobody can test it on a Windows 98/2000 machine? works fine on assorted XP and 2000 boxes for me. is the "n = 61409 + 1" stuff necessary, or do you get the same problem for all outputs over a given size ? even if you just do, say, print '*'*61410 ? does print '*'*61409 work? is it always the same number, or does it vary depending on, say, what other programs you're using, how much you've already printed to the console, etc. are you using a standard cmd.exe in a standard console? no cygwin or other oddities? From bignose+hates-spam at benfinney.id.au Sat Nov 12 16:47:02 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Nov 2005 08:47:02 +1100 (EST) Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> Message-ID: Pierre Barbier de Reuille wrote: > This proposal suggests to add symbols into Python. I still don't think "symbol" is particularly descriptive as a name; there are too many other things already in the language that might also be called a "symbol". > Symbols are objects whose representation within the code is more > important than their actual value. An interesting > Two symbols needs only to be equally-comparable. I believe it would be more useful to have enumerated types in Python, which would also allow values from the same type to be cmp() compared. > Currently, there is no obvious way to define constants or states or > whatever would be best represented by symbols. "constants" isn't a good equivalent here, since constants in most other languages are all about the name-to-value mapping, which you said was unimportant for this concept. > Discussions on comp.lang.python shows at least half a dozen way to > replace symbols. s/replace/implement/ > Some use cases for symbols are : state of an object (i.e. for a file > opened/closed/error) and unique objects (i.e. attributes names could > be represented as symbols). That pretty much covers the common use cases. Nicely done. > First, I think it would be best to have a syntax to represent > symbols. I disagree. Namespaces would be fine, and would also make clear which values were related to each other; e.g. for your "state of an object" use case, it's useful to have all the states in one namespace, separate from unrelated states of other classes of objects. > Adding some special char before the name is probably a good way to > achieve that : $open, $close, ... are $ymbols. Counterproposal: FileState = SomeTypeDefiningStates( 'open', 'closed' ) thefile.state = FileState.open if thefile.state == FileState.closed: print "File is closed" So all that's needed here is the type SomeTypeDefiningStates, not a new syntax. > One possible way to implement symbols is simply with integers > resolved as much as possible at compile time. I believe all your requirements and motivations could be met with an Enum type in the language. Here's an implementation using a sequence of integers for the underlying values: "First Class Enums in Python" An enumerated type would also allow values from that type to be compared with cmp() if their sequence was considered important. e.g. for object state, the "normal" sequence of states could be represented in the enumeration, and individual states compared to see if they are "later" that each other. If sequence was not considered important, of course, this feature would not get in the way. -- \ "I put instant coffee in a microwave oven and almost went back | `\ in time." -- Steven Wright | _o__) | Ben Finney From jstroud at mbi.ucla.edu Sun Nov 6 21:22:47 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 6 Nov 2005 18:22:47 -0800 Subject: text widget example? In-Reply-To: <1131323136.640414.143030@f14g2000cwb.googlegroups.com> References: <1131323136.640414.143030@f14g2000cwb.googlegroups.com> Message-ID: <200511061822.47964.jstroud@mbi.ucla.edu> On Sunday 06 November 2005 16:25, wanwan wrote: > I need my GUI to open and display a text file. I'm thinking of using a > text widget but it looks so complicated in the tkinter manual. > > question I have is: > > is there an example anyone can find on the internet? Couldn't find a good one, so here's a 5 minute version (your exercise is to put in a scroll bar). See: http://www.pythonware.com/library/tkinter/introduction/ James from Tkinter import * import tkFileDialog import tkMessageBox class MyText(Frame): def __init__(self, parent=None, *args, **kwargs): Frame.__init__(self, parent) self.pack() self.text = Text(self, *args, **kwargs) self.text.config(background='white') self.text.pack(expand=YES, fill=BOTH) def get(self): return self.text.get(1.0,"%s-1c" % END) def set(self, astr): self.text.delete(1.0, END) self.text.insert(INSERT, astr) def set_from_file(self): afilename = tkFileDialog.askopenfilename() if afilename: try: afile = open(afilename) self.set(afile.read()) afile.close() except Exception, e: tkMessageBox.showwarning("File Problem", "Couldn't read file '%s': %s" % (afilename, str(e))) def main(): tk = Tk() tk.title('Text Reader App') atext = MyText(tk) atext.pack() open_button = Button(tk, text="Open File", activeforeground='blue', command=atext.set_from_file) open_button.pack() tk.mainloop() if __name__ == "__main__": main() -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From superprad at gmail.com Tue Nov 1 14:09:10 2005 From: superprad at gmail.com (PyPK) Date: 1 Nov 2005 11:09:10 -0800 Subject: Add attribute using pyxml Message-ID: <1130872149.945270.218070@g44g2000cwa.googlegroups.com> How do I add a new attribute to the existing xml Document tree??? From calfdog at yahoo.com Thu Nov 3 13:44:07 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 3 Nov 2005 10:44:07 -0800 Subject: Web automation (was: Pressing a Webpage Button) In-Reply-To: <1131042041.155434.254810@g44g2000cwa.googlegroups.com> References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> <1131042041.155434.254810@g44g2000cwa.googlegroups.com> Message-ID: <1131043447.905201.9860@g44g2000cwa.googlegroups.com> Twill or Pamie looks good, if your looking for a solution using Python. If you are looking for Cross- browser solution for testing there is also selenium that does that. The have some code for use in Python. There is also WATIR in RUBY and SAMIE in PERL It depends on your enviroment and needs. Hope that helps!! Rob M. From mhellwig at xs4all.nl Sat Nov 26 05:05:25 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 26 Nov 2005 11:05:25 +0100 Subject: wxPython Licence vs GPL In-Reply-To: References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> <86oe49wyky.fsf@bhuda.mired.org> <43863e25$0$11061$e4fe514c@news.xs4all.nl> Message-ID: <4388336c$0$11063$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > On Thu, 24 Nov 2005 23:26:38 +0100, Martin P. Hellwig wrote: > >> BSD/MIT style license is a >> good substitute of no license at all. > > But that's not true: "no licence at all" means that nobody has the right > to use or copy or even *see* your work. You can, of course, choose to > show them your work without a licence, but unless you give them a licence > they can't legally do anything with it. > > Perhaps you are thinking of the public domain, which does not require a > licence, but that is because it is not owned by anyone -- not even you, > the creator. > > If you want to release your work with no restrictions whatsoever, then > just put the work in the public domain. Is attribution really that > important to you -- especially when that attribution may be buried deep in > the source code of software which nobody will ever see? > > Well I don't know how it's legally outside (most of) the EU, but here if your are actioned in publishing information of any kind (including source code) without restricting it, you can not refer to any copyrights or protected IP thereafter, but you still are responsible for the consequences of your action if the results are related to a more or less unmodified version of your publishing. Of course you still have the right to claim to be the original author and accuse anybody else who falsely claim that as plagiarist. -- mph From bonono at gmail.com Tue Nov 22 19:32:25 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 16:32:25 -0800 Subject: Converting a flat list to a list of tuples In-Reply-To: <4383897d.489297222@news.oz.net> References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <438301ef$0$29180$8fcfb975@news.wanadoo.fr> <1132674151.370320.100130@g44g2000cwa.googlegroups.com> <4383897d.489297222@news.oz.net> Message-ID: <1132705945.406071.137590@z14g2000cwz.googlegroups.com> Bengt Richter wrote: > On 22 Nov 2005 07:42:31 -0800, "George Sakkis" wrote: > > >"Laurent Rahuel" wrote: > > > >> Hi, > >> > >> newList = zip(aList[::2], aList[1::2]) > >> newList > >> [('a', 1), ('b', 2), ('c', 3)] > >> > >> Regards, > >> > >> Laurent > > > >Or if aList can get very large and/or the conversion has to be > >performed many times: > > > >from itertools import islice > >newList = zip(islice(aList,0,None,2), islice(aList,1,None,2)) > > > Or, if you want to include fractional groups at the end > > >>> aList = ['a', 1, 'b', 2, 'c', 3] > >>> from itertools import groupby > >>> def grouper(n): > ... def git(): > ... while True: > ... for _ in xrange(n): yield 0 > ... for _ in xrange(n): yield 1 > ... git = git() > ... def grouper(_): return git.next() > ... return grouper > ... > >>> [tuple(g) for _, g in groupby(aList, grouper(2))] > [('a', 1), ('b', 2), ('c', 3)] > >>> [tuple(g) for _, g in groupby(aList, grouper(3))] > [('a', 1, 'b'), (2, 'c', 3)] > >>> [tuple(g) for _, g in groupby(aList, grouper(4))] > [('a', 1, 'b', 2), ('c', 3)] > Personally, I would like to see it as [('a',1,'b',2), ('c',3, None,None)], as a list of tuple of equal length is easier to be dealt with. i = iter(aList) zip(i,chain(i,repeat(None)), chain(i,repeat(None)),chain(i,repeat(None))) From mwm at mired.org Sat Nov 5 23:26:26 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 23:26:26 -0500 Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> <7x4q6q7f6b.fsf@ruckus.brouhaha.com> <86hdaqsfjo.fsf@bhuda.mired.org> <7x3bmafrip.fsf@ruckus.brouhaha.com> <86d5lescfd.fsf@bhuda.mired.org> <7x8xw2ea4e.fsf@ruckus.brouhaha.com> Message-ID: <86fyqa4d1p.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> > It's only -because- of those licenses that there's any reason not to >> > bundle. >> Actually, there are other reasons, just as there are reasons besides >> licensing for not simply including third party libraries into the >> standard library. > > I'm not talking about 3rd party libraries, I'm talking about 3rd party > documentation for modules that are already in the Python standard > library. So am I. My point is that many of the considerations as to why you don't simply include a module in the library also apply when it comes to including documentation in the distribution. I gave some examples, including why they were important for *documentation*, but you carefully elided those. > For example, if someone wrote a good Tkinter manual that > were licensed in a way that the PSF could drop it into the Python > distro, then PSF should certainly consider including it. The same > goes for good docs about urllib2, or various other modules that > currently have lousy docs. The key word is "consider". They have to deal with all the issues I pointed out before, of which licensing is just the beginning. > Sorry, I meant: > http://infohost.nmt.edu/tcc/help/pubs/tkinter/ (html) > http://www.nmt.edu/tcc/help/pubs/tkinter.pdf (pdf of same) > You've probably seen this manual already. Yes, I have. I still say the only good documentation is Grayson's book. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From eyubin at gmail.com Thu Nov 3 07:52:40 2005 From: eyubin at gmail.com (ice) Date: 3 Nov 2005 04:52:40 -0800 Subject: how to write a blog system with Python In-Reply-To: References: <1130986622.788569.225120@o13g2000cwo.googlegroups.com> Message-ID: <1131022360.558821.74240@f14g2000cwb.googlegroups.com> Thanks for all your comments. What I wanted is a chance to practise my programming talents with Python. From deets at nospam.web.de Sat Nov 26 07:14:11 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 26 Nov 2005 13:14:11 +0100 Subject: icmp - should this go in itertools? In-Reply-To: References: Message-ID: <3ur1skF12cnirU1@uni-berlin.de> Tom Anderson wrote: > Hi all, > > This is a little function to compare two iterators: > > > > def icmp(a, b): > for xa in a: > try: > xb = b.next() > d = cmp(xa, xb) > if (d != 0): > return d > except StopIteration: > return 1 > try: > b.next() > return -1 > except StopIteration: > return 0 > > > > It's modelled after the way cmp treats lists - if a and b are lists, > icmp(iter(a), iter(b)) should always be the same as cmp(a, b). > > Is this any good? Would it be any use? Should this be added to itertools? Whilst not a total itertools-expert myself, I have one little objection with this: the comparison won't let me know how many items have been consumed. And I end up with two streams that lack some common prefix plus one field. I'm just not sure if there is any usecase for that. However, _if_ there is one, I'm all for adding it to itertools - it seems to be in the appropriate spirit. Regards, Diez From fredrik at pythonware.com Wed Nov 9 15:06:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 21:06:07 +0100 Subject: Floating numbers and str References: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> Message-ID: "Tuvas" wrote: >I would like to limit a floating variable to 4 signifigant digits, when > running thorugh a str command. Ei, > > x=.13241414515 > y=str(x)+" something here" > > But somehow limiting that to 4 sign. digits. I know that if you use the > print statement, you can do something like %.4d, but how can I do this > with converting the number to a string? Thanks! you mean "%.4g" ? the % operator is a string operator, and can be used outside print: text = "%.4g" % value for more details, here's the first google hit for "python string formatting": http://docs.python.org/lib/typesseq-strings.html but that doesn't make too much sense if you don't know how things work in C, which is explained here: http://www.cplusplus.com/ref/cstdio/printf.html here are some examples: >>> x=.13241414515 >>> x 0.13241414515 >>> "%.4f" % x '0.1324' >>> "%.4g" % x '0.1324' >>> x=5.13241414515 >>> "%.4f" % x '5.1324' >>> "%.4g" % x '5.132' From klappnase at web.de Fri Nov 11 18:40:17 2005 From: klappnase at web.de (klappnase at web.de) Date: 11 Nov 2005 15:40:17 -0800 Subject: Ann.: Python wrapper for Tktreectrl Message-ID: <1131752417.176181.318580@g49g2000cwa.googlegroups.com> I wrote a Tkinter wrapper for the tktreectrl widget (). Tktreectrl is an advanced tool that lets you set up things like sortable multi column listboxes and tree browsers. The python module comes with a reference manual and a (very basic) demo script. The url is . Any reports, good or bad, are much appreciated. Regards Michael From graham.fawcett at gmail.com Wed Nov 2 09:24:29 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 2 Nov 2005 06:24:29 -0800 Subject: Python and Lotus Notes In-Reply-To: References: Message-ID: <1130941469.353649.195200@g14g2000cwa.googlegroups.com> Grzegorz Slusarek wrote: > Hello everyone. I have to get data from Lotus Notes and i curious is it > possible doing it with Python. I heard that Lotus Notes using COM, so > the Python does so maybe it can be done? Anyone have any experiences > doing that? > Ane help will by apreciated Yes, it's pretty simple. Quick example: from win32com.client import Dispatch session = Dispatch('Lotus.NotesSession') session.Initialize(MY_NOTES_PASSWORD) db = session.getDatabase(SERVER_NAME, DB_NAME) ... The LotusScript reference guide is almost completely applicable to Notes via COM. It can be useful to define some helper functions to make working with Notes a bit easier. For example, this is the (very clunky) way to iterate all documents in a Notes database, without helper code: view = db.getView('Important Docs') doc = db.getFirstDocument() while doc: do_something_with(doc) doc = view.getNextDocument(doc) You probably recognize the pattern from any LotusScript you've written. (It sure is easy to forget that last line...) But Python gives you far better control structures, like generators. It's worthwhile to define a few helper functions like this, in a common module: def iterateDocuments(docs): doc = docs.getFirstDocument() while doc: yield doc doc = docs.getNextDocument(doc) Then you can write much cleaner code, like this: for doc in iterateDocuments(view): do_something_with(doc) Similarly you can write iterator functions for traversing databases, ACL entries, etc. I also find these two defnitions useful: def get(doc, attr): return doc.getItemValue(attr) def get1(doc, attr): return get(doc, attr)[0] because it's a lot easier to write: user_name = get1(user_doc, 'FullName') than: user_name = user_doc.getItemValue('FullName')[0] Note that the attribute-access style that LotusScript allows, e.g. "user_doc.FullName(0)" does not work in Python/COM, hence you'll need getItemValue(), replaceItemValue(), etc.. You could write a wrapper for the NotesDocument class that would give you attributes like this. Personally, I find that to be more trouble than it's worth, but your needs be very different. Last warning: once you've tried using Python and COM, you'll scream whenever you have to write LotusScript, and you'll wish like crazy that Notes/Domino supported Python as a native scripting language. :-) Jython kind of works, but I never got it happily running for server-side code, alas. Graham From akameswaran at gmail.com Thu Nov 10 10:19:30 2005 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 10 Nov 2005 07:19:30 -0800 Subject: wxPython newbie question, creating "mega widgets" , and DnD Message-ID: <1131635970.831338.109280@g49g2000cwa.googlegroups.com> I've made the switch from tKinter to wxPython. I'm slowly trying to learn it, but I had a question - what is the appropriate object to subclass to create a "mega widget" ie A listbox with it's add/delete buttons already built in? wxPanel seems a possibility - any thoughts? A side question - why is their a EVT_LIST_BEGIN_DRAG but no EVT_LIST_END_DRAG, unlike tree's which have BEGIN and END? I need a draggable list box, and would prefer to not handle low level mouse events. From robert.dowell at gmail.com Fri Nov 4 15:42:22 2005 From: robert.dowell at gmail.com (robert.dowell at gmail.com) Date: 4 Nov 2005 12:42:22 -0800 Subject: Filepath string manipulation help In-Reply-To: References: <1130959950.485233.230230@z14g2000cwz.googlegroups.com> <1131032213.559554.163730@g14g2000cwa.googlegroups.com> <1131037470.042070.316820@g44g2000cwa.googlegroups.com> <1131109516.404190.173000@z14g2000cwz.googlegroups.com> Message-ID: <1131136942.427909.326710@g43g2000cwa.googlegroups.com> I just assumed he had heard of me and knew better than to take my advice. :-) From onurb at xiludom.gro Fri Nov 11 05:20:36 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 11 Nov 2005 11:20:36 +0100 Subject: derived / base class name conflicts In-Reply-To: <1131677456.966817.147470@g44g2000cwa.googlegroups.com> References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> <1131677456.966817.147470@g44g2000cwa.googlegroups.com> Message-ID: <43747075$0$7344$636a55ce@news.free.fr> christopherlmarshall at yahoo.com wrote: (snip) > So putting two underscores in front of an instance variable (or any > identifier used inside the scope of a class statement) invokes a name > mangling mechanism (snip) > Is it commonplace to use underscores I assume you mean double underscore... > when defining derived class > instance variables, > or is this considered against the grain of python? I don't know if it's 'commonplace', but that's something I only do when I absolutely want to protect a given attribute of a base class from being accidentally overriden by a derived class. Else I use the usual convention ('_name' => implementation, 'name' => API), and assume users of my code will read the documentation (or the source FWIW) before subclassing. Note that since 'users of my code' are mostly my coworkers and I, this is a quite sensible assumption !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at holdenweb.com Fri Nov 4 07:00:43 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Nov 2005 12:00:43 +0000 Subject: how to compile c-extensions under WinXP? In-Reply-To: References: Message-ID: severa at sophia.dtp.fmph.uniba.sk wrote: > What should I do to be able to compile C-extensions (with python 2.4, > winXP)? I get an error message, approximately "The .NET Framework SDK > needs to be installed"; I tried to get something from the Microsoft web > site, but maybe not the right version (or didn't set some variables), > since the error remains. Could you please help me (it will need some > patience with a computer newbie)? > See http://www.vrplumber.com/programming/mstoolkit and say thanks to Mike Farmer. 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 Nov 16 18:30:24 2005 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 16 Nov 2005 18:30:24 -0500 Subject: HTML generation vs PSP vs Templating Engines Message-ID: <777056A4A8F1D21180EF0008C7DF75EE033176CD@sunbelt.org> If this is your first try, use cgi, cgitb and html % dictionary as suggested in this thread. If your db is mysql, you can actually use os.popen() (or equivalent) to run a 'mysql -html -e "select * from yaddayadda" to return html. you can make that look prettier with css. here's a quick and dirty I just did. ===================================snip===================================== ======================= #!/usr/bin/python import os, string, sys, time, cgi, cgitb cgitb.enable(display=1) import ezcgi HTML = """ Snapshot of Administrative Bed Holds

Current Administrative Bed Holds at all Facilities

%s
%s
Copyright (C) 1996-2005, Adventist Care Centers, Inc. For Internal Use Only
Home| Logout """ COMMAND = ['mysql --host=acaredb --user=acare --password=acare -D census -H -e ', '"SELECT facility,wrb Room,description Reason,startdate, note Explanation', 'FROM admin_bed_holds h, abhreasons r ' 'WHERE h.reason=r.id ', ' ORDER BY facility;"'] COMMAND = ' '.join(COMMAND) def select_holds(): x = os.popen(COMMAND) table = x.read(6000) return HTML % ('', table) def execute(): if ezcgi.is_authenticated(): print ezcgi.HTML_CONTENT_TYPE print select_holds() else: ezcgi.authenticate_user() if __name__=='__main__': #print ezcgi.PLAIN_CONTENT_TYPE #print COMMAND execute() ===========================snip============================================= ========================= -----Original Message----- From: pkassianidis at gmail.com [mailto:pkassianidis at gmail.com] Sent: Wednesday, November 16, 2005 11:32 AM To: python-list at python.org Subject: HTML generation vs PSP vs Templating Engines Hello everybody, I am in the process of writing my very first web application in Python, and I need a way to generate dynamic HTML pages with data from a database. I have to say I am overwhelmed by the plethora of different frameworks, templating engines, HTML generation tools etc that exist. After some thought I decided to leave the various frameworks aside for the time being and use mod_python.publisher along with some means of generating HTML on the fly. Could someone that has used all the different ways mentioned above for dynamic HTML content, suggest what the pros and cons of the different methods are? Thank you very much in advance Panos -- http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------------- 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 roy at panix.com Sun Nov 27 19:04:00 2005 From: roy at panix.com (Roy Smith) Date: Sun, 27 Nov 2005 19:04:00 -0500 Subject: Writing pins to the RS232 References: <1132953944.656557.31910@g14g2000cwa.googlegroups.com> <3urg78F130gopU1@individual.net> <1133134832.031873.302400@g49g2000cwa.googlegroups.com> Message-ID: "jay.dow at gmail.com" wrote: > While I realize this is more on a driver/hardware level it's > interesting that it's so difficult to use a different protocol for an > existing driver. For example, all serial does is a series of high and > low voltages on specific pins. Why should it be so hard to use an > existing driver and hold a pin on high? It's been a long time since I've looked at this low-level hardware, but the answer is almost certainly, "No just 'so hard', but 'impossible'". A serial port is driven by a thing called a UART (Universal Asynchronous Receiver/Transmitter). Back when I was playing with these things, a UART was a discrete chip; these days I'm sure it's just a minor part of a more complex I/O processor, but I suspect the basic idea is the same. You load a character to be transmitted into a register on the UART and the hardware takes care of all the low-level gunk like clocking the bits out at the correct rate, adding start and stop bits, and computing parity. And the reverse for the receive side of the house (which is usually the more complicated part). There just isn't any way to tell the hardware to do anything other than it was designed to do. Could you design a piece of hardware which could function as both a serial port and what you want? Sure you could, but it would cost more, and PC design today is a matter of shaving 10 cents here and 30 cents there. It's like looking at a microwave oven and saying, "Can't this thing be reprogrammed to be a communications relay?" Well, sure, it's got some of the same parts, but the parts were put together in a way that makes food get hot, not in a way that makes data bits get transmitted to someplace. From bonono at gmail.com Fri Nov 25 12:10:02 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 25 Nov 2005 09:10:02 -0800 Subject: (newbie) N-uples from list of lists In-Reply-To: <1132776015.567869.214570@g14g2000cwa.googlegroups.com> References: <1132776015.567869.214570@g14g2000cwa.googlegroups.com> Message-ID: <1132938602.483207.74600@f14g2000cwb.googlegroups.com> This is my attempt : def cross(seq): r=[[]] for x in seq: r = [ a + b for a in r for b in [[i] for i in x ]] return r It is not very efficient though as it would loop through the intermediate list produced multiple times. vd12005 at yahoo.fr wrote: > Hello, > > i think it could be done by using itertools functions even if i can not > see the trick. i would like to have all available "n-uples" from each > list of lists. > example for a list of 3 lists, but i should also be able to handle any > numbers of items (any len(lol)) > > lol = (['a0', 'a1', 'a2'], ['b0', 'b1'], ['c0', 'c1', 'c2', 'c3']) > > => > > > [('a0', 'b0', 'c0'), ('a0', 'b0', 'c1'), ('a0', 'b0', 'c2'), ('a0', > 'b0', 'c3'), ('a0', 'b1', 'c0'), ('a0', 'b1', 'c1'), ('a0', 'b1', > 'c2'), ('a0', 'b1', 'c3'), ('a1', 'b0', 'c0'), ('a1', 'b0', 'c1'), > ('a1', 'b0', 'c2'), ('a1', 'b0', 'c3'), ('a1', 'b1', 'c0'), ('a1', > 'b1', 'c1'), ('a1', 'b1', 'c2'), ('a1', 'b1', 'c3'), ('a2', 'b0', > 'c0'), ('a2', 'b0', 'c1'), ('a2', 'b0', 'c2'), ('a2', 'b0', 'c3'), > ('a2', 'b1', 'c0'), ('a2', 'b1', 'c1'), ('a2', 'b1', 'c2'), ('a2', > 'b1', 'c3')] > > maybe tee(lol, len(lol)) can help ? > > it could be done by a recursive call, but i am interested in using and > understanding generators. > > i also have found a convenient function, here : > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65285 (paste > below) > but i am curious of how you will do it or refactorize this one with > generators... > > def permuteflat(*args): > outs = [] > olen = 1 > tlen = len(args) > for seq in args: > olen = olen * len(seq) > for i in range(olen): > outs.append([None] * tlen) > plq = olen > for i in range(len(args)): > seq = args[i] > plq = plq / len(seq) > for j in range(olen): > si = (j / plq) % len(seq) > outs[j][i] = seq[si] > for i in range(olen): > outs[i] = tuple(outs[i]) > return outs > > many thanx From duncan.booth at invalid.invalid Wed Nov 30 09:53:06 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2005 14:53:06 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: Antoon Pardon wrote: >> The left one is equivalent to: >> >> __anon = [] >> def Foo(l): >> ... >> >> Foo(__anon) >> Foo(__anon) > > So, why shouldn't: > > res = [] > for i in range(10): > res.append(i*i) > > be equivallent to: > > __anon = list() > ... > > res = __anon > for i in range(10): > res.append(i*i) Because the empty list expression '[]' is evaluated when the expression containing it is executed. > >> The left has one list created outside the body of the function, the >> right one has two lists created outside the body of the function. Why >> on earth should these be the same? > > Why on earth should it be the same list, when a function is called > and is provided with a list as a default argument? Because the empty list expression '[]' is evaluated when the expression containing it is executed. > > I see no reason why your and my question should be answered > differently. We are agreed on that, the answers should be the same, and indeed they are. In each case the list is created when the expression (an assigment or a function definition) is executed. The behaviour, as it currently is, is entirely self-consistent. I think perhaps you are confusing the execution of the function body with the execution of the function definition. They are quite distinct: the function definition evaluates any default arguments and creates a new function object binding the code with the default arguments and any scoped variables the function may have. If the system tried to delay the evaluation until the function was called you would get surprising results as variables referenced in the default argument expressions could have changed their values. From pydecker at gmail.com Sun Nov 6 15:36:25 2005 From: pydecker at gmail.com (Peter Decker) Date: Sun, 6 Nov 2005 15:36:25 -0500 Subject: Python gui In-Reply-To: <1131307703.160659.267170@g44g2000cwa.googlegroups.com> References: <436e3916$0$22284$4fafbaef@reader1.news.tin.it> <1131307703.160659.267170@g44g2000cwa.googlegroups.com> Message-ID: On 6 Nov 2005 12:08:23 -0800, gsteff wrote: > PyGTK is just easier to code with. The api is much nicer. That's why I think that Dabo's UI module is the best of all worlds. It wraps wxPython, so the controls look great on any platform, but provides a cleaner and more consistent API than raw wxPython. I almost never have to look up how to do something in Dabo, whereas I couldn't program in wxPython without the docs open. -- # p.d. From aleax at mail.comcast.net Wed Nov 23 11:11:54 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 08:11:54 -0800 Subject: about sort and dictionary References: <1132493880.591426.224140@g49g2000cwa.googlegroups.com> <1132651818.348370.117450@g49g2000cwa.googlegroups.com> <1132653873.855348.265740@g47g2000cwa.googlegroups.com> <1132700747.794586.73170@g44g2000cwa.googlegroups.com> <1h6g1t6.qxc6tnag2skbN%aleax@mail.comcast.net> <1132719140.781847.251410@z14g2000cwz.googlegroups.com> Message-ID: <1h6gyxh.1bqns7v1lw2frwN%aleax@mail.comcast.net> Magnus Lycka wrote: ... > >>indicate that the method is a mutator. So, you can have a.reverse [NOT > >>mutating a since no !] _and_ a.reverse! [mutating a]. Probably too much > >>of a change even for Python 3000, alas... but, it DOES make it obvious > >>when an object's getting mutated, and when not... > > Except when it isn't obvious. What constitutes mutation of an object? "Potential alteration of the object's state". [2,2,2] -- a list with three identical items -- may be subject to any permutation in-place, including sorting and reversing, without _actual_ alteration of state, just as, say, L[2]=2 MAY happen not to alter state if L[2] was already 2 before the assignment. However, such corner cases do not constitute any deep conceptual blockage to the notion of mutation, any more than, say, the possibility of state being empty (e.g in an empty tuple) constitues any to the notion of state. I classify list and dict methods as mutating and non-mutating in the Nutshell, for example, and nobody's quibbled about their usefulness. If you want to get more formal, you can focus on the post-condition (either in programming-by-contract terms, or the more formal Hoare and Djikstra ideas that preceded Pbc) using X' to mean "X as it was on entry": for any type T, a method M of T is said to be non-mutating iff, for any instance t of T, the strongest postcondition of calling M on t includes t == t' a method M is said to be mutating if it is not non-mutating Note how cleanly this deals (by delegating to ==, if you will;-) with the issue of whether 'non-observable state' (e.g. a cache) "counts" as state (answer: if it cannot influence the result of == it does not matter regarding this definition). Objects which cannot be compared for equality with their peers, or for which it is conceptually absurd to talk of "as it was", are always going to be problematic for any system of formal reasoning about programming, but the problem is with the formalization under such conditions (it's hard to do most any formal reasoning without equality, for example) and not with the pragmatics of the situation. > C++ handles this with 'const', and lets the programmer cheat by using > transient member variables, since there are cases when you actually > want to mutate objects a little, but claim that you don't... I think you mean volatile or mutable rather than transient? "transient" is not a keyword in C++, while both volatile and mutable are, with different semantics. Anyway, C++'s 'const' is a mess both theoretical AND practical. I'm told Ruby's "object-freezing" works better (but I have no practical experience). > Perhaps we need a.reverse? for just-mutating-a-little reverse as well? > ;^) I don't see the alleged humor in this ill-defined concept. Anyway, a trailing question mark is used in Ruby to indicate a predicate (a non mutator which returns a boolean result); a convention similar to that of exclamation for mutators, though not quite as important IMHO. I do see some nice symmetry, supposing for example that S is a mutable string, in being able to name some of S's methods as: upper return an uppercased copy of S, not mutating S upper! mutate S in-place to be uppercased upper? return True iff S is already uppercased, not mutating S but (maybe because I have no extensive Ruby real-life experience) the predicate case, while nice, doesn't seem compelling to me (having to name it, say, isupper, doesn't appear to cause practical problems). Alex From apardon at forel.vub.ac.be Thu Nov 24 05:21:51 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Nov 2005 10:21:51 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> Message-ID: Op 2005-11-23, rhettinger at gmail.com schreef : > My own experience with adapting to Guido's design-view relates to > tuples and lists. To Guido, tuples are for records and lists are for > iteration. My own inclination is to view tuples as immutable lists. > Accordingly, it seems obvious to me that tuples should have count() and > index() methods for better substitutability. However, I've learned > that adapting to Guido's world-view leads to happiness because Python's > function signatures tend to reflect his design view. So, when I'm > thinking the Guido way, my code comes together seamlessly. When I > persist with a conflicting viewpoint, I find myself having to make > conversions, write work-arounds, or create more helper functions than > otherwise needed. But only Guido, thinks like Guido and then even Guido may now think differently than he thought before. And what if Guido had a bad day when he came up with something, should we just adopt to what he had in mind without questioning them. Sure, when you have a particular job to finish, you better adapt to how the language actually works. But when the argument is about how the language could be better, in whatever way you want to fill that in, just arguing that one should adapt to Guido style, is not an argument. Maybe an other approach could work better. Since I have been working with python I have seen the following changes not in a particular order: augmented arithmetic operators. generators. iterators. nested scopes. descriptors (and properties) list comprehension generator comprehension f(*sequence) calls new style classes unifictation of longs and ints sets decorators I wonder how much of these would have come about if everybody would just have adapted to the langauge as it was, instead of wondering how things could be improved. For all changes one could argue that those who wanted something from this list before it came about, that they were fighting the language. When we notice that people are fighting the language, sometimes the best approach is to change the language so that there is less reason to fight the language. -- Antoon Pardon From apardon at forel.vub.ac.be Wed Nov 30 09:31:47 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Nov 2005 14:31:47 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: On 2005-11-30, Duncan Booth wrote: > Antoon Pardon wrote: >> But lets just consider. Your above code could simply be rewritten >> as follows. >> >> res = list() >> for i in range(10): >> res.append(i*i) >> > I don't understand your point here? You want list() to create a new list > and [] to return the same (initially empty) list throughout the run of the > program? No, but I think that each occurence returning the same (initially empty) list throughout the run of the program would be consistent with how default arguments are treated. > >> Personnaly I think that the two following pieces of code should >> give the same result. >> >> def Foo(l=[]): def Foo(l): >> ... ... >> >> Foo() Foo([]) >> Foo() Foo([]) >> >> Just as I think, you want your piece of code to give the same >> result as how I rewrote it. >> >> I have a problem understanding people who find the below don't >> have to be equivallent and the upper must. > > The left one is equivalent to: > > __anon = [] > def Foo(l): > ... > > Foo(__anon) > Foo(__anon) So, why shouldn't: res = [] for i in range(10): res.append(i*i) be equivallent to: __anon = list() ... res = __anon for i in range(10): res.append(i*i) > The left has one list created outside the body of the function, the right > one has two lists created outside the body of the function. Why on earth > should these be the same? Why on earth should it be the same list, when a function is called and is provided with a list as a default argument? I see no reason why your and my question should be answered differently. > Or to put it even more simply, it seems that you are suggesting: > > __tmp = [] > x = __tmp > y = __tmp > > should do the same as: > > x = [] > y = [] No, I'm not suggesting it should, I just don't see why it should be considered a problem if it would do the same, provided this is the kind of behaviour we already have with list as default arguments. Why is it a problem when a constant list is mutated in an expression, but isn't it a problem when a constant list is mutated as a default argument? -- Antoon Pardon From jepler at unpythonic.net Tue Nov 29 10:26:53 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 29 Nov 2005 09:26:53 -0600 Subject: Death to tuples! In-Reply-To: <438c2f4f.211175043@news.oz.net> References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> <438c2f4f.211175043@news.oz.net> Message-ID: <20051129152653.GB8850@unpythonic.net> On Tue, Nov 29, 2005 at 10:41:13AM +0000, Bengt Richter wrote: > Seems like str.__mod__ could take an arbitary (BTW, matching length, necessarily? > Or just long enough?) iterable in place of a tuple, just like it can take > an arbitrary mapping object in place of a dict for e.g. '%(name)s'% {'name':''} What, and break reams of perfectly working code? s = set([1, 2, 3]) t = [4, 5, 6] u = "qwerty" v = iter([None]) print "The set is: %s" % s print "The list is: %s" % t print "The string is: %s" % u print "The iterable is: %s" % v Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From km at mrna.tn.nic.in Tue Nov 29 12:31:46 2005 From: km at mrna.tn.nic.in (km) Date: Tue, 29 Nov 2005 23:01:46 +0530 Subject: XMLSchema Parsing Message-ID: <20051129173146.GA8962@mrna.tn.nic.in> Hi all, i'd like to know if there are any good XMLSchema (.xsd files) parsing modules in python. regards, KM From inyeol.lee at siliconimage.com Wed Nov 16 15:25:41 2005 From: inyeol.lee at siliconimage.com (Inyeol Lee) Date: Wed, 16 Nov 2005 12:25:41 -0800 Subject: repeating regular expressions in one string In-Reply-To: <20051116200956.8273.qmail@server285.com> References: <20051116200956.8273.qmail@server285.com> Message-ID: <20051116202541.GI29926@siliconimage.com> On Wed, Nov 16, 2005 at 03:09:56PM -0500, Shane wrote: > Hi folks, > > I'm new to regular expressions (and a novice at Python) but it seems to be the tool I need for a particular problem. I have a bunch of strings that looks like this: > > 'blahblah_sf1234-sf1238_blahblah' > > and I would like to use the re module to parse all the 'sfXXXX' parts of the string. Each 'sfXXXX' needs to be its own string when I am through. How do I compile a regular expression that looks for more than one instance? Currently my expression looks like this: > > myString = re.compile('sf[0-9][0-9][0-9][0-9]') > > This works great for finding the first instance of 'sfXXXX'. I hope that was clear :) > > Thanks, > > Shane > -- > http://mail.python.org/mailman/listinfo/python-list You can simplify your pattern myString = re.compile('sf[0-9][0-9][0-9][0-9]') to myString = re.compile(r"sf\d{4}") >>> import re >>> s = 'blahblah_sf1234-sf1238_blahblah' >>> pat = re.compile(r"sf\d{4}") >>> re.findall(pat, s) ['sf1234', 'sf1238'] >>> for m in re.finditer(pat, s): ... print m.group() ... sf1234 sf1238 >>> Inyeol From xray_alpha_charlie at yahoo.com Fri Nov 11 14:22:08 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Fri, 11 Nov 2005 11:22:08 -0800 (PST) Subject: Python Countdown Message-ID: <20051111192208.93680.qmail@web35912.mail.mud.yahoo.com> I am running the following program from the example in "how to think like a computer scientist" def countdown(n): if n ==0: print "Blastoff!" else: print n countdown (n-1) countdown (1000) When I set "n"= 1000 the program runs in interpreter and stops counting down at 14 instead of running all the way to "Blastoff". If I set n = 985 it completes the program. If I set n=1200 it runs to 214 and stops. Why is this program only counting to 986....Anybody have an answer?? I am using Python 2.4.2 --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jd at something.com Fri Nov 11 06:24:11 2005 From: jd at something.com (JD) Date: Fri, 11 Nov 2005 11:24:11 -0000 Subject: output buffering References: Message-ID: <11n8vqrfo05j0b8@corp.supernews.com> On 2005-11-11, Fredrik Lundh wrote: > "JD" wrote: > >> When reading a large datafile, I want to print a '.' to show the >> progress. This fails, I get the series of '.'s after the data has been >> read. Is there a trick to fix this? > > assuming that you're printing to stdout, > > sys.stdout.flush() > > should do the trick. It does, Thanks! From sjhalpin at gmail.com Fri Nov 18 00:44:05 2005 From: sjhalpin at gmail.com (flippetigibbet) Date: 17 Nov 2005 21:44:05 -0800 Subject: .pth - howto? In-Reply-To: <1132292147.957378.166520@g44g2000cwa.googlegroups.com> References: <1132286440.597347.186850@g47g2000cwa.googlegroups.com> <1132291541.007880.146330@g47g2000cwa.googlegroups.com> <1132292147.957378.166520@g44g2000cwa.googlegroups.com> Message-ID: <1132292645.835048.53260@g49g2000cwa.googlegroups.com> Ok, I think I've finally worked out where my error was. My .pth file had: C:\Documents and Settings\user\My Documents\my\scripts\py\mydir and I was importing mydir, but that's wrong. I changed my .pth to have: C:\Documents and Settings\user\My Documents\my\scripts\py and imported mydir and it worked just fine I think I should have just done print sys.path at a python prompt before posting - I think that would have shown why it wasn't working (though thankyou again Peter, for without your suggestion, I wouldn't have got there). From martin at v.loewis.de Wed Nov 23 19:20:31 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 24 Nov 2005 01:20:31 +0100 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <4384FF25.6000802@redlinepy.com> References: <3uk6siF11mqgvU1@individual.net> <4384ec18$0$25871$9b622d9e@news.freenet.de> <4384FF25.6000802@redlinepy.com> Message-ID: <4385074f$0$4066$9b622d9e@news.freenet.de> Paul Watson wrote: > This is on AIX 4.3.3 > > $ grep -i _hz $(find . -name m_param.h) > #define _HZ 100 /* ticks per second of the clock */ > #define __hz HZ /* Berkeley uses lower case hz */ > #define HZ _HZ > #define hz __hz I expected to see something like this. However: in the file containing the #define hz: Is there any #ifdef around it that could be disabled/enabled? Regards, Martin From robert.kern at gmail.com Mon Nov 7 23:21:58 2005 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Nov 2005 20:21:58 -0800 Subject: overloading *something In-Reply-To: <200511072014.52919.jstroud@mbi.ucla.edu> References: <200511072014.52919.jstroud@mbi.ucla.edu> Message-ID: James Stroud wrote: > Hello All, > > How does one make an arbitrary class (e.g. class myclass(object)) behave like > a list in method calls with the "*something" operator? What I mean is: > > myobj = myclass() > > doit(*myobj) > > I've looked at getitem, getslice, and iter. What is it if not one of these? > > And, how about the "**something" operator? Avoiding magic at the expense of terseness, I would do something like the following: class myclass(object): def totuple(self): ... def todict(self): ... myargs = myclass() mykwds = myclass() doit(*myargs.totuple(), **mykwds.todict()) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bearophileHUGS at lycos.com Thu Nov 17 17:17:18 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 17 Nov 2005 14:17:18 -0800 Subject: Py 3.0 print Message-ID: <1132265838.822726.296190@g47g2000cwa.googlegroups.com> There is/was a long discussion about the replacement for print in Python 3.0 (I don't know if this discussion is finished): http://mail.python.org/pipermail/python-dev/2005-September/055968.html There is also a wiki page that collects the ideas: http://wiki.python.org/moin/PrintAsFunction There is the will to keep the printing operation very simple for the most common situation, but at the same time to make it flexible (optional no space between printed items, newline, redirection to file, etc), such requirements can collide. Another problem is to avoid backward compatibility problems in the source code. I post my idea here because I think I'm not fit for the python-dev mailing list yet. I hope posting this here is okay. A printing operation as a function requires the (), but I think there can be little advantages (but not many advantages, the print statement is acceptable for me still), so I agree to make it a function. Name: I think print() and printnl() can be fine names for the two functions, but this can give problems, so other names can be: write/writenl, show/shownl, echo/echonl, put/putnl, emit/emitnl, say/saynl I think the write/writenl or show/shownl namas are the best (writeln instead of writenl is acceptable too, I think). Spacing problem: I can solve this problem with the solution used in the Pascal language, that is to not print the space between items. Here are some examples, from the PrintAsFunction page: # Standard printing print 1, 2, 3 shownl(1, " ", 2, " ", 3) # Printing without any spaces print "%d%d%d" % (1, 2, 3) shownl(1, 2, 3) # Print as comma separated list print "%d, %d, %d" % (1, 2, 3) shownl(1, ", ", 2, ", ", 3) # Print without a trailing newline print 1, 2, 3, show(1, " ", 2, " ", 3) # Print to a different stream print >> sys.stderr, 1, 2, 3 shownl(1, " ", 2, " ", 3, to=sys.stderr) # Print a simple sequence print " ".join(map(str, range(10))) shownl( " ".join(map(str, range(10))) ) # Print a generator expression print " ".join(str(x*x) for x in range(10)) shownl( " ".join(str(x*x) for x in range(10)) ) It's not very nice looking, but it's simple, and it avoids problems and the use of the "sep" parameter. This is the alternative that uses the sep: # Print without a trailing newline print 1, 2, 3, show(1, 2, 3) # Printing without any spaces print "%d%d%d" % (1, 2, 3) shownl(1, 2, 3, sep='') # Print as comma separated list print "%d, %d, %d" % (1, 2, 3) shownl(1, 2, 3, sep=', ') # Print a simple sequence print " ".join(map(str, range(10))) shownl(*range(10)) I think the % string formatting used in Python can be fine for the C language (and ), but I have to look its syntax each time I use it ("%" character + Mapping key (optional) + Conversion flags (optional) + Minimum field width (optional) + Precision (optional) + Length modifier (optional) + Conversion type), and I think a simpler solution (fit for the most common usage) can be found for a high level langage like Python (I can say something similar about the syntax to define the base of integer numbers, the use of the trailing 0 for the octals isn't good). Bye, bearophile From samrobertsmith at gmail.com Tue Nov 15 04:49:12 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Tue, 15 Nov 2005 01:49:12 -0800 Subject: compare list In-Reply-To: <4379AA95.80806@cc.umanitoba.ca> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <1d987df30511142330t39b137fdpdc9eee56e73d6e1f@mail.gmail.com> <4379AA95.80806@cc.umanitoba.ca> Message-ID: <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> On 11/15/05, Brian van den Broek wrote: > Shi Mu said unto the world upon 2005-11-15 01:30: > >>Hey Ben, > >> > >>first, as expected, the other two answers you received are better. :-) > >> > >>Sets are much better optimized for things like membership testing than > >>are lists. I'm not competent to explain why; indeed, I keep > >>overlooking them myself :-( > > > > >> > >>Best, > >> > >>Brian vdB > > > > is it possible to modify the codes to compare the two lists with not > > necessarily consecutive numbers? > > For example, > > lisA=[1,2,5,9] > > lisB=[9,5,0] > > compare A and b will get true because the two lists have 5 and 9 > > together though they are indifferent order. > > Best Regards, > > Robert > > > > Sure, but rather than repair a less than best first approach, better > to do it with sets: > > >>> lisA=[1,2,5,9] > >>> lisB=[9,5,0] > >>> lisC=[9,5,0,1] > >>> def intersection_has_two(sequence1, sequence2): > set1, set2 = set(sequence1), set(sequence2) > return len(set1.intersection(set2)) == 2 > > >>> intersection_has_two(lisA, lisB) > True > >>> intersection_has_two(lisA, lisC) > False > > Sets make stuff easy. (I have got to remember that :-) The only reason > to make that a function is the one liner gets a bit long for my taste: > > >>> len(set(lisA).intersection(set(lisB))) == 2 > True > >>> > > Best, > > Brian vdB it does not work. >>> len(set(lisA).intersection(set(lisB))) == 2 Traceback (most recent call last): File "", line 1, in ? NameError: name 'set' is not defined From mwm at mired.org Wed Nov 30 01:33:14 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 01:33:14 -0500 Subject: General question about Python design goals References: <86k6estfkd.fsf@bhuda.mired.org> <7xu0du64zo.fsf@ruckus.brouhaha.com> Message-ID: <86psoiodat.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> But a programming language (or UI) is not just a collection of syntax >> and and interfaces - it's an implementation. You need to keep in mind >> that "practicality beats purity". > An awful lot of the time in this newsgroup, "practicality beats > purity" translates as "the programmer can just be a lazy slob". You post that as if it were a bad thing. >> If following POLA makes the implementation an order of magnitude >> slower or larger, then you don't follow POLA - at least until you >> can do it without that cost. > If following POLA costs that much, at least in the kinds of examples > we talk about all the time here, something is probably wrong with the > implementation (or the design) to begin with. True, but not constructive. Knowing that something is wrong is easy. Diagnosing the problem is harder. Curing it is even harder. And unti you get to that last step, you haven't done anything to improve the situation. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From lycka at carmen.se Thu Nov 24 08:14:28 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 24 Nov 2005 14:14:28 +0100 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> <1132712643.968300.151010@g49g2000cwa.googlegroups.com> <1132713954.040591.120660@f14g2000cwb.googlegroups.com> <1132718374.960509.206800@z14g2000cwz.googlegroups.com> Message-ID: Antoon Pardon wrote: > What does this mean? It means that the hammer works better if you learn how to hold and swing it, instead of trying to modify it so that it's more comfortable to use it in a non-optimal way. From dave at pythonapocrypha.com Wed Nov 2 14:55:55 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 02 Nov 2005 12:55:55 -0700 Subject: Threading In-Reply-To: <1130959652.003475.26650@o13g2000cwo.googlegroups.com> References: <1130959652.003475.26650@o13g2000cwo.googlegroups.com> Message-ID: <436919CB.1030408@pythonapocrypha.com> Tuvas wrote: > I am trying to write a thread that will execute a function every 2 > seconds until the program is close, in which case it will stop. I can > write the program easy enough to execute the command every 2 seconds, > the problem comes when I try to close the program. It won't close the > thread. Any ideas as to what I can do? Thanks! > The simplest thing to do is call setDaemon on the thread object: t = threading.Thread(target=MyFunc, args=(1,2,3)) t.setDaemon(1) t.start() This doesn't really give your other thread a chance to shutdown cleanly though, so if you need to "guarantee" clean shutdown, then have your thread check some shared flag or have some other way to know when it needs to quit, and then have the main thread wait for it to terminate by calling Thread.join. For example, if you have a work queue, you could decide on the convention that None means all the work is done: import threading, Queue, time def Work(q): while 1: work = q.get() if work is None: break print 'Working on', work time.sleep(1) print 'Worker is quitting now' q = Queue.Queue() # this queue is shared with the worker thread # Start up a worker t = threading.Thread(target=Work, args=(q,)) t.start() # Give it stuff to do for i in range(5): q.put(i) # signal end of work q.put(None) print 'Main thread waiting for worker to be done' t.join() # returns once all the work is done print 'All done' -Dave From bokr at oz.net Fri Nov 4 20:19:13 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 05 Nov 2005 01:19:13 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> Message-ID: <436c0527.146082265@news.oz.net> On Thu, 03 Nov 2005 13:37:08 -0500, Mike Meyer wrote: [...] >> I think it even less sane, if the same occurce of b.a refers to two >> different objects, like in b.a += 2 > >That's a wart in +=, nothing less. The fix to that is to remove += >from the language, but it's a bit late for that. > Hm, "the" fix? Why wouldn't e.g. treating augassign as shorthand for a source transformation (i.e., asstgt = expr becomes by simple text substitution asstgt = asstgt expr) be as good a fix? Then we could discuss what b.a = b.a + 2 should mean ;-) OTOH, we could discuss how you can confuse yourself with the results of b.a += 2 after defining a class variable "a" as an instance of a class defining __iadd__ ;-) Or point out that you can define descriptors (or use property to make it easy) to control what happens, pretty much in as much detail as you can describe requirements ;-) Regards, Bengt Richter From msj at infoserv.dk Wed Nov 16 05:18:15 2005 From: msj at infoserv.dk (Martin) Date: Wed, 16 Nov 2005 11:18:15 +0100 Subject: Python/ASP local characters and 500 server error In-Reply-To: References: <437ae3b1$0$46986$edfadb0f@dread15.news.tele.dk> Message-ID: <437b076a$0$47069$edfadb0f@dread15.news.tele.dk> Fredrik Lundh wrote: > > http://www.python.org/peps/pep-0263.html > Using the info from pep-0263, adding a line in the start for the file: # -*- coding: -*- works for .py files, but the error i get is from an .asp file. The logfile contains this info: ASP_0147|500_Server_Error 500 A solution is to move ALL code from the .asp page to a .py file and import it on the .asp page. But there must be another solution? /Martin From lycka at carmen.se Wed Nov 9 04:04:49 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 09 Nov 2005 10:04:49 +0100 Subject: Application monitor In-Reply-To: <1131399761.209133.19690@g49g2000cwa.googlegroups.com> References: <1131399761.209133.19690@g49g2000cwa.googlegroups.com> Message-ID: dcrespo wrote: > Hi to all, > > I'd like to have an app monitor that gets rid of another app, in the > way that if it closes unspectedly, the app monitor just wake it up one > more time, and viceversa. Twisted contains such a thing. I think it's called twisted.runner, and no, it's not just for keeping Twisted processes running. From steve.morin at gmail.com Wed Nov 16 16:13:14 2005 From: steve.morin at gmail.com (Steve) Date: 16 Nov 2005 13:13:14 -0800 Subject: can modules be dynamically reloaded Message-ID: <1132175594.931382.257860@g47g2000cwa.googlegroups.com> Can python modules be reloaded. For example you import a module, programatically edit it, then have the file reload the module? Does anyone have any ideas about this? Steve From could.net at gmail.com Tue Nov 22 00:30:08 2005 From: could.net at gmail.com (could ildg) Date: Tue, 22 Nov 2005 13:30:08 +0800 Subject: How to paste python code on wordpress? In-Reply-To: <79021162-F73D-44DC-B621-1CE24E14F453@tangledhelix.com> References: <311b5ce10511211717q1d1cd6e7hd622c16d0f725745@mail.gmail.com> <79021162-F73D-44DC-B621-1CE24E14F453@tangledhelix.com> Message-ID: <311b5ce10511212130t68f4e562g298610fae121edb7@mail.gmail.com> Thank you~ It works! but how can paste "<" and ">", please? these 2 symbols will also confuse wordpress and I can't publish what I want. On 11/22/05, Dan Lowe wrote: > > > On Nov 21, 2005, at 8:17 PM, could ildg wrote: > > > Wordpress.com blog will eat up the spaces before > a line, > > just as it will trim every line of my article. So I can't paste > > python code indentedly. > > Does any one use wordpress blog here? > > Please tell me how to leave the sapces as they are when publishing > > ariticles on the blog, > > You can enclose the code in a PRE block, like this: > >
> def foobar():
> print "abc"
> if x == 3:
> print "def"
> print "ghi"
> 
> > If you don't care for how it renders in a browser, hack your CSS to > make PRE render in a way you like. > > -dan > > -- > Well sure the government lies, and the press lies, but in a democracy > they aren't the same lies. -Alexis A. Gilliland > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From noway at sorry.com Thu Nov 24 02:54:36 2005 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 24 Nov 2005 07:54:36 GMT Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <86br0a229a.fsf@bhuda.mired.org> Message-ID: <0lehf.3890$S6.66694@twister2.libero.it> Mike Meyer wrote: >> If it's not a wart, why would it be a wart for user-defined types to >> have the same behaviour? > > It's a wart because user-defined classes *don't* have the same > behavior. Then *my* solution for this would be to give user-defined classes a way to behave like builtins, eg. explicitally and fully implement immutability. Immutability is an important concept in Python programs, and I'm impressed it does not have explicit support. -- Giovanni Bajo From uval at rz.uni-karlsruhe.de Thu Nov 17 22:37:11 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Fri, 18 Nov 2005 04:37:11 +0100 Subject: simple array question In-Reply-To: References: Message-ID: purna chandra wrote: > Hello, > I have a simple question.Hoping not to take much of > your valuable time...:-). I am trying to get the data > from a string, and am wondering if I get > http://groups.google.com/intl/en/googlegroups/tour/index.html > from the array : > array('c', > '\x00=http://groups.google.com/intl/en/googlegroups/tour/index.html')) > > Thanks in advance, > > regards, > purna. > i am not sure i understand your question right if not just ignore import array x = array.array("c", "test") s = x.tostring() s # => "test" hth, Daniel From uval at rz.uni-karlsruhe.de Wed Nov 23 11:23:44 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Wed, 23 Nov 2005 17:23:44 +0100 Subject: moving mouse? In-Reply-To: References: Message-ID: dado wrote: > I'm implementing a "self-tutorial" into my app, > and wondering if there's a way of moving a mouse > cursor on command? probably using sys,os modules? sys doesn't mean [operating] system it's completely Python related, the intepreter itself you can use it to see how many referenced does a object like 1 have .. or check the current recusrion depth .. or see the encoding of stdin, stdout only such things os module is operating system related it provides many lowlevel functions .. os.open etc I dont know of a module which provides things you are looking for Regards, Daniel From gsakkis at rutgers.edu Mon Nov 7 17:20:05 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 7 Nov 2005 14:20:05 -0800 Subject: Map of email origins to Python list References: <8764r417v4.fsf@jupiter.g2ctech> Message-ID: <1131402005.789068.207890@z14g2000cwz.googlegroups.com> "Jorge Godoy" : > Hmmmm... I don't see mine listed there: I'm in South America, Brasil. More > specifically in Curitiba, Paran?, Brasil. :-) That's funny; I was looking for mine and I stumbled across yours at Piscataway, NJ, US. :-) George From fredrik at pythonware.com Tue Nov 22 12:49:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 18:49:15 +0100 Subject: Timeout for regular expression References: <1132681028.115173.201230@g47g2000cwa.googlegroups.com> Message-ID: wrote > Is there a way to set a timeout interval when executing with a > re.search ? Sometimes (reason being maybe a "bad" pattern), > the search takes forever and beyond... not directly. the only reliable way is to run it in a separate process, and use the resource module to set necessary limits. (to figure out if an expression can take lots of time, look for nested repeats. analyzing the output from sre_parse.parse(pattern) makes that relatively easy). From mwm at mired.org Sun Nov 13 05:30:39 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 13 Nov 2005 05:30:39 -0500 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> Message-ID: <861x1k2628.fsf@bhuda.mired.org> Pierre Barbier de Reuille writes: >>>In LISP : Symbols are introduced by "'". "'open" is a symbol. >> No, they're not. "'(a b c)" is *not* a symbol, it's a list. Symbols in >> LISP are just names. "open" is a symbol, but it's normally evaluated. >> The "'" is syntax that keeps the next expression from being evaluated, >> so that "'open" gets you the symbol rather than it's value. Since >> you're trying to introduce syntax, I think it's important to get >> existing practice in other languages right. > You're right ! I was a bit quick here ... "'" is a way to stop > evaluation and you may also write "(quote open)" for "'open". Yup. Also notice that if you eval the symbol, you get any value that happens to be bound to it. This is irrelevant for your purposes. But the properties you're looking for are - in LISP, anyway - implementation details of how it handles names. >> While you don't make it clear, it seems obvious that you intend that >> if $open occurs twice in the same scope, it should refer to the same >> symbol. So you're using the syntax for a dual purpose. $name checks to >> see if the symbol name exists, and references that if so. If not, it >> creates a new symbol and with that name. Having something that looks >> like a variables that instantiates upon reference instead of raising >> an exception seems like a bad idea. > > Well, that's why symbols are absolutely not variables. If they aren't variables, they probably shouldn't *look* like variables. >> Provide a solid definition for the proposed builtin type "symbol". >> Something like: >> >> symbol objects support two operations: is and equality >> comparison. Two symbol objects compare equal if and only if >> they are the same object, and symbol objects never compare >> equal to any other type of object. The result of other >> operations on a symbol object is undefined, and should raise >> a TypeError exception. >> >> symbol([value]) - creates a symbol object. Two distinct >> calls to symbol will return two different symbol objects >> unless the values passed to them as arguments are equal, in >> which case they return the same symbol object. If symbol is >> called without an argument, it returns a unique symbol. > > Good definition to me ! Note that this definition doesn't capture the name-space semantics you asked for - symbol(value) is defined to return the same symbol everywhere it's called, so long as value is equal. This is probably a good thing. Using the ability to have non-strings for value means you can get this behavior by passing in something that's unique to the namespace as part of value. Said something probably depends on the the flavor of the namespace in question. This allows you to tailor the namespace choice to your needs. Also, since I'm allowing non-strings for value, just invoking str on the symbol isn't really sufficient. Let's add an attribute 'value', such that symbol(stuff).value is identical to stuff. I you want, define symbol.__str__ as str(symbol.value) so that str(symbol("foo")) returns "foo". > Well, maybe we should find some other way to express symbols. The only > thing I wanted was a way easy to write, avoiding the need to declare > symbols, and allowing the specification of the scope of the symbol. My > prefered syntax would be something like : > 'opened, `opened or `opened` > However, none are usable in current Python. Well, symbol('opened') solves the declaration issue, but it's not as easy as you'd like. >> Personally, I think that the LISP quote mechanism would be a better >> addition as a new syntax, as it would handle needs that have caused a >> number of different proposals to be raised. It would require that >> symbol know about the internals of the implementation so that ?name >> and symbol("name") return the same object, and possibly exposing said >> object to the programmer. And this is why the distinction about how >> LISP acts is important. > Maybe, although I may say I cannot see clearly how LISP quote mechanism > translates into Python. It compiles the quoted expression and returns a code object. I'd love to recycle backquotes so that `expr` means compile(expr, 'quoted-expr', 'eval'), but that won't happen anytime soon. Hmm. You know, $symbol$ doesn't seem nearly as bad as $symbol. It tickles TeX, not P***. I could live with that. Like I said, the tricky part of doing this is getting `symbol` to have the semantics you want. If you compile the same string twice, you get two different code objects, though they compare equal, and the variable names in co_names are the same strings. Maybe equality is sufficient, and you don't need identity. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From pwatson at redlinepy.com Sun Nov 20 22:19:18 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 20 Nov 2005 21:19:18 -0600 Subject: Web-based client code execution In-Reply-To: References: <3u6ngeFvh3v1U1@individual.net> Message-ID: <43813CB6.4030209@redlinepy.com> John J. Lee wrote: > Paul Watson writes: > > >>What are the options? >> >>The user to hits a web page, downloads code (Python I hope), execute it, >>and be able to return the results. It needs to be able to go through >>standard HTTP so that it could be run from behind a corporate firewall >>without any other ports being opened. >> >>Am I stuck doing an ActiveX control? > > [...] > > If you just need to talk on port 80, just go ahead and do that (module > socket, module httplib, module urllib2, urllib.getproxies, etc), and > write a normal desktop application. > > > If it must run in a browser, here is some food for thought: > > > Compile Python to JavaScript -- very cool > > http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework > > http://www.aminus.org/blogs/index.php/phunt/2005/10/09/psst_crackajax_is_in_svn > > > Plain old AJAX with Python on server side > > https://sourceforge.net/projects/json-py/ > > http://www.google.co.uk/search?q=ajax+python&btnG=Search (um, ignore the 1st result) > > > Write Java applets in Python > > http://www.jython.org/ > > > Flash 'local storage' > > http://www.macromedia.com/support/documentation/en/flashplayer/help/help02.html > > Sort-of AJAX-for-Flash stuff > > http://www.cs.unc.edu/~parente/tech/tr04.shtml > http://www.simonf.com/flap/ > > Flash itself (boo;-) > > http://www.macromedia.com/ > > > XUL and PyXPCOM (Firefox only) > > http://www.xulplanet.com/ > > http://trac.nunatak.com.au/projects/nufox > > > Firefox future capabilities in this direction (probably most of this > is relevant) > > http://www.mozilla.org/roadmap/gecko-1.9-roadmap.html > > http://weblogs.mozillazine.org/roadmap/archives/2005_09.html > > > John I appreciate your long list of references. For this task, I think the first answer may have to be the one with which to go. A standard application that talks through port 80 and perhaps can use proxies. My desire to have the code distributed through a web page is just to ensure that the user is running the correct version and has not hacked it in any way. I suppose I can checksum the local client application and compare it with what is on the server. Then, make a way to update... ARGH! Even when future browsers embed Python interpreters, the security considerations may be such that no one will want to accept code which can do much locally anyway. Probably the right thing for the public Internet, Makes it harder to develop internal system management tools. From cito at online.de Sun Nov 20 20:32:46 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 21 Nov 2005 02:32:46 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Personally, I have needs for ordered dict but I don't think it should > be in standard library though, as different situation called for > different behaviour for "ordered" and skewing my code to a standard lib > way is no good. I have started the thread in the first place because I believed it is pretty unabmiguous what an "ordered dictionary" is and how it should behave. That's why I asked myself why something that straigthforward has not been added to the standard lib yet. Maybe I'm wrong; I must admit that I haven't meditated about it very much. Do you have an example for different options of behavior? -- Christoph From steve at REMOVETHIScyber.com.au Fri Nov 25 19:59:55 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 26 Nov 2005 11:59:55 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> Message-ID: On Thu, 24 Nov 2005 17:43:22 +0100, Martin P. Hellwig wrote: > if I owned a company > making profit on software sales (sale =! support) you sign a death wish > for using GPL Apart from Microsoft, and possibly Quark (makers of Quark Express desktop packaging software), and perhaps a few console game developers, is there any company making a profit on software sales? -- Steven. From ggrp1.20.martineau at dfgh.net Mon Nov 28 11:43:31 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 28 Nov 2005 08:43:31 -0800 Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> <1133191986.034689.59090@g14g2000cwa.googlegroups.com> <1h6q906.wbfwmtxr0zjN%aleax@mail.comcast.net> Message-ID: <1133196211.468791.220480@g47g2000cwa.googlegroups.com> I'd like to point out to the OP that using a function's __get__ method this way only works with new-style classes and their instances...not with the example in the shown in original post. -Martin Alex Martelli wrote: > Flavio wrote: > > > This "new" module sounds pretty cool, too bad its deprecated... > > > > I would not want to add a dependancy to a deprecated module in my code. > > But maybe I'll check the code for instancemethod within it and see what > > it does. > > If you have a function f and want to make an instancemethod out of it, > you can simply call f.__get__(theinstance, theclass) and that will build > and return the new instancemethod you require. > > > Alex From cito at online.de Wed Nov 23 18:15:27 2005 From: cito at online.de (Christoph Zwerschke) Date: Thu, 24 Nov 2005 00:15:27 +0100 Subject: Why is dictionary.keys() a list and not a set? Message-ID: Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys(): ... or even for x in sorted(d.keys()): ... would still work and do the same. However, the older idiom k = d.keys() k.sort() for x in k: ... would break (since you cannot sort a map directly). So it seems not possible to change the behavior since it would break old code. Maybe keys() and values() could be made deprecated functions, superseded by keyset() and valueset(), but probably this would not be worth the effort. Another related question: Actually, dicts can be considered as subclasses of sets and thus could inherit a lot of set methods and operators. Only intersection and union must be treated with care, because dictionaries must be mappings (i.e. map to exactly one value). In fact, some inheritance from sets has already been implemented: For instance, by allowing the set operator "in" for dictionaries, instead of "has_key". The len(), clear(), copy() and update() functions can also be interpreted as inherited from set. The dictionary method popitem() is actually the inherited set method pop(). (d.pop() without arguments could actually do the same as d.popitem(); I guess the suffix "item" was chosen to remind you that it returns a key/value pair, not only a value.) But could other set methods also be useful? A dictionary could inherit the remove() and discard() method from sets. d.remove(x) would do the same as del d[x], but d.discard(x) would not raise a KeyError if x not in d. Or, for instance, if a = { 1:11, 2:12 }; b = { 2:22, 3:13 }, c = { 2:32 } then c.issubset(b) == c <= b == True b.issuperset(c) == b >= c == True a.difference(b) == a - b == { 1:11 } a.s.symmetric_difference(b) == a ^ b == { 1:11, 3:13 } a.update(b) == a |= b == a = { 1:11, 2:22, 3:13 } a.intersection_update(b) == a &= b == a = { 2:22 } a.difference_update(b) == a -= b == a = { 1:11 } a.symmetric_difference_update(b) == a ^= b == a = { 1:11, 3:13 } Of these, a |= b may be particularly interesting as short notation for a.update(b). -- Christoph From lycka at carmen.se Thu Nov 3 08:33:43 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 03 Nov 2005 14:33:43 +0100 Subject: computer programming In-Reply-To: <1130978408_1503@spool6-east.superfeed.net> References: <1130944817.168134.124690@g14g2000cwa.googlegroups.com> <1130978408_1503@spool6-east.superfeed.net> Message-ID: Brandon K wrote: > what is .tk? Turkmenistan? or is it just some arbitrary suffix. Nope that's tm. Tokelau has tk. I'm sure you can learn more from Wikipedia etc. See e.g. http://en.wikipedia.org/wiki/ISO_3166-1 > >> www.javaholics.tk > > > > > ----== Posted via Newsgroups.com - Usenet Access to over 100,000 > Newsgroups ==---- > Get Anonymous, Uncensored, Access to West and East Coast Server Farms! > ----== Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM > ==---- > > From siona at chiark.greenend.org.uk Fri Nov 11 09:53:08 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Nov 2005 14:53:08 +0000 (GMT) Subject: help make it faster please References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> <1131646601.299316.166570@g47g2000cwa.googlegroups.com> <1131647614.893835.225560@g47g2000cwa.googlegroups.com> Message-ID: wrote: >Oh sorry indentation was messed here...the >wordlist = countDict.keys() >wordlist.sort() >should be outside the word loop.... now >def create_words(lines): > cnt = 0 > spl_set = '[",;<>{}_&?!():-[\.=+*\t\n\r]+' > for content in lines: > words=content.split() > countDict={} > wordlist = [] > for w in words: > w=string.lower(w) > if w[-1] in spl_set: w = w[:-1] > if w != '': > if countDict.has_key(w): > countDict[w]=countDict[w]+1 > else: > countDict[w]=1 > wordlist = countDict.keys() > wordlist.sort() > cnt += 1 > if countDict != {}: > for word in wordlist: print (word+' '+ >str(countDict[word])+'\n') > >ok now this is the correct question I am asking... (a) You might be better off doing: words = words.lower() for w in words: ... instead of calling lower() on each separate word (and note that most functions from string are deprecated in favour of string methods). (b) spl_set isn't doing what you might think it is -- it looks like you've written it as a regexp but your using it as a character set. What you might want is: spl_set = '",;<>{}_&?!():-[\.=+*\t\n\r' and while w[-1] in spl_set: w = w[:-1] That loop can be written: w = w.rstrip(spl_set) (which by my timings is faster if you have multiple characters from spl_set at the end of your word, but slower if you have 0 or 1). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From steve at holdenweb.com Thu Nov 24 01:02:54 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 06:02:54 +0000 Subject: Unicode in MIMEText In-Reply-To: References: Message-ID: Damjan wrote: >>Why doesn't this work: >> >>from email.MIMEText import MIMEText >>msg = MIMEText(u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430') >>msg.set_charset('utf-8') >>msg.as_string() > > ... > >>UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: >>ordinal not in range(128) > > > It's a real shame that unicode support in the python library is very weak > sometimes... > > Anyway I solved my problem by patching email.Charset > > --- Charset.py~ 2005-11-24 04:20:09.000000000 +0100 > +++ Charset.py 2005-11-24 04:21:02.000000000 +0100 > @@ -244,6 +244,8 @@ > """Convert a string from the input_codec to the output_codec.""" > if self.input_codec <> self.output_codec: > return unicode(s, self.input_codec).encode(self.output_codec) > + elif isinstance(s, unicode): > + return s.encode(self.output_codec) > else: > return s > > > > > ... and being concerned to improve the library you logged this patch in Sourceforge for consideration by the developers? That's the only way to guarantee proper consideration of your fix. 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 malvert at telenet.be Fri Nov 25 13:29:52 2005 From: malvert at telenet.be (malv) Date: 25 Nov 2005 10:29:52 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132943392.448228.118630@g49g2000cwa.googlegroups.com> I suggest you take a look at Qt3, much superior to Tkinter or PyGtk. With Python, you have to use PyQt bindings. peter.mosley at talk21.com wrote: > I am trying to learn GUI programming in Python, but have to confess I > am finding it difficult. > > I am not an experienced programmer - just someone who from time to > time writes small programs for my use. Over the years I have moved > from GWBASIC to QBASIC to Visual Basic, and now trying to move across > to a Linux platform. Python seems to be the best compromise between > the limitations of command line basic programming and the total > incomprehensibility of C. > > Googling around it seems the best GUI is either Tkinter or PyGtk. I > found a book which recommended PyGtk, as it had a graphical design > option, Glade. Coming from a VB background I latched onto that and > bought the book (Beginning Python, Wrox), but it was a disappointment > (or more accurately a complete waste of money) - there was > insufficient detail in the text. > > I've found the tutorial and reference manual on the PyGtk web site, > but although I've made some progress, I keep reaching points where I > have insufficient background to understand them. Currently I'm stuck > on dialog boxes (the code seems immensely complex for the equivalent of > MsgBox("Do you really want to do this ",vbYesNo) and I haven't > got it to work properly yet) and loading graphical images in anything > other than their original size, but every new step brings another > struggle > > I've seen reference to a Tkinter book - something like 'Python > and Tkinter Programming' but it seems to be out of print and > unavailable. > > Can anyone offer any suggestions as to the least painful way forwards? > > (Email address was valid once but has long since been abandoned to > spam. Please rely via newsgroup) From ptmcg at austin.rr._bogus_.com Mon Nov 7 12:55:47 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 07 Nov 2005 17:55:47 GMT Subject: [OT] Map of email origins to Python list References: Message-ID: "Claire McLister" wrote in message news:mailman.221.1131384118.18701.python-list at python.org... We've been working with Google Maps, and have created a web service to map origins of emails to a group. As a trial, we've developed a map of emails to this group at: http://www.zeesource.net/maps/map.do?group=668 This represents emails sent to the group since October 27. Would like to hear what you think of it. ------------------------------ Another sleepless camera pointed at the fishbowl that is my online life. I guess it's a great way to find where there might be Python jobs to be found, or at least kindred souls (or dissident Python posters in countries where Internet activity is closely monitored...) To me, it's either cool in a creepy sort of way, or creepy in a cool sort of way. -- Paul From sjmaster at gmail.com Wed Nov 2 17:55:31 2005 From: sjmaster at gmail.com (Steve M) Date: 2 Nov 2005 14:55:31 -0800 Subject: convert COM obj to integer In-Reply-To: References: Message-ID: <1130972131.273236.78480@g44g2000cwa.googlegroups.com> I don't know exactly what a COM object is, but those aren't them. The win32com package takes care of converting everything to Python types. The excel call returns a tuple of tuples. That is, the outer tuple is the sequence of rows, and each such row is itself a tuple with one member per column requested. Since you only request one column, it is a one-item-long tuple, also called a 1-tuple. That is demonstrated by the result of print'ing the list. By the way, you shouldn't use 'list' as a name because it is also the name of a built-in function. And it isn't a list anyway, it's a tuple. Now, each number is in fact already a primitive Python object of type float. (The asterisk is a unicode string.) So you want to convert the floats into integers, and it looks like you want to round rather than truncate. ---- table = xlApp.ActiveWorkbook.ActiveSheet.Range("Q13:Q36") converted_values = [] for row in table: value = row[0] #get the first (and only) item in the tuple try: value = round(value) except TypeError: #value is not a float value = None else: value = int(value) #turn the float into an int converted_values.append(value) print converted_values ---- By the way, if you wonder how I knew to catch the TypeError, I just fired up the interactive Python interpreter, and typed this: round(u'*') From ggrp1.20.martineau at dfgh.net Wed Nov 30 19:19:06 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 30 Nov 2005 16:19:06 -0800 Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> <1133193055.057481.174380@g49g2000cwa.googlegroups.com> <1133194571.960132.94640@g43g2000cwa.googlegroups.com> Message-ID: <1133396346.125104.132970@g47g2000cwa.googlegroups.com> Sorry, I seldom look at the built-in __doc__ strings or use the 'help()' function. Instead I usually refer to the html or winhelp versions of the documentation, and for Python 2.4.1 there's nothing in section 3.28 on the 'new' module that mentions that it deprecated -- so thanks to you and Fl?vio for the information. Using help on MethodType gave me the following somewhat surprising output [truncated here]: >>> import types >>> help(types.MethodType) Help on class instancemethod in module __builtin__: class instancemethod(object) | instancemethod(function, instance, class) | | Create an instance method object. [snip] Which I take to mean that 'instancemethod' is no longer [just] a function in the deprecated 'new' module but is also a built-in class. However and somewhat confusingly (to me anyway), a search in the help docs file turns up the following: > 7.5.3 Method Objects > There are some useful functions that are useful for working with method objects. > > PyTypeObject PyMethod_Type > This instance of PyTypeObject represents the Python method type. This is > exposed to Python programs as types.MethodType. > ... [snip] Which, as you can see, claims that types.MethodType is actually an instance of a PyTypeObject (not the class instancemethod that help(types.MethodType) indicated). Best, -Martin ==== Steven D'Aprano wrote: > On Mon, 28 Nov 2005 08:16:12 -0800, Martin Miller wrote: > > > First of all,why do you think the new module is deprecated? (I can't > > find anything in the docs to indicate this.) > > Did you try help(new) from an interactive prompt? > > > py> new.__doc__.splitlines()[0] > 'Create new objects of various types. Deprecated.' > > > -- > Steven. Fl?vio wrote: > > First of all,why do you think the new module is deprecated? (I can't > > find anything in the docs to indicate this.) > > Its in the docs of python 2.4. I dont know about older versions: > > Help on module new: > > NAME > new - Create new objects of various types. Deprecated. > > FILE > /usr/lib/python2.4/new.py > > MODULE DOCS > /usr/share/doc/python-docs-2.4.2/html/module-new.html > > DESCRIPTION > This module is no longer required except for backward > compatibility. > Objects of most types can now be created by calling the type > object. > > > As for using MethodType in the types module: There's nothing in the > > module documentation that suggests that you can call MethodType as a > > function as you suggest, only that it is the name of the type of > > methods of user-defined class instances.. So, while calling it might > > work, it sounds like you are using an undocumented feature... > > If you look at new.py, all it does is import the functions from types > and rename them. For MethodType is goes like this > > from types import MethodType as instancemethod > > so instance method *is* Methodtype. > > Moreover, I tried and it works ;-) > > So this solution is perfect once adapted not to depend on "new". > > Thanks, > > Fl?vio From bignose+hates-spam at benfinney.id.au Tue Nov 15 23:25:10 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Nov 2005 15:25:10 +1100 (EST) Subject: Newb ? References: <3tvpqaFv0q48U1@individual.net> Message-ID: Chad Everett wrote: > I searched the group for the term backwards but I did not get any > results. You might have better results searching for 'reverse'. -- \ "For certain people, after fifty, litigation takes the place of | `\ sex." -- Gore Vidal | _o__) | Ben Finney From peter.maas at somewhere.com Sat Nov 12 15:16:49 2005 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 12 Nov 2005 21:16:49 +0100 Subject: SciPy python 2.4 wintel binaries In-Reply-To: <1131803968.993069.29660@f14g2000cwb.googlegroups.com> References: <1131803968.993069.29660@f14g2000cwb.googlegroups.com> Message-ID: jelle schrieb: > I dearly miss having the power of SciPy on my python 2.4 installation. > The topic of SciPy python 2.4 wintel binaries has been discussed before > on this list, but I haven't been able to find a compiled binary. If you really need SciPy, you should install Python 2.3 (Enthought Edition) in a separate directory as long as a Python 2.4 SciPy binary is not available. Python 2.3 EE comes with a bunch of useful additions, e.g. SciPy. From peter at engcorp.com Fri Nov 18 22:31:03 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 18 Nov 2005 22:31:03 -0500 Subject: textwrap.dedent() drops tabs - bug or feature? In-Reply-To: References: Message-ID: Steven Bethard wrote: > Note that even though the tabs are internal, they are still removed by > textwrap.dedent(). The documentation[1] says: ... > So it looks to me like even if this is a "feature" it is undocumented. > I'm planning on filing a bug report, but I wanted to check here first in > case I'm just smoking something. While I wouldn't say it's obvious, I believe it is (indirectly?) documented and deliberate. Search for this in the docs: """ expand_tabs (default: True) If true, then all tab characters in text will be expanded to spaces using the expandtabs() method of text. """ (This is not to say a specific rewording of the docs to lessen any confusion in this area wouldn't be welcomed.) -Peter From gaudetteje at gmail.com Thu Nov 17 17:22:17 2005 From: gaudetteje at gmail.com (NavyJay) Date: 17 Nov 2005 14:22:17 -0800 Subject: Stretching a bitmap In-Reply-To: <1132262655.753062.210080@g14g2000cwa.googlegroups.com> References: <1132262655.753062.210080@g14g2000cwa.googlegroups.com> Message-ID: <1132266137.875055.82600@g14g2000cwa.googlegroups.com> Try ImageMagik: http://www.imagemagick.org/ From nobody at this.home.com Tue Nov 29 20:27:21 2005 From: nobody at this.home.com (Krystian) Date: Wed, 30 Nov 2005 02:27:21 +0100 Subject: python speed References: Message-ID: <0ovpo11mqp4l2ndnvdre12td59iuscnauh@4ax.com> 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. > >Why would we want Python to be as fast as Java when it's already faster? hm... i came across this site: http://shootout.alioth.debian.org/benchmark.php?test=all&lang=java&lang2=python&sort=fullcpu could you take an attitude with regard to this benchmark? >Take a look at PyGame. on my way :) best k From jstroud at mbi.ucla.edu Mon Nov 7 19:38:11 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 7 Nov 2005 16:38:11 -0800 Subject: Regular expression question -- exclude substring In-Reply-To: <1131409094.240352.67240@g43g2000cwa.googlegroups.com> References: <1131405834.093144.206510@g43g2000cwa.googlegroups.com> <1131409094.240352.67240@g43g2000cwa.googlegroups.com> Message-ID: <200511071638.11343.jstroud@mbi.ucla.edu> On Monday 07 November 2005 16:18, google at fatherfrost.com wrote: > Ya, for some reason your non-greedy "?" doesn't seem to be taking. > This works: > > re.sub('(.*)(00.*?01) target_mark', r'\2', your_string) The non-greedy is actually acting as expected. This is because non-greedy operators are "forward looking", not "backward looking". So the non-greedy finds the start of the first start-of-the-match it comes accross and then finds the first occurrence of '01' that makes the complete match, otherwise the greedy operator would match .* as much as it could, gobbling up all '01's before the last because these match '.*'. For example: py> rgx = re.compile(r"(00.*01) target_mark") py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') ['00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01'] py> rgx = re.compile(r"(00.*?01) target_mark") py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') ['00 noise1 01 noise2 00 target 01', '00 dowhat 01'] My understanding is that backward looking operators are very resource expensive to implement. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From jepler at unpythonic.net Tue Nov 29 17:05:43 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 29 Nov 2005 16:05:43 -0600 Subject: unicode speed In-Reply-To: References: Message-ID: <20051129220543.GE8850@unpythonic.net> On Tue, Nov 29, 2005 at 09:48:15AM +0100, David Siroky wrote: > Hi! > > I need to enlighten myself in Python unicode speed and implementation. > > My platform is AMD Athlon at 1300 (x86-32), Debian, Python 2.4. > > First a simple example (and time results): > > x = "a"*50000000 > real 0m0.195s > user 0m0.144s > sys 0m0.046s > > x = u"a"*50000000 > real 0m2.477s > user 0m2.119s > sys 0m0.225s > > So my first question is why creation of a unicode string lasts more then 10x > longer than non-unicode string? string objects have the optimization described in the log message below. The same optimization hasn't been made to unicode_repeat, though it would probably also benefit from it. ------------------------------------------------------------------------ r30616 | rhettinger | 2003-01-06 04:33:56 -0600 (Mon, 06 Jan 2003) | 11 lines Optimize string_repeat. Christian Tismer pointed out the high cost of the loop overhead and function call overhead for 'c' * n where n is large. Accordingly, the new code only makes lg2(n) loops. Interestingly, 'c' * 1000 * 1000 ran a bit faster with old code. At some point, the loop and function call overhead became cheaper than invalidating the cache with lengthy memcpys. But for more typical sizes of n, the new code runs much faster and for larger values of n it runs only a bit slower. ------------------------------------------------------------------------ If you're a "C" coder too, consider creating and submitting a patch to do this to the patch tracker on http://sf.net/projects/python . That's the best thing you can do to ensure the optimization is considered for a future release of Python. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bdesth.quelquechose at free.quelquepart.fr Sat Nov 12 21:02:15 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 Nov 2005 03:02:15 +0100 Subject: Multikey Dict? In-Reply-To: <1131841761.745972.249830@o13g2000cwo.googlegroups.com> References: <437682b5$0$2108$edfadb0f@dtext02.news.tele.dk> <1131841761.745972.249830@o13g2000cwo.googlegroups.com> Message-ID: <43769462$0$21678$626a54ce@news.free.fr> Sam Pointon a ?crit : >>If I could just say to Python: john and graham (and ...) are all a part >>of a "superdict" and either their id or their name can be used as keys. > > >>Can I do that somehow? > > > Sure you can. There are two obvious ways to do this - enlist the aid of > a Superdict (or similar) class to take care of the details. A simple > implementation would be: > > class Superdict(object): > > def __init__(self, by_id, by_name): > self.by_id = by_id > self.by_name = by_name > > def __getitem__(self, value): > if value.isdigit(): > return self.by_id[value] > else: > return self.by_name[value] What if the OP now wants non numeric id fields ? From python at rcn.com Sat Nov 19 23:24:09 2005 From: python at rcn.com (Raymond Hettinger) Date: 19 Nov 2005 20:24:09 -0800 Subject: exception raised by nested iterator being ignored by for loop References: Message-ID: <1132460648.987425.137240@g47g2000cwa.googlegroups.com> james t kirk wrote: > I'm writing a wrapper class to handle the line merging and filtering > for a log file analysis app > > The problem I'm running into is that the StopIteration exception > raised when the wrapped file goes past EOF isn't causing the second > for loop to stop. Admiral Kirk, The innermost for-loop is catching its own StopIteration. You need to explicitly raise StopIteration in your next() method when there are no more lines in the file (hint, add an else-clause to the for-loop). Alternatively, you could simplify your life by writing the whole wrapper as a generator: import gzip def wrapper(filename) : if filename[-3:] == ".gz" : fh = gzip.GzipFile(filename, "r") else : fh = open(filename, "r") for line in fh: if line[:1] != "t": # filter out lines starting with 't' yield line.rstrip() fh.close() Raymond Hettinger Starfleet Command From bobueland at yahoo.com Thu Nov 17 06:02:15 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 17 Nov 2005 03:02:15 -0800 Subject: IDLE question References: <1132217965.434209.122200@f14g2000cwb.googlegroups.com> <3u3186FvbckvU1@individual.net> <1132221788.888868.8370@f14g2000cwb.googlegroups.com> <3u34abFv24c5U1@individual.net> Message-ID: <1132225335.948524.162190@g43g2000cwa.googlegroups.com> I did as you suggested, however after I make a new File (File/New Window) and save and then run (F5) I get the following alert The Python Shell is already executing a command; please waith until it is finished I also get the error message Traceback (most recent call last): File "", line 1, in -toplevel- import os; from path import path ImportError: No module named path >>> Bob From aum at spam.me.please Tue Nov 8 00:58:17 2005 From: aum at spam.me.please (aum) Date: Tue, 08 Nov 2005 18:58:17 +1300 Subject: PyFLTK - an underrated gem for GUI projects References: <87acgg3e8n.fsf@jupiter.g2ctech> Message-ID: On Mon, 07 Nov 2005 09:10:32 -0200, Jorge Godoy wrote: > Installing things mean, usually: 8>< Distilling what you've said, it would appear the essence of your argument is "PyFLTK is less desirable because it's not popular", an argument which, despite a level of pragmatic truth, does contain more than a little bit of recursion. Fortunately this thinking wasn't too widespread in the early days of wx and wxPython. I do respect wxPython. It's definitely a high-class gui environment. But for smaller gui programs not needing the power of wx, I find I get the job done much more quickly and effortlessly with PyFLTK. -- Cheers David From aleax at mail.comcast.net Thu Nov 3 00:20:49 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 2 Nov 2005 21:20:49 -0800 Subject: Python's website does a great disservice to the language References: <1130959513.228185.265740@g14g2000cwa.googlegroups.com> Message-ID: <1h5f4ih.1vzj241qzcz4tN%aleax@mail.comcast.net> The Eternal Squire wrote: ... > 2) Consider what he really wants for a supervisor of software > engineers. Ideally such a person should be a software engineer with > at least 3 times the experience of the most junior member. Such a I like the general idea but not your formula. If the most junior team member was 1 month out of school, would it really be OK for the supervisor to be somebody who graduated 3 months ago?-) Alex From fredrik at pythonware.com Fri Nov 4 09:52:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Nov 2005 15:52:48 +0100 Subject: ExpatError attributes References: <5f56302b0511040614r7233a577mce08e06a2542b1ff@mail.gmail.com> Message-ID: Daniel Nogradi wrote: > According to the documentation the xml.parsers.expat module provides > the exception ExpatError and this exception has 3 attributes, lineno, offset > and code. I would like to use lineno, but can't. > try: > minidom.parse("my.xml") > except ExpatError: > print 'The file my.xml is not well-formed.' > print 'And the problem is here: ', ExpatError.lineno you're supposed to look at the exception instance, not the class that defines it: try: minidom.parse("my.xml") except ExpatError, v: print 'The file my.xml is not well-formed.' print 'And the problem is here: ', v.lineno more here: http://docs.python.org/tut/node10.html From stefan.arentz at gmail.com Thu Nov 3 07:25:21 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 03 Nov 2005 13:25:21 +0100 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> <87y846j5fe.fsf@keizer.soze.com> Message-ID: <87u0etkjf2.fsf@keizer.soze.com> Stuart Turner writes: > I'm already using it for a ton of things - I want to try and get broader > acceptance in the organisation for it to be made and 'officially supported > product'. IMO that is what you need to communicate: 'already using it for a ton of things' and probably adding 'being more productive than with tool XYZ' S. From fperez.net at gmail.com Fri Nov 11 00:17:35 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 10 Nov 2005 22:17:35 -0700 Subject: exceptions, internals (introspection?) References: <4373ae4a$1@nntp.zianet.com> Message-ID: ej wrote: > I have often wondered how to get at other internals, such as the name of > the current function, file, line number I am in? The arguments to the > current function, etc. I browsed through the table of contents of both the > Library Reference & Language Reference. I see section 18. Python Language > Services. In browsing through that, I'm thinking "Oh man... this is way > more than I need - there's got to be an easier way." Nothing else is > jumping out at me. Can someone point me to some documentation on this > subject and/or provide some examples? Poke around IPython, which implements a pretty massive amount of functionality in this direction. In particular, you want to read OInspect.py and ultraTB.py. Cheers, f From onurb at xiludom.gro Wed Nov 2 07:43:53 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 02 Nov 2005 13:43:53 +0100 Subject: About the Python Expert In-Reply-To: References: Message-ID: <4368b48a$0$8296$626a14ce@news.free.fr> blah at blah.blah wrote: > Hey, i didnt say i need an expert. wel i did... anyways, i m just > saying that Fan is not a good python programmer, he doesnt know enough > python to help those who have joined his group, i know its askin a > lot, and i m not askin for a private tutor, just someone(s), to pop > into the group, see the discussions and help the people. but it is ur > decision. Why would someone "pop into the group" when there are already this newsgroup and the tutor ml ? And if you are not happy with whatever group you joined, just quit. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mwm at mired.org Thu Nov 24 10:49:03 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 10:49:03 -0500 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> Message-ID: <864q62yrkg.fsf@bhuda.mired.org> "Martin P. Hellwig" writes: > If the non-techie is still interested, I'll rave on about that I > understand why GPL is a good way to ensure availability of IP > especially if the software is a collaborated effort in the academic > scene. Your comment about the GPL "ensuring availability" would imply that other-licensed software has a tendency to become unavailable. Do you know of any examples of such? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From cvanarsdall at mvista.com Thu Nov 17 19:29:46 2005 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 17 Nov 2005 16:29:46 -0800 Subject: about try and exception In-Reply-To: <8c11e4350511171621p17034516u85ec7044efa69a2f@mail.gmail.com> References: <8c11e4350511171621p17034516u85ec7044efa69a2f@mail.gmail.com> Message-ID: <437D207A.2020102@mvista.com> I would think that when the exception occurs the interpreter exits the block of code it is currently in and enters the exception block. Thus the line n = 1/2 would never get executed. -Carl Ben Bush wrote: > I wrote the following code to test the use of "try...exception", > and I want n to be printed out. However, the following code's output is: > Traceback (most recent call last): > File > "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\py\use\tryExVa.py", line 7, in ? > print n > NameError: name 'n' is not defined > > the code is here: > > try: > m=2/0 > n=1/2 > except ZeroDivisionError: > pass > print "Yes!!! This line will always print" > print n From noway at sorry.com Thu Nov 24 20:17:09 2005 From: noway at sorry.com (Giovanni Bajo) Date: Fri, 25 Nov 2005 01:17:09 GMT Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> <86y83dvacs.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > And I have no problems with that. If you believe your class should > throw an error if someone calls an instances pop() method when it's > empty, do so. > > Likewise, if you want to make it so a client can't change your > attributes, feel free to do so. > > However, when you prevent a client from adding an attribute, you're > not merely making your objects immutable, you're making them > static. Python isn't a static language, it's a dynamic language. I > consider parts of it that are static to be warts. I always thought that adding an attribute was just as bad as changing the attributes, for an immutable object. But I now see your point (eventually!), they are pretty different issues. But, whatever attribute you add to the instance, it should *also* be immutable (so that, in other words, wouldn't be so different than carrying around a tuple with the original instance and the added attribute). This said, I think I devise that a language support for enforcing immutability could allow adding attributes to instance -- as long as those attributes then become immutable as well. >>> I'm not sure it's more important than >>> things like interned strings and the sharing of small integers. >>> Most >>> of the discussion of immutables here seems to be caused by newcomers >>> wanting to copy an idiom from another language which doesn't have >>> immutable variables. Their real problem is usually with binding, not >>> immutability. >> I'm not such a newcomer, but (how funny) Python is *the* language >> that introduced me to the concept of immutable objects and their >> importance in design :) > > Well, that would explain why you think it's so important - it's where > you first encountered it. Yes. But I'm familiar with different object semantics, and I found the immutable objects to be a pretty good replacement of value semantics, and to implement a kind-of pass-by-value convention in a language which only has references. > I'd argue that it's no more important than > identity - which is what I was searching for when I talked about > interned strings sharing small integers. There are builtin types that > preserve identity for equal instances, at least under some > conditions. There are no constructs for helping you do that with > user-defined objects. Should we add them for the sake of > orthogonality? I don't think so - not without a good use case. I don't think identity is important for immutable objects (as I wrote elsewhere), so I don't think adding language constucts for this would prove useful. Instead, immutable objects *are* common, and we still miss a way to mark them as such. -- Giovanni Bajo From jsfrank.chen at msa.hinet.net Tue Nov 1 13:16:14 2005 From: jsfrank.chen at msa.hinet.net (Thomas Moore) Date: Wed, 2 Nov 2005 02:16:14 +0800 Subject: String Identity Test References: Message-ID: <004701c5df10$59a7b100$2c8cfea9@Thomas> Hi: > Were you planning to write code that relied on id(x) being different > for different but identical strings x or do you just try to understand > what's going on? > Just try to understand what's going on..... Thanks All. From fredrik at pythonware.com Tue Nov 22 03:20:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 09:20:34 +0100 Subject: Why are there no ordered dictionaries? References: <1h6c7sd.1z0nwvuy4g9c9N%aleax@mail.comcast.net> Message-ID: Tom Anderson wrote: > Incidentally, can we call that the "Larosa-Foord ordered mapping"? The implementation, sure. > Then it sounds like some kind of rocket science discrete mathematics stuff But math folks usually name things after the person(s) who came up with the idea, not just some random implementer. The idea of combining unordered mappings and ordered sequences is older than Python itself. From steve at REMOVEMEcyber.com.au Tue Nov 15 21:12:38 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 16 Nov 2005 13:12:38 +1100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> Message-ID: <437A9596.6020006@REMOVEMEcyber.com.au> Roy Smith wrote: > You can't tell the difference between: > > try: > for i in 5: > print i + 1 > except TypeError: > print "non-iterable" > > and > > try: > for i in ["one", "two", "three"]: > print i + 1 > except TypeError: > print "can't add string and integer" try: for item in obj: do_stuff(item) except TypeError, msg: if msg == "iteration over non-sequence": handle_non_iterator() else: # re-raise the exception raise -- Steven. From Tommy.Ryding at gmail.com Thu Nov 3 04:57:19 2005 From: Tommy.Ryding at gmail.com (Tommy.Ryding at gmail.com) Date: 3 Nov 2005 01:57:19 -0800 Subject: typo in the documentation or am I stupid? Message-ID: <1131011839.813636.129140@g47g2000cwa.googlegroups.com> In the embedding Python manual at Python.org an example is presented that uses the function: PyDict_GetAttrString. Is it possible that this is a typo? I have searched the source code and I can't find it, I have also used google and I only get 4 hits. In for example Programming Python another function with similar name is described: PyObject_GetAttrString. Could that be the one that fit into the example? Hopefully someone knows the answer to my question ;) //Tommy Link to the spot at Python.org: http://docs.python.org/ext/pure-embedding.html From benji at benjiyork.com Tue Nov 8 13:49:24 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 08 Nov 2005 13:49:24 -0500 Subject: debugger In-Reply-To: <1131474688.096736.173480@z14g2000cwz.googlegroups.com> References: <1131474688.096736.173480@z14g2000cwz.googlegroups.com> Message-ID: <4370F334.1090102@benjiyork.com> robert.dowell at gmail.com wrote: > Benji York wrote: >>You might like Winpdb: >>http://www.digitalpeers.com/pythondebugger/ > > Not Found > > The requested URL /pythondebugger/-- was not found on this server. > Apache/2.0.52 (Red Hat) Server at www.digitalpeers.com Port 80 Works for me. -- Benji York From steve at REMOVETHIScyber.com.au Fri Nov 18 22:57:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 14:57:23 +1100 Subject: How to convert a "long in a string" to a "long"? References: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> <2voff.857$Nd.317876@newshog.newsread.com> Message-ID: On Fri, 18 Nov 2005 17:49:50 +0000, Leif K-Brooks wrote: > Sion Arrowsmith wrote: >> Steven Bethard wrote: >> >>>ondekoza at gmail.com wrote: >>> >>>>s = long("0xffffffffL") >>>>ValueError: invalid literal for long(): 0xffffffffL >>>> >>>>>>int("0xffffffff", 0) >>> >>>4294967295L >> >> So why does the base argument to int() (or long()) default to >> 10 and not 0? > > Because it's designed for numbers normal people provide, not for numbers > programmers provide. Normal people see 0123 as being equal to 123, not 83. The base arguments to int() and long() default to base 10 because base 10 is used by just about all people and cultures in the world. Leading zeroes are mathematically meaningless: 0123 means 0*base**3 + 1*base**2 + 2*base**1 + 3*base**0, which is identical to 123 no matter what base you choose. Interpreting 0123 in octal is a sop to programmers who want/need compatibility to the C bug that changes the meaning of numeric literals according to the presence or absence of a leading zero. Alas I suspect that this particular piece of illogic is too ingrained now to ever eradicate. -- Steven. From lycka at carmen.se Thu Nov 3 09:55:10 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 03 Nov 2005 15:55:10 +0100 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > There is no instance variable at that point. How can it add 2, to > something that doesn't exist at the moment. Because 'a += 1' is only a shorthand for 'a = a + 1' if a is an immutable object? Anyway, the behaviour is well documented. http://docs.python.org/ref/augassign.html says: An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. ... For targets which are attribute references, the initial value is retrieved with a getattr() and the result is assigned with a setattr(). Notice that the two methods do not necessarily refer to the same variable. When getattr() refers to a class variable, setattr() still writes to an instance variable. For example: class A: x = 3 # class variable a = A() a.x += 1 # writes a.x as 4 leaving A.x as 3 From cjw at sympatico.ca Sun Nov 20 19:01:53 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 20 Nov 2005 19:01:53 -0500 Subject: examining python objects In-Reply-To: <1132413271.287391.66790@g43g2000cwa.googlegroups.com> References: <1132339687.048155.252160@g47g2000cwa.googlegroups.com> <437ef75a$0$32754$626a14ce@news.free.fr> <1132413271.287391.66790@g43g2000cwa.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > Bruno Desthuilliers wrote: > >>rurpy at yahoo.com a ?crit : >> >>>Is there a function/class/module/whatever I can use to >>>look at objects? I want something that will print the object's >>>value (if any) in pretty-printed form, and list all it's attributes >>>and their values. And do all that recursively. >>>I want to be able to find out everything about an object that >>>Python can introspectively find out. >> >>Then check the inspect module > > > I want a callable, ready-to-use class or function. > Inspect provides soime funtions that would be useful for wrinting > such a class or function, but does not provide one. > > I seems that nobody who has written or used such a tool reads > this group, or feels like responding. > > FWIW, (for anyone looking for something similar in the future) > I found http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/137951 > which will format and print an object's attributes. By combining that > and pprint in the Python distrib, I think can coble up what I am > looking > for. > > Still, it is discouraging that such a basic thing is not provided with > python, or at lleast easily available in some library. > In the interactive mode, you might try >> help(object) Colin W. From robert.kern at gmail.com Wed Nov 9 18:15:44 2005 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 Nov 2005 15:15:44 -0800 Subject: struct, IEEE-754 and internal representation In-Reply-To: <437280ee$1@nntp.zianet.com> References: <437280ee$1@nntp.zianet.com> Message-ID: ej wrote: > If that's true, then I guess I am confused why Python is displaying > 148.72999572753906 when you unpack the 4 bytes, implying a lot more > precision that was available in the original 32-bits? Python is doing > 64-bit floating point here? I'm obviously not understanding something... > help? Yes, Python uses C double precision floats for float objects. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dcalvelo at gmail.com Thu Nov 24 21:15:55 2005 From: dcalvelo at gmail.com (dcalvelo at gmail.com) Date: 24 Nov 2005 18:15:55 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383b600.500692667@news.oz.net> <4384DD77.9080303@online.de> Message-ID: <1132884955.735518.213780@g47g2000cwa.googlegroups.com> "hacer" probablemente. DCA. Piet van Oostrum wrote: > >>>>> Christoph Zwerschke (CZ) escribi?: > > >CZ> Eso es exactamente lo que yo queria haber! > > ?Haber? ?Tener? :=( > -- > Piet van Oostrum > URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] > Private email: piet at vanoostrum.org From bonono at gmail.com Mon Nov 21 04:54:38 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 21 Nov 2005 01:54:38 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> Message-ID: <1132566878.521180.115790@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > > If I need the dict feature 90% of the time, and the list feature 10% of > > the time. > > Wasn't your use case that you wanted to specify form fields in > a given order (LIST), render a default view of the form in that > order (LIST), and, later on, access the field specifiers in an > arbitrary order, based on their key (DICT). Sure looks like it's > the LIST aspect that's important here... Yes. But whether LIST aspect or DICT is important is well, opinion. So let's leave it there. > > > I want an ordered dict. Rather than a list and create this new view every > > time and every where I want to use it as a dict. > > You want an ordered dict because you say you want one, not be- > cause it's the best way to address your use case. That's fine, but > it's not really related to the question asked in the subject line. Again, best way is decided by ME. If I am entering a coding contest which is organized by YOU, that is a different story. As for related to the subject line, since when I said my preference or use case has anything to do with the subject line ? I have said in another post that I don't think there should be one in the standard library, which is directly about the subject line. > > > parsing or not parsing is not the point, and parsing/converting is > > still "create a new view" of an existing data structure. > > Copying the entire data structure hardly qualifies as "creating a > new view". dict() doesn't do that; in this use case, it doesn't cost > you anything to use it. doesn't cost me anything ? That is good news to me. From fuzzyman at gmail.com Thu Nov 24 10:13:40 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Nov 2005 07:13:40 -0800 Subject: Understanding Python Documentation In-Reply-To: References: Message-ID: <1132845220.002413.318300@g44g2000cwa.googlegroups.com> pydoc - sorry to be terse... I'm sure others will expand. :-) There was also a project, recently, that generated the sort of api documentation for the whole standard library. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From martin at v.loewis.de Thu Nov 24 03:23:37 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 24 Nov 2005 09:23:37 +0100 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <3ukk91F11t5c5U1@individual.net> References: <3uk6siF11mqgvU1@individual.net> <4384ec18$0$25871$9b622d9e@news.freenet.de> <438505AA.8000105@redlinepy.com> <43850790$0$4066$9b622d9e@news.freenet.de> <3ukk91F11t5c5U1@individual.net> Message-ID: <4385788a$0$24921$9b622d9e@news.freenet.de> Paul Watson wrote: > It appears that _ALL_SOURCE gets defined in the /usr/include/standards.h > file. If we could #define _ANSI_C_SOURCE or _POSIX_SOURCE, it appears > that it would eleminate _ALL_SOURCE. Ah, ok - this should be easy enough. Python would normally define _POSIX_SOURCE (through _XOPEN_SOURCE), but configure(.in) has this block: # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined # or has another value. By not (re)defining it, the defaults come in place. AIX/4) define_xopen_source=no;; AIX/5) if test `uname -r` -eq 1; then define_xopen_source=no fi ;; which causes _XOPEN_SOURCE (and subsequently probably _POSIX_SOURCE) not to be defined. What AIX version are you using? Can you try removing the fragment from configure(.in), rerun configure, verify that _XOPEN_SOURCE is defined in pyconfig.h, and then try building again? If this works, this might be a solution. Otherwise, we need to put something like this into _codecs_cn.c: #ifdef hz /* On AIX version such-and-such, hz is defined because _ALL_SOURCE is defined, this in turn is defined because _XOPEN_SOURCE is not. As _XOPEN_SOURCE cannot be enabled (see configure.in), we just work around by removing the hz definition again. */ #undef hz #endif Regards, Martin From case.nelson at gmail.com Fri Nov 11 22:08:07 2005 From: case.nelson at gmail.com (snoe) Date: 11 Nov 2005 19:08:07 -0800 Subject: Hash map with multiple keys per value ? In-Reply-To: References: Message-ID: <1131764887.474718.223900@g44g2000cwa.googlegroups.com> Are you looking for this type of thing? class Test: value = 900 t = Test() d['1'] = t d['2'] = t d['3'] = t d['3'].value = 800 d['1'].value From fredrik at pythonware.com Mon Nov 28 09:55:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Nov 2005 15:55:32 +0100 Subject: General question about Python design goals References: Message-ID: Duncan Booth wrote: > > I'm just illustrating that some list-like methods with tuples > > could be usefull. > > > But you aren't illustrating that at all. "But assume that I have some other use case" From skip at pobox.com Tue Nov 22 15:07:23 2005 From: skip at pobox.com (skip at pobox.com) Date: Tue, 22 Nov 2005 14:07:23 -0600 Subject: bsddb185 question In-Reply-To: <1132685940.792215.304760@o13g2000cwo.googlegroups.com> References: <1132611401.426797.143120@g47g2000cwa.googlegroups.com> <4382a563$0$8870$9b622d9e@news.freenet.de> <1132666914.659909.315550@g49g2000cwa.googlegroups.com> <1132685940.792215.304760@o13g2000cwo.googlegroups.com> Message-ID: <17283.31355.309869.443191@montanaro.dyndns.org> thakadu> Ok but if you read my original post I already said that! Sure, I did. I was recapping what the purpose of the bsddb185 module is and why its API is not likely to change. thadaku> The issue is that I have an application that needs to share thakadu> data with an existing Berekeley db 1.85 database and thakadu> applications in perl. Sure if I was creating the database thakadu> myself I would use the newer bsddbmodule but I can't require thakadu> the perl code be rewritten, so is there any way in Python to thakadu> read and write to a legacy 1.85 Berkely db? Yup. Use the bsddb185 module and suffer with the older API. Note that part of the reason the API it exposes is so feeble is that the underlying 1.85 Berkeley DB library doesn't provide anything better. The API you've become used to with the later bsddb module is only available because the underlying library API is more complete. Skip From godoy at ieee.org Fri Nov 18 05:55:54 2005 From: godoy at ieee.org (Jorge Godoy) Date: 18 Nov 2005 08:55:54 -0200 Subject: Zope vs Php References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> <86br0in877.fsf@bhuda.mired.org> <87hdaa3brc.fsf@jupiter.g2ctech> <86oe4iljz4.fsf@bhuda.mired.org> <878xvm39mt.fsf@jupiter.g2ctech> <867jb6lfxj.fsf@bhuda.mired.org> Message-ID: <87u0ea1ayt.fsf@jupiter.g2ctech> Mike Meyer writes: > Unfortunately, my tools don't - which is another one of the things I > like about Cheetah: it doesn't interfere with my X/HTML tools. For > instance, I edit attributes by asking the editor to let me edit the > current tags attributes. It opens window with a list of valid > attributes, along with type information about those attributes. I edit > the list, close the window, and it inserts the required attributes, > appropriately quoted, into the tag. I couldn't use that for py:* > attributes without tweaking the DTD for each language I wanted to > edit. Similar problems crop up with the other features that depend on > information from the DTD. What DTD do you use to write Python code? ;-) I can use my "HTML writing tool" with the XHTML, HTML, etc. DTD specified and have it insert the tags for me. The Python namespace allows me to insert Python commands and still have valid (X)HTML output (at least tidy is very happy with them). After I have the mockup, with Python tags embedded, I send the files to the webdesigners and they do their art. :-) For one project we are using a lot of CSS and JavaScript. But, as you can see with TurboGears, it's possible to do even more with it. -- Jorge Godoy From http Mon Nov 28 16:20:16 2005 From: http (Paul Rubin) Date: 28 Nov 2005 13:20:16 -0800 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> <86lkz8vh34.fsf@bhuda.mired.org> Message-ID: <7x1x10ii5r.fsf@ruckus.brouhaha.com> Mike Meyer writes: > Which means you can't create a verifier which will verify all > programs. Is there a reason to believe that you can't have a verifier > with three possible outcomes: Correct, Incorrect, and I don't know, > and it is always correct in doing so? Note that "I don't know" could > be "I ran longer than I think is reasonable and gave up trying." It's trivial to write such a verifier, if you get my drift. From bokr at oz.net Fri Nov 18 16:38:06 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 18 Nov 2005 21:38:06 GMT Subject: Behaviour of enumerated types (was: Re: Immutable instances, constant values) References: <437d6711.87269326@news.oz.net> Message-ID: <437e3cb3.141959727@news.oz.net> On Fri, 18 Nov 2005 23:43:10 +1100 (EST), Ben Finney wrote: >Bengt Richter wrote: >> Ben Finney wrote: >> >I've recently packaged 'enum' in PyPI. >> [...] >> My notion of enum comes from (what I remember of) Pascal > >You might want to investigate the 'enum' package for my idea of how an >enumerated type can work. I guess I saw an earlier version, and got confused as to the goal, sorry. I will look in PyPI. > >> which is basically an ordered set of names of integers forming a >> type, and ord(one_of_the_names) gets you the index value. > >Getting a numeric index might be useful in a language such as Pascal, >with no built-in dict or sequence types. In Python, where any >immutable object can be a dict key, and any sequence can be iterated, >it seems of no use. Does your concept of enumeration not have a fixed order of a set of names? If it does, what is more natural than using their index values as keys to other ordered info? OTOH, the index values (and hence my enums) are[1] not very good as unique dict keys, since they compare[2] promiscuously with each other and other number types. Hm, maybe if hash were defined class-unique, e.g., def __hash__(self): return hash((int(self), type(self).__name__) Ok, did that, _seems_ to work (fixed __repr__ too): [1] were & [2] compared ;-) >>> from makeenum import makeEnum >>> Few = makeEnum('Few','zero one two three') >>> Few() Few('zero') >>> d = dict((Few(n), Few.names.index(n)) for n in Few.names) >>> d {Few('zero'): 0, Few('three'): 3, Few('one'): 1, Few('two'): 2} >>> d[1] Traceback (most recent call last): File "", line 1, in ? KeyError: 1 >>> d[Few(1)] 1 But still can work as integer: >>> 'ABC'[Few(1)] 'B' >>> 'ABC'[Few('one')] 'B' >>> 'ABC'[Few('two')] 'C' > >> But what we have is named integers, much as True and False are built >> in names for integer subtypes with value 1 and 0. > >That's an implementation detail; surely code shouldn't be expecting >any particular relationship between integers and boolean values? Au contraire, much code depends on it, e.g., >>> def verboselen(s): return '%r has %d element%s'%(s, len(s), ('s','')[len(s)==1]) ... >>> verboselen(range(3)) '[0, 1, 2] has 3 elements' >>> verboselen(range(0)) '[] has 0 elements' >>> verboselen(range(1)) '[0] has 1 element' >>> type(len(range(3))==1) >>> type(len(range(3))==1).mro() [, , ] >>> int (len(range(3))==1) 0 >>> int (len(range(1))==1) 1 > >> So I'd say enums should also be int subtypes... > >Likewise, that seems best left as an implementation detail. Why expect >any particular mapping to int values? Doing arithmetic or boolean >logic on enumerated values seems against their purpose. I guess I will have to look at your enum in PyPI to understand what you mean by "their purpose" ;-) To me the int correspondence is as expectable and natural as a,b,c=range(3) (at least as a default) though I think different enumerations should be different types. Note that the ordering of int values makes the instances nicely sortable too, e.g., >>> d.items() [(Few('zero'), 0), (Few('three'), 3), (Few('one'), 1), (Few('two'), 2)] >>> sorted(d.items()) [(Few('zero'), 0), (Few('one'), 1), (Few('two'), 2), (Few('three'), 3)] or more directly >>> d.keys() [Few('zero'), Few('three'), Few('one'), Few('two')] >>> sorted(d.keys()) [Few('zero'), Few('one'), Few('two'), Few('three')] Enumerations defined as monotonic but non-contiguous sequences of named int values are conceivable too. They can be useful in defining bit masks with distinguishable types, but that act like ints. Kind of a sparse enumeration. Maybe I'll add that in. But bottom line, I really thing the int base type is more than an implementation detail. I think it's natural for an _ordered_ set of names ;-) I'll go look at PyPI now ;-) Regards, Bengt Richter From larry.bates at websafe.com Fri Nov 11 13:55:50 2005 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 11 Nov 2005 12:55:50 -0600 Subject: Internal Variables In-Reply-To: References: Message-ID: <4374E936.6030104@websafe.com> What you want are attributes of sys object. import sys print sys.version -Larry Bates James Colannino wrote: > Hey everyone. I hope I have my terminology right, because I'm not quite > sure what to call them. I was just wondering how I can find information > in internal variables (for example - and I'm just making this up - > __version__ to give me the version of Python.) The only reason I ask is > that I'm trying very hard to search for information and can't find > anything. Perhaps the information I'm looking for isn't even contained > in variables but rather some other sort of object. Basically, I just > want to know how from within a script I can get information about the > python interpreter that I'm running. Thanks in advance. > > James > From drochom at WYTNIJ.hyene.com Sun Nov 20 08:15:40 2005 From: drochom at WYTNIJ.hyene.com (przemek drochomirecki) Date: Sun, 20 Nov 2005 14:15:40 +0100 Subject: about dictionary References: Message-ID: Uzytkownik "Peter Otten" <__peter__ at web.de> napisal w wiadomosci news:dlppk4$f0v$00$1 at news.t-online.com... > Shi Mu wrote: > > > how to do with it? > > Use Ben Finney's, not Przemek's approach if the values are mutables that you > plan to modify. If that's what you are asking. > > Peter Maybe he just want to use dictionary as a set. He can use SET container instead. Przemek From mwm at mired.org Thu Nov 24 11:20:46 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 11:20:46 -0500 Subject: return in loop for ? References: <1132812397.369787.214140@g47g2000cwa.googlegroups.com> Message-ID: <86y83exbj5.fsf@bhuda.mired.org> Duncan Booth writes: > In practice it is impossible to write code in Python (or most > languages) with only one return point from a function: any line could throw > an exception which is effectively another return point, so the cleanup has > to be done properly anyway. This simply isn't true. Not having a return statement is no worse than not having a goto. Well, maybe it's a little worse. A number of languages don't have it. Rewriting my example to have a single return is easy: def f(): for i in range(20): if i > 10: break inloop() # Added for a later example return This isn't noticably different than the original. Of course, if you want to *do* something after the for loop, you have to test the conditional again (or use a flag variable): def f(): for i in range(20): if i > 10: break inloop() if not (i > 10): afterloop() return In my experience, people who believe that single exit is a good principle often believe that's true at the statement level as well, so that "break" and "continue" in for loops are bad things. That means you have to rewrite the above as: def f(): for i in [j for j in range(20) if j <= 10]: inloop() if not (i > 10): afterloop() return At this point, the argument collapses in a cloud of impracticality, and we go back to returning from wherever we want to. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From peter at engcorp.com Tue Nov 8 20:53:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Nov 2005 20:53:38 -0500 Subject: which feature of python do you like most? In-Reply-To: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: <042dne8P_Ys9y-zenZ2dnUVZ_sadnZ2d@powergate.ca> zelzel.zsu at gmail.com wrote: > I have no idea why people are so facinating with python. Hey, I'm fascinating even without python! -Peter From diesch at spamfence.net Sat Nov 12 00:51:29 2005 From: diesch at spamfence.net (Florian Diesch) Date: Sat, 12 Nov 2005 06:51:29 +0100 Subject: how to present Python's OO feature in design? References: <1131332809.044523.169900@o13g2000cwo.googlegroups.com> <1131333250.078344.176070@g43g2000cwa.googlegroups.com> <1131333662.653503.285330@g47g2000cwa.googlegroups.com> <1131347829.761335.6780@g43g2000cwa.googlegroups.com> <1131357179.515200.48320@g44g2000cwa.googlegroups.com> Message-ID: <20051112055129.1614.e.NOFFLE@dieschf.news.arcor.de> Ben Sizer wrote: > I don't know if there are any tools that convert UML to Python code, dia2code Floriaa -- Einen Troll zu f?ttern ist das gleiche als w?rde man einen Haufen Hundescheisse sehen, absichtlich reinsteigen und sich dann beschweren. (Christian Schneider in <2005-10-25T10-04-37 at bofh.my-fqdn.de>) From cito at online.de Wed Nov 23 17:31:19 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 23:31:19 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132759280.221030.210460@g44g2000cwa.googlegroups.com> References: <438258f2.411334718@news.oz.net> <4383635b.479535916@news.oz.net> <1132734447.104113.99140@o13g2000cwo.googlegroups.com> <1132759280.221030.210460@g44g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > That's not the only use case. Other use cases are to have a specific > order, not based on entry time. > > Simple example : > d1 = OrderedDict(some_dict.items()) > d1.sequence.sort() > d1 is now an ordered dict with the keys in alphabetic order. As I said, I would not need to access the sequence, if I can write d1.sort() or d1.sortkeys() > If you don't want to modify sequence, don't. If you want a copy do : > seq = d1.sequence[:] This is not needed since you can do the same with: seq = d1.keys() -- Christoph From scott.daniels at acm.org Fri Nov 11 12:52:01 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 11 Nov 2005 09:52:01 -0800 Subject: testing C code with python In-Reply-To: References: <1131661106.277887.308690@z14g2000cwz.googlegroups.com> Message-ID: <4374d900$1@nntp0.pdx.net> >Bilgehan.Balban at gmail.com wrote: > A simple question - Is it common/good practice to test C code using > Python? I certainly do such testing (hand-wrapped, because it doesn't seem to cost too much time to do so. Usually I develop in Python and accumulate my tests there, then write the C equivalent, and move the tests to the C code. I've done this for programs that were always to have become C programs as well as for those things I intend to wrap as Python modules. -- -Scott David Daniels scott.daniels at acm.org From steve at REMOVETHIScyber.com.au Tue Nov 22 16:42:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 23 Nov 2005 08:42:59 +1100 Subject: about sort and dictionary References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> Message-ID: On Tue, 22 Nov 2005 08:53:07 -0800, rurpy wrote: > I am not a complete newb at python, but I am still pretty new. > I too thought immediately that the output should be 3,2,1, 1,2,3. What you are saying is that a.reverse() should *both* change a in place *and* return a reference to the same list. > I used reverse() and sort() a couple time and of course read > the docs before I did. I noted they do the change inplace, and > don't find rememering that to be a terrible burden. Actually, I > get rather annoyed by the comment that they return None "as > a reminder" that the change is inplace. How arrogant! While > I'm sure the designers had kindly intentions. my memory, though > bad, is not that bad, and I object to being forced to write code > that is more clunky than need be, because the designers thought > they needed to help me with my memory. Built-in methods with side-effects (sort, reverse, update, clear, etc.) return None because every function must return something, not because it is a reminder. Python is not Pascal, and there are no procedures. There are four possibilities for a construction like list.sort(): (1) sort the list in place and return a reference to the same list; (2) sort the list in place and return a copy of the same list; (3) sort the list in place and return None; (4) don't sort in place and return a sorted list. No solution is always right, no solution is always wrong, but the most flexible is a combination of (3) and (4). Python now has that with sort() and sorted(). Prior to the addition of sorted() to the language, (3) was considered the best solution because of a simple Python principle: never duplicate objects unless explicitly told to. -- Steven. From bearophileHUGS at lycos.com Thu Nov 10 13:43:04 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Nov 2005 10:43:04 -0800 Subject: help make it faster please In-Reply-To: <1131647869.950612.174670@g43g2000cwa.googlegroups.com> References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> <1131646601.299316.166570@g47g2000cwa.googlegroups.com> <1131647332.797580.138890@g49g2000cwa.googlegroups.com> <1131647869.950612.174670@g43g2000cwa.googlegroups.com> Message-ID: <1131648184.768134.89610@f14g2000cwb.googlegroups.com> This can be faster, it avoids doing the same things more times: from string import maketrans, ascii_lowercase, ascii_uppercase def create_words(afile): stripper = """'[",;<>{}_&?!():[]\.=+-*\t\n\r^%0123456789/""" mapper = maketrans(stripper + ascii_uppercase, " "*len(stripper) + ascii_lowercase) countDict = {} for line in afile: for w in line.translate(mapper).split(): if w: if w in countDict: countDict[w] += 1 else: countDict[w] = 1 word_freq = countDict.items() word_freq.sort() for word, freq in word_freq: print word, freq create_words(file("test.txt")) If you can load the whole file in memory then it can be made a little faster... Bear hugs, bearophile From bonono at gmail.com Sat Nov 19 04:48:55 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 19 Nov 2005 01:48:55 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132376750.855932.45470@g47g2000cwa.googlegroups.com> Message-ID: <1132393735.499057.213340@g49g2000cwa.googlegroups.com> Steven D'Aprano wrote: > L = ["zero" if n == 0 else \ > "negative " + ("odd" if n % 2 else "even") if n < 0 else \ > "odd" if n % 2 else "even" for n in range(8)] > BTW, the continuation is not necessary I believe. [ x==0 and "zero" or ["","-"][x < 0] + ("even", "odd")[x%2] for x in range(8) ] isn't too bad. though I like the C one a bit more(as it doesn't overload the and/or) [ x==0 ? "zero" : ["","-"][x < 0] + ("even", "odd")[x%2] for x in range(8) ] As it is still a very straight forward flow(from left to right, without "internal decision split in between"). From michele.simionato at gmail.com Thu Nov 10 08:31:29 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 Nov 2005 05:31:29 -0800 Subject: web interface In-Reply-To: References: Message-ID: <1131629489.471501.126980@g47g2000cwa.googlegroups.com> I have been looking for an example like this for a while, so thanks to J.P. Calderone. Unfortunately, this kind of solution is pretty much browser-dependent. For instance, I tried it and it worked with Firefox, but not with MSIE 5.01 and it will not work with any browser if you disable Javascript. So, I don't think there is a real solution for this kind of problem as of today (I would love to be wrong, though). Michele Simionato From uval at rz.uni-karlsruhe.de Mon Nov 21 08:16:43 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Mon, 21 Nov 2005 14:16:43 +0100 Subject: sort the list In-Reply-To: References: Message-ID: [...] >> >>> lst = [[1,4],[3,9],[2,5],[3,2]] >> >>> lst >>[[1, 4], [3, 9], [2, 5], [3, 2]] >> >>> >> >>> >> >>> lst.sort(cmp = lambda x,y: cmp(x[1], y[1])) >> >>> lst >>[[3, 2], [1, 4], [2, 5], [3, 9]] >> >>> >> >>works for Python 2.4 >>in earlier Pythons just let cmp = .. away >> >>Regards, Daniel > > what does let cmp = .. away mean? it means lst.sort(lambda x,y: cmp(x[1], y[1])) I can offer you some more brain food to digest ;) maybe you can adapt this solution, but that depends on your problem I find it clear and I used it recently >>> name, age, salary = "name", "age", "salary" >>> people = [ ... {name:"oliver", age:25, salary:1800}, ... {name:"mischa", age:23, salary:0}, ... {name:"peter", age:22, salary:1500}, ... ] >>> >>> def cmpFabrik(field): ... def cmpFunc(x,y): ... return cmp(x[field], y[field]) ... return cmpFunc >>> people.sort(cmp = cmpFabrik(name)) >>> people.sort(cmp = cmpFabrik(age)) >>> people.sort(cmp = cmpFabrik(salary)) it's not very OO but sometimes things are simple and no need to create a class Regards, Daniel From kaiser.vocote at gmail.com Wed Nov 2 06:35:22 2005 From: kaiser.vocote at gmail.com (Andreas Kaiser) Date: 2 Nov 2005 03:35:22 -0800 Subject: tachometer diagram In-Reply-To: References: <1130753253.564379.63190@g47g2000cwa.googlegroups.com> Message-ID: <1130931322.508958.209180@f14g2000cwb.googlegroups.com> Hi Franz, you're right! Andrea (the developer of these widgets) sends me this link about the wxPython ML. Thanks. Andreas From steve at holdenweb.com Fri Nov 25 03:36:26 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Nov 2005 08:36:26 +0000 Subject: return in loop for ? In-Reply-To: References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: <4386CD0A.2070403@holdenweb.com> Steven D'Aprano wrote: > On Thu, 24 Nov 2005 12:51:34 +0000, Duncan Booth wrote: > > >>Steven D'Aprano wrote: >> >> >>>>While outwardly they apear to offer a technique for making software >>>>more reliable there are two shortcomings I'm leery of. First, no >>>>verification program can verify itself; >>> >>>That's not a problem if there exists a verification program A which >>>can't verify itself but can verify program B, which in turn also can't >>>verify itself but will verify program A. >>> >> >>That is logically equivalent to the first case, so it doesn't get you >>anywhere. (Just combine A and B into a single program which invokes A >>unless the input is A when it invokes B instead.) > > > Then there you go, there is a single program which can verify itself. > > I think you are confabulating the impossibility of any program which can > verify ALL programs (including itself) with the impossibility of a program > verifying itself. Programs which operate on their own source code do not > violate the Halting Problem. Neither do programs which verify some > subset of the set of all possibly programs. > > There seems to have been some misattribution in recent messages, since I believe it was *me* who raised doubts about a program verifying itself. This has nothing to do with the Halting Problem at all. A very simple possible verification program is one that outputs True for any input. This will also verify itself. Unfortunately its output will be invalid in that and many other cases. I maintain that we cannot rely on any program's assertions about its own formal correctness. 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 Fri Nov 11 12:48:24 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 11 Nov 2005 09:48:24 -0800 Subject: What do you use as symbols for Python ? In-Reply-To: References: <4372f88a$0$31833$636a15ce@news.free.fr> Message-ID: <4374d828$1@nntp0.pdx.net> Sion Arrowsmith wrote: ... > class State: > Enum = range(3) > OPENED, CLOSED, ERROR = Enum > Names = { OPENED: "OPENED", CLOSED: "CLOSED", ERROR: "ERROR" } > so you can used State.Names[state] to provide something user-readable, ... Or use a function like: def named(value, classes): for klass in classes: for name, val in vars(klass).iteritems(): if val == value: return name raise ValueError, "No names for %r in %s" (value, classes) Remember CPU time is almost free when it is associated with a line typed to a user paying attention. This way you (A) don't have to repeat the names in the source (a great place for errors), and (B) you can say to yourself, "I think this is in one of these several things" and go hunting happily. In our example, named(2, [State]) gives us "ERROR" -- -Scott David Daniels scott.daniels at acm.org From luismgz at gmail.com Fri Nov 25 19:51:13 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 25 Nov 2005 16:51:13 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132966273.190972.47820@f14g2000cwb.googlegroups.com> IMHO, the easier alternative for building GUI apps with Python is PythonCard. It is based on wxWindows, and it lets you build gui apps by dragging and dropping widgets on a form, just like VB or Delphi. It is very high level and very easy to learn and use. http://pythoncard.sourceforge.net/ Another alternative, also based in wxWindows, is Boa Constructor, but I wouldn't recomend it over Pythoncard. Good luck! Luis From bokr at oz.net Tue Nov 22 21:48:18 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 23 Nov 2005 02:48:18 GMT Subject: Why are there no ordered dictionaries? References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: <4383d564.508728452@news.oz.net> On Tue, 22 Nov 2005 22:06:12 +0100, Christoph Zwerschke wrote: >> d1[0:0] + d1[2:2] ==> OrderedDict( (1, 11), (3, 13) ) > >Oops, sorry, that was nonsense again. I meant >d1[0:1] + d1[1:2] ==> OrderedDict( (1, 11), (3, 13) ) > >> Ordered dictionaries could allow slicing and concatenation. > >Some operations such as concatenation need of course special >considerations, since the keys must stay unique. A concatenation of >ordered dicts with overlapping keys should probably give an IndexError. > If you define the semantics like feeding overlapping keys in a tuple sequence to dict, then later duplicate keys just replace prior ones by same rules as d[k]=v1; d[k]=v2. I think that makes sense in this context, and can be defined unambigously. Regards, Bengt Richter From tim.vets at skynet.be Tue Nov 22 18:34:07 2005 From: tim.vets at skynet.be (tim) Date: Wed, 23 Nov 2005 00:34:07 +0100 Subject: hex string to hex value In-Reply-To: <1132701750.841307.97890@g14g2000cwa.googlegroups.com> References: <1132701750.841307.97890@g14g2000cwa.googlegroups.com> Message-ID: <4383AAEF.9010809@skynet.be> but then i get : >>> m 66 >>> n=int(hex(m)) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 0x42 >>> what am I missing here ? thank you Tim avnit wrote: >If you just want to convert a string to an integer, it would be: > > > >>>>int(n) >>>> >>>> > >in your case it would be: > > > >>>>m=66 >>>>n=int(hex(m)) >>>> >>>> > > > From mwm at mired.org Wed Nov 2 19:01:46 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 02 Nov 2005 19:01:46 -0500 Subject: Getting a function name from string References: <436943e0$0$2083$edfadb0f@dtext02.news.tele.dk> Message-ID: <86vezabnv9.fsf@bhuda.mired.org> "Paul McGuire" writes: > "David Rasmussen" wrote in message > news:436943e0$0$2083$edfadb0f at dtext02.news.tele.dk... >> If I have a string that contains the name of a function, can I call it? >> As in: >> >> def someFunction(): >> print "Hello" >> >> s = "someFunction" >> s() # I know this is wrong, but you get the idea... >> >> /David > > Lookup the function in the vars() dictionary. > >>>> def fn(x): > ... return x*x > ... >>>> vars()['fn'] > >>>> vars()['fn'](100) > 10000 vars() sans arguments is just locals, meaning it won't find functions in the global name space if you use it inside a function: >>> def fn(x): ... print x ... >>> def fn2(): ... vars()['fn']('Hello') ... >>> fn2() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in fn2 KeyError: 'fn' >>> Using globals() in this case will work, but then won't find functions defined in the local name space. For a lot of uses, it'd be better to build the dictionary by hand rather than relying on one of the tools that turns a namespace into a dictionary. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From david.rasmussen at gmx.net Wed Nov 2 17:55:34 2005 From: david.rasmussen at gmx.net (David Rasmussen) Date: Wed, 02 Nov 2005 23:55:34 +0100 Subject: Getting a function name from string Message-ID: <436943e0$0$2083$edfadb0f@dtext02.news.tele.dk> If I have a string that contains the name of a function, can I call it? As in: def someFunction(): print "Hello" s = "someFunction" s() # I know this is wrong, but you get the idea... /David From paul at boddie.org.uk Wed Nov 30 18:10:29 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 30 Nov 2005 15:10:29 -0800 Subject: python speed In-Reply-To: References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133380421.028537.110860@g44g2000cwa.googlegroups.com> Message-ID: <1133392229.502845.91040@o13g2000cwo.googlegroups.com> Carsten Haese wrote: > On Wed, 2005-11-30 at 14:53, Paul Boddie wrote: > > [...] the Java virtual machine > > is suitably designed/specified to permit just-in-time complication. > > +1 Freudian slip of the week :) Well, I never said it was easy. ;-) Paul From aleax at mail.comcast.net Fri Nov 11 10:55:11 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 11 Nov 2005 07:55:11 -0800 Subject: derived / base class name conflicts References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> <1131677456.966817.147470@g44g2000cwa.googlegroups.com> <43747075$0$7344$636a55ce@news.free.fr> <1131724161.083151.255920@g14g2000cwa.googlegroups.com> Message-ID: <1h5ur8n.y19ta61ga3f5mN%aleax@mail.comcast.net> wrote: ... > I don't think it is reasonable in general to only subclass from base > classes you have studied the full API of, however. The double I think you underestimate the level of coupling that inevitably occurs between base and derived classes. In general, such coupling being strong, knowing the full API of the base class is inevitable (although in some special corner-case, when you do only need to add private data, you may, exceptionally, get away with less knowledge). Alex From http Wed Nov 9 23:34:49 2005 From: http (Paul Rubin) Date: 09 Nov 2005 20:34:49 -0800 Subject: Iterator addition Message-ID: <7x4q6lm87q.fsf_-_@ruckus.brouhaha.com> Is there a good reason to not define iter1+iter2 to be the same as itertools.chain(iter1, iter2)? Examples: # all lines in a collection of files, like perl <> all_lines = file1 + file2 + file3 candidate_primes = (2,) + (1+2*i for i in itertools.count(1)) # candidate_primes is 2,3,5,7,9,11,... primes = itertools.ifilter(is_prime, candidate_primes) From nico-NoSp at m-tekNico.net Tue Nov 8 02:39:06 2005 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Tue, 08 Nov 2005 08:39:06 +0100 Subject: Newbie Alert: Help me store constants pythonically In-Reply-To: <1131412583.285926.185740@g49g2000cwa.googlegroups.com> References: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> <436EDDA8.5020600@REMOVEMEcyber.com.au> <1131412583.285926.185740@g49g2000cwa.googlegroups.com> Message-ID: <43705817$1_3@newsgate.x-privat.org> > Also my config files have (a tiny bit of) nested > structure, such as: > > Model1( > numBumps = 1 > sizeOfBumps = 2 > transversePlanes = [ > Plane(type=3, z=4), > Plane(type=5, z=6), > Plane(type=3, z=8) > ] > ) > > which I'm not sure the .ini format can easily support. I could use > (key buzzword voice) XML, but I fear that might send me down the > 'overcomplicating things' path. Your suggestion has given me some new > places to search Google (configparser, python config files), so I'll > look around for better ideas. You may want to look into ConfigObj: http://www.voidspace.org.uk/python/configobj.html#config-files -- Nicola Larosa - nico-NoSp at m-tekNico.net No inventions have really significantly eased the cognitive difficulty of writing scalable concurrent applications and it is unlikely that any will in the near term. [...] Most of all, threads do not help, in fact, they make the problem worse in many cases. -- G. Lefkowitz, August 2005 From root at smtp.imst.de Tue Nov 29 04:25:16 2005 From: root at smtp.imst.de (root) Date: Tue, 29 Nov 2005 10:25:16 +0100 Subject: Virus in your Mail to empire.support Message-ID: <200511290925.jAT9PGqw018233@smtp.imst.de> The VirusCheck at the IMST generated the following Message: V I R U S A L E R T Our VirusCheck found a Virus (W32/Netsky-Q) in your eMail to "empire.support". This eMail has been deleted ! Now it is on you to check your System for Viruses This System is running with Linux and Amavis (www.amavis.org). :-) From bonono at gmail.com Wed Nov 23 23:15:59 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 20:15:59 -0800 Subject: Python as Guido Intended In-Reply-To: <867jay1ybk.fsf@bhuda.mired.org> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1132800973.008501.34090@g14g2000cwa.googlegroups.com> <867jay1ybk.fsf@bhuda.mired.org> Message-ID: <1132805759.799632.265850@f14g2000cwb.googlegroups.com> Mike Meyer wrote: > "bonono at gmail.com" writes: > >> You're the one that wants to use the hammer to do whatever it is, not > >> me. I don't believe in silver bullets. Python is good at what it > >> does. If I need a different tool, I use a different tool, rather than > >> try and mangle a good tool into something it's not. Such attempts are > >> pretty much doomed. They nearly inevitably produce a tool that's not > >> as good at what the original did as the original, and not as good at > >> whatever new task it's being mangled to do as a tool that was > >> designed for that in the first place. > > And again. > > This isn't a Python thing, it's a believe about tools in general - > that you should choose the right tool for the job. It isn't applied > very often to hardware tools because they aren't as mallable as > software tools, and have in general been around and improving for a > long time. But it applies to programming languages, data formats, and > similar more mallable things. Changes that make them better at what > they do are welcome; changes that make the into what they aren't are > viewed with great suspicion. > > Maybe Python attracts people who share that belief. After all, TRTFTJ > is implies TSBOOWTDI, and vice versa. I was not talking about the believe, I was talking about the way you presented it. You are setting up an "imaginary" me, which is not me. And that is the kind of arguments I saw, I believe this many times are done unconciously. From stefan.arentz at gmail.com Thu Nov 3 09:35:50 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 03 Nov 2005 15:35:50 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: <878xw5lry1.fsf@keizer.soze.com> Antoon Pardon writes: ... > Fine, we have the code: > > b.a += 2 > > We found the class variable, because there is no instance variable, > then why is the class variable not incremented by two now? Because it really is executed as: b.a = b.a + 2 1. get 't'b.a and store it in a temporary 't' (found the instance) 2. add 2 to 't' 3. store 't' in 'b.a' The last operation stores it into an instance variable. > > > Remember, Python is a dynamic language. > > So? Python being a dynamic language doesn't prevent the following to fail: > > >>> a=1 > >>> def f(): > ... a += 2 > ... > >>> f() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in f > UnboundLocalError: local variable 'a' referenced before assignment See the 'global' keyword. s. From finite.automaton at gmail.com Thu Nov 10 15:16:44 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Nov 2005 12:16:44 -0800 Subject: wxPython newbie question, creating "mega widgets" , and DnD In-Reply-To: <1131635970.831338.109280@g49g2000cwa.googlegroups.com> References: <1131635970.831338.109280@g49g2000cwa.googlegroups.com> Message-ID: <1131653804.477649.89440@f14g2000cwb.googlegroups.com> Yes, wx.Panel. > A side question - why is their a EVT_LIST_BEGIN_DRAG but no > EVT_LIST_END_DRAG, unlike tree's which have BEGIN and END? I need a > draggable list box, and would prefer to not handle low level mouse > events. Dunno. There is an EVT_LIST_COL_END_DRAG, though, maybe that will help. From bokr at oz.net Wed Nov 2 01:33:28 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 02 Nov 2005 06:33:28 GMT Subject: Running autogenerated code in another python instance References: Message-ID: <43685941.1593033671@news.oz.net> On Wed, 2 Nov 2005 06:08:22 +0000 (UTC), Paul Cochrane wrote: >Hi all, > >I've got an application that I'm writing that autogenerates python code >which I then execute with exec(). I know that this is not the best way to >run things, and I'm not 100% sure as to what I really should do. I've had a >look through Programming Python and the Python Cookbook, which have given me >ideas, but nothing has gelled yet, so I thought I'd put the question to the >community. But first, let me be a little more detailed in what I want to >do: > [...] > >Any help or advice would be really (really!) appreciated. > It's a little hard to tell without knowing more about your user input (command language?) syntax that is translated to or feeds the process that "autogenerates python code". E.g., is it a limited python subset that you are accepting as input, or a command language that you might implement using the cmd module, or ? There are lots of easy things you could do without generating and exec-ing python code per se. How complex is a user session state? What modifies it? What actions are possible? History? Undo? Is the data a static passive resource to view, or partly generated or made accessible by prior actions in a session? Single user or collaborative? Shared access to everything or only to static data? Etc., etc. Some examples of user input and corresponding generated python might help, with some idea of the kind of visualization aspects being controlled ;-) Regards, Bengt Richter From steve at holdenweb.com Tue Nov 8 17:09:37 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 Nov 2005 22:09:37 +0000 Subject: How to convert a number to hex number? In-Reply-To: <7xhdamygy7.fsf@ruckus.brouhaha.com> References: <1131442115.025438.326670@g49g2000cwa.googlegroups.com> <1131464101.546746.107110@g47g2000cwa.googlegroups.com> <7xmzkfrum1.fsf@ruckus.brouhaha.com> <7xhdamygy7.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: > >>>Try hex(33**33). >> >>You're usually smarter than this, or am I missing some joke? >> >> >>> hex(33*33) >>'0x441' > > > You used only one * (multiplication), I used two *'s (exponentiation). > > >>> hex(33**33) > '0x5857366DCE0162CB5DDCD1BF0FC7C03A6438304421L' That makes sense. Sorry, a bit sleep-deprived today. 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 eurleif at ecritters.biz Wed Nov 2 02:30:10 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 02 Nov 2005 07:30:10 GMT Subject: dictionary that have functions with arguments In-Reply-To: <1h5d70w.1dtb368qvz6kgN%aleax@mail.comcast.net> References: <1130903698.450993.268680@f14g2000cwb.googlegroups.com> <1h5d70w.1dtb368qvz6kgN%aleax@mail.comcast.net> Message-ID: <6WZ9f.1023$ZA3.233518@monger.newsread.com> Alex Martelli wrote: > execfunc = { 'key1' : (func1, ()), > 'key2' : (func2, args) } > > now, something like: > > f, a = execfunc[k] > f(**a) > > will work for either key. Shouldn't func1's args be a dictionary, not a tuple? From eyubin at gmail.com Wed Nov 2 21:57:02 2005 From: eyubin at gmail.com (ice) Date: 2 Nov 2005 18:57:02 -0800 Subject: how to write a blog system with Python Message-ID: <1130986622.788569.225120@o13g2000cwo.googlegroups.com> I am a fresh here , and I have no idea of it. Do you have any comments? From damonwischik at gmail.com Fri Nov 25 06:46:14 2005 From: damonwischik at gmail.com (damonwischik at gmail.com) Date: 25 Nov 2005 03:46:14 -0800 Subject: Stealing focus: PIL Message-ID: <1132919173.955637.90140@z14g2000cwz.googlegroups.com> I'm using the Python Image Library (PIL) for Python 2.4. If I have an image and I show it from PIL import Image im = Image.new('RGB',100,100) im.show() then the output window steals focus. It's very handy to use an image to show the progress of execution for my program, but the computer is unusable when focus keeps on being stolen every few seconds. How can I prevent Image.show() from stealing focus? Damon. From alex.greif at gmail.com Mon Nov 14 07:28:39 2005 From: alex.greif at gmail.com (Alex Greif) Date: Mon, 14 Nov 2005 13:28:39 +0100 Subject: multiple inharitance super() question Message-ID: <778770d80511140428g181c00d8rded6d5e4402a1e93@mail.gmail.com> Hi, Before 2.2 I could initialize multiple super classes like this: class B(A,AA): def __init__(self, args): A.__init__(self,args) AA.__init__(self,args) Tutorials say that since python 2.2 superclasses should be initialized with the super() construct. class A(object): def __init__(self, args): ... class B(A): def __init__(self, args): super(B, self).__init__(args) BUT what happens if B extends from A and AA like: class A(object): def __init__(self, args): ... class AA(object): def __init__(self, args): ... class B(A,AA): def __init__(self, args): super(B, self).__init__(args) How can I tell that B.__init__() should initialize A and AA? Or is the new super() so clever to call A.__init__() and AA.__init__() internally? thanks, Alex Greif ________________________________________ http://www.fotobuch-xxl.de/ From jorg at neoplex.org Tue Nov 8 01:57:44 2005 From: jorg at neoplex.org (=?ISO-8859-1?Q?Jorg_R=F8dsj=F8?=) Date: Tue, 08 Nov 2005 07:57:44 +0100 Subject: os.path.getmtime on winXP Message-ID: <43704c83@news.broadpark.no> [sorry to those reading twice, but I just realised that I had posted this after mucking about with the date on my machine to try to figure this out -- so the message probably went into last months messages for most people including me.] Hi I'm trying to use os.path.getmtime to check if a file has been modified. My OS is WinXP. The problem is, that when the os changes from/to daylight savings time, the result is suddenly off by 3600 seconds ie. one hour, even if the file remains the same. I've tried using win32file.GetFileTime, and it reports a consistent number, regardless of DST. What is happening here? My first thought is that getmtime should measure 'raw' time, and not be concerned with DST, and thus give me the same result no matter the date on the machine I call it. Is the module broken in some way, or am I just missing something here? regards Jorg R?dsj? From iamkris at gmail.com Mon Nov 14 15:09:38 2005 From: iamkris at gmail.com (Kris) Date: 14 Nov 2005 12:09:38 -0800 Subject: SnakeCard products source code In-Reply-To: References: Message-ID: <1131998978.863972.144880@g14g2000cwa.googlegroups.com> Thanks for sharing it. I am interested in the GINA part. Philippe C. Martin wrote: > Dear all, > > The source code is available in the download section: www.snakecard.com > > Regards, > > Philippe From steve at REMOVETHIScyber.com.au Sat Nov 5 20:21:39 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 06 Nov 2005 12:21:39 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <436c0527.146082265@news.oz.net> <864q6rkfie.fsf@bhuda.mired.org> <436d0b61.213212052@news.oz.net> <7xirv639kb.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 05 Nov 2005 16:27:00 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> But do you want x += y to work for immutable objects as well? Then >> __iadd__ cannot be a statement, because x can't be modified in place. > > It never occurred to me that immutable objects could implement __iadd__. > If they can, I'm puzzled as to why. ??? The classic += idiom comes from C, where you typically use it on ints and pointers. In C, ints aren't objects, they are just bytes, so you can modify them in place. I'm surprised that it never occurred to you that people might want to do something like x = 1; x += 1 in Python, especially as the lack of such a feature (as I recall) was one of the biggest complaints from C programmers crossing over to Python. Personally, I'm not fussed about +=. Now that it is in the language, I'll use it, but I never missed it when it wasn't in the language. >> While I am enjoying the hoops people are jumping through to modify the >> language so that b.a += 2 assigns b.a in the same scope as it was >> accessed, I'm still rather perplexed as to why you would want that >> behaviour. > > Weren't you the one saying += acting differently for mutables and > immutables was a wart? Nope, not me. > If it's such a wart, why are do you find it so > important to be able to rely on the more bizarre consequences of the > wartiness? Warts should be (if not fixed) avoided, not relied on. The consequences of instance.attribute += 1 may be unexpected for those who haven't thought it through, or read the documentation, but they aren't bizarre. Whether that makes it a feature or a wart depends on whether you think non-method attributes should be inherited or not. I think they should be. I can respect the position of somebody who says that only methods should be inherited -- somebody, I think it was you, suggested that there is at least one existing OO language that doesn't allow inheritance for attributes, but never responded to my asking what language it was. Personally, I would not like an OO language that didn't inherit attributes, but at least that is consistent. (At least, if you don't consider methods to be a particular sort of attribute.) But I can't understand the position of folks who want inheritance but don't want the behaviour that Python currently exhibits. instance.attribute sometimes reading from the class attribute is a feature of inheritance; instance.attribute always writing to the instance is a feature of OOP; instance.attribute sometimes writing to the instance and sometimes writing to the class would be, in my opinion, not just a wart but a full-blown misfeature. I ask and I ask and I ask for some use of this proposed behaviour, and nobody is either willing or able to tell me where how or why it would be useful. What should I conclude from this? -- Steven. From juho.schultz at helsinki.fi Wed Nov 9 08:19:29 2005 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Wed, 09 Nov 2005 15:19:29 +0200 Subject: append to non-existing list In-Reply-To: References: Message-ID: Yves Glodt wrote: > Hello, > > if I do this: > > for row in sqlsth: > ________pkcolumns.append(row[0].strip()) > ________etc > > > without a prior: > > pkcolumns = []; > > > I get this error on first iteration: > UnboundLocalError: local variable 'pkcolums' referenced before assignment > > I guess that's normal as it's the way python works...?!? > > My question is: Is there no way to append to a non existing list? > > I am lazy for declaring it first, IMHO it bloats the code, and (don't > know if it's good to say that here) where I come from (php) I was used > to not-needing it... > > > regards, > Yves You mean you want to type "pkcolumns" only once to keep your code short? Would something like this be useful? pkcolumns = [row.strip() for row in sqlsth] From avnit7 at gmail.com Sun Nov 20 15:12:00 2005 From: avnit7 at gmail.com (avnit) Date: 20 Nov 2005 12:12:00 -0800 Subject: Command line In-Reply-To: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> References: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> Message-ID: <1132517520.719843.217590@z14g2000cwz.googlegroups.com> What OS are you using. I'm not sure about anything else but on a mac it's: >>import os >>os.system("ls -la") From http Wed Nov 30 00:43:06 2005 From: http (Paul Rubin) Date: 29 Nov 2005 21:43:06 -0800 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> Message-ID: <7xirua3d3p.fsf@ruckus.brouhaha.com> Mike Meyer writes: > When it was suggested that a facility for doing this be added to the > language, I asked for a use case for it. Nobodies come up with a > reason for placing such restriction on the client yet. If you've got a > use case, I'd be interested in hearing it. I see it the other way; almost all the time in my own code I try to initialize all of any instance's attributes in an __init__ method. Dynamically adding attributes is useful sometimes, but done willy-nilly leads to spaghetti code. In the cases where it's useful, I'd rather see it done through a special __setattr__ method, perhaps inherited from a mixin: class Frob(Whatsit, DynamicAttributeMixin): ... However, that's not likely to happen. From iperez at skytecpr.com Thu Nov 3 09:09:06 2005 From: iperez at skytecpr.com (Ivan Perez) Date: Thu, 3 Nov 2005 10:09:06 -0400 Subject: Can somebody help compiling 'mssqldb.pyd' for Python24 [win]? Message-ID: Did you ever find any information about this... I've been trying to compile it, but wanted to know if someone had done it first. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen.thorne at gmail.com Thu Nov 3 21:00:32 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 4 Nov 2005 12:00:32 +1000 Subject: Not Equal to Each Other? In-Reply-To: <1131066067.980875.223790@g43g2000cwa.googlegroups.com> References: <1131066067.980875.223790@g43g2000cwa.googlegroups.com> Message-ID: <3e8ca5c80511031800q4a22f654h@mail.gmail.com> On 3 Nov 2005 17:01:08 -0800, ale.of.ginger at gmail.com wrote: > the above so that all the data in one row is not equal to each other, > is there something I can write to make it simpler? For example, > (cellboard[0] is not cellboard[1] is not ... cellboard[8]) only worked > for the numbers to the left and right of the cell - is there anyway I > can expand this to cover all numbers in a set range? Python has an operator call 'in', which will allow you to do what you're after. "1 in (1,2,3)" will be true "4 in (1,2,3)" will be false "not 1 in (1,2,3)" will be false So you'd be after something along the lines of: not cellboard[0] in (cellboard[1], ...., celboard[8]). This seems quite tedious to write, maybe you should consider something along the lines of using slicing: not celboard[0] in cellboard[1:8] I hope i have given you enough tools to do what you're trying to do. -- Stephen Thorne Development Engineer From pythonnew at gmail.com Sun Nov 13 15:02:16 2005 From: pythonnew at gmail.com (Ben Bush) Date: Sun, 13 Nov 2005 12:02:16 -0800 Subject: the button of cancel In-Reply-To: References: <8c11e4350511122015l63fc54e1md0e5a1c1a3cf6904@mail.gmail.com> Message-ID: <8c11e4350511131202k67bae4e3uf015edaa7af1f27a@mail.gmail.com> On 11/13/05, Fredrik Lundh wrote: > > Ben Bush wrote: > > > When I click the button of cancel, > > I got the follwoing message. I want to see "Goodbye" on the console > screen. > > What to do? > > > KeyboardInterrupt: operation cancelled > > > num = input( "Enter a number between 1 and 100: " ) > > while num < 1 or num > 100: > > print "Oops, your input value (", num, ") is out of range." > > num = input( "Be sure to enter a value between 1 and 100: " ) > > you need to catch the exception, and print the message you want. > > try: > ... your code ... > except KeyboardInterrupt: > print "Goodbye!" > > see chapter 8.3 in the tutorial for more info: > > http://docs.python.org/tut/node10.html > > > Thanks, now the code works. I wonder when i put the number between 1 and > 100, I get the message of 'Your number is in the range' but i still see the > input box. How to remove it? > num = input( "Enter a number between 1 and 100: " ) > try: > while num < 1 or num > 100: > print 'Oops, your input value (', num, ') is out of range.' > num = input( 'Be sure to enter a value between 1 and 100: ' ) > num=input('Your number is in the range') > except KeyboardInterrupt: > print 'Goodbye!' -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVETHIScyber.com.au Sat Nov 19 05:57:17 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 21:57:17 +1100 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: On Sat, 19 Nov 2005 01:33:40 -0800, bearophileHUGS wrote: > Steven D'Aprano: >> Perhaps Python should concatenate numeric literals at compile time: >> 123 456 is the same as 123456. > > I think using the underscore it is more explicit: > n = 123_456 It is also easy to make a typo: n = 123-456 -- Steven. From nick at craig-wood.com Mon Nov 14 05:30:07 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 14 Nov 2005 04:30:07 -0600 Subject: How to avoid "f.close" (no parens) bug? References: Message-ID: Peter wrote: > First off, please explain what you are talking about better next time. > > Second, What on earth are you talking about? > > "f" is a file object, correct? > > Are you trying to close a file by typing f.close or is the file closing > when you type f.close? I would guess that this person is coming to python from perl. In perl, you are allowed to miss the parens off a method call if it takes no arguments, so f.close is equivalent to f.close(). I used to make this mistake all the time. However it is one pychecker catches, so install pychecker and run it on all your programs is the answer! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From plucek at ssaris.com Wed Nov 9 09:40:48 2005 From: plucek at ssaris.com (PL) Date: 9 Nov 2005 06:40:48 -0800 Subject: need an example of Python numarray to C++ and back again, Boost / SWIG? Message-ID: <1131547248.473442.313820@g47g2000cwa.googlegroups.com> I want to pass a 2D array from Python to C++, manipulate it in C++ (for example, add 1 to each element) and pass it back to Python. With these building blocks I will be able to figure out all the rest of what I need to do for my project. I am very familiar with Python, but less so with C++ and Boost or SWIG. Does anyone have an example with all steps that I can follow? More specifically I am looking for the C++ code, ".i" file for SWIG and/or the analagous setup files that Boost would need to do this. Thanks in advance for any help you can provide, From mwm at mired.org Thu Nov 10 14:53:45 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 14:53:45 -0500 Subject: ANN: P(x) 0.2 applet builder References: <86br0t6mtz.fsf@bhuda.mired.org> <1131610240.716331.50600@g14g2000cwa.googlegroups.com> Message-ID: <867jbg6zzq.fsf@bhuda.mired.org> Steve Holden writes: > LB wrote: >>>The tarball can be found at >>http://www.mired.org/downloads/P(x)-0.2.tar.gz >. >> Something doesn't work with the link. >> LB >> > Copy the whole string up to and including the ".gz" at the end and > paste that into your browser's location window. > > I think it's a bit ill-advised to use parens in a URL, and if you do > then they shoud really be represented as %xx escapes. I wouldn't have expected parens to be a problem in a URL - they aren't magic characters in URLs. I expected some problems in dealing with it in a shell, but not on the web. Because of that, I looked for - but didn't find - an option in distutils to specify a name for the tarball. I finally decided not to fight distutils, and went with the name it wanted to use. Since following standards is optional on the web, at least if things work in the most popular browser of the day, I probably should have seen this coming. The URL with the ()'s pre-escaped is: http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tim.golden at viacom-outdoor.co.uk Fri Nov 4 11:53:30 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 4 Nov 2005 16:53:30 -0000 Subject: how to open a windows folder? Message-ID: <9A28C052FF32734DACB0A288A3533991044D22F0@vogbs009.gb.vo.local> [Bell, Kevin] > I'd love to be able to open up a windows folder, > like c:\temp, so that it pops up visually. > I know how to drill down into a directory, but I > can't figure out how to open one up on screen. > Would I have to make a call to windows explorer > in a similar way that I hit Excel with: Ummm. I may have misunderstood you, but would either of: import os os.startfile ("c:/temp") # or import os os.system (r"explorer c:\temp") be what you wanted? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jstroud at mbi.ucla.edu Fri Nov 4 15:47:25 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 4 Nov 2005 12:47:25 -0800 Subject: I need Motivation In-Reply-To: <1131089202.065204.48370@z14g2000cwz.googlegroups.com> References: <436b0b9b$0$11068$e4fe514c@news.xs4all.nl> <1131089202.065204.48370@z14g2000cwz.googlegroups.com> Message-ID: <200511041247.25315.jstroud@mbi.ucla.edu> On Thursday 03 November 2005 23:26, bonono at gmail.com wrote: > Martin P. Hellwig wrote: > > blah at blah.blah wrote: > > > I m not a python Expert or anythin > > > i need help, i m losin my motivation to continue with python > > > can anyone inspire me again.??? > > > > Ooh that is easy, start learning other programming languages, you'll go > > back continuing with python very soon after that! ;-) > > It seems that many people switch to Ruby and never look back, some > other go to haskell as well. I would try a scbasic for classic macs. Very easy to program in, if you can find a quadra. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bokr at oz.net Thu Nov 10 21:59:04 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 11 Nov 2005 02:59:04 GMT Subject: How to set program name in Python? ($0 in Perl) References: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> <4373c4e4.152866300@news.oz.net> Message-ID: <437402b9.168695771@news.oz.net> On Thu, 10 Nov 2005 23:29:28 +0100, "Fredrik Lundh" wrote: >Bengt Richter wrote: > >> >> > Is there a way to set the program name in Python, similar to $0 in >> >> > Perl? >> >> > >> >> >>From `man perlvar`: >> >> > >> >> > $0 Contains the name of the program being executed. On some oper- >> >> > ating systems assigning to "$0" modifies the argument area that >> >> > the ps program sees. This is more useful as a way of indicat- >> >> > ing the current program state than it is for hiding the program >> >> > you're running. (Mnemonic: same as sh and ksh.) > >> OTOH, if the intent is just to set a value for subsequent getting by way of >> sys.argv[0], isn't sys.argv an ordinary list? >> >> >>> import sys >> >>> sys.argv[0] >> '' >> >>> sys.argv[0] = '' >> >>> sys.argv[0] >> '' >> >> >>> type(sys.argv) >> > >given that Swaroop has written a nice book about Python, I somehow >suspect that he knows how sys.argv works: > > http://tinyurl.com/9s7bz > Sorry, I wasn't familiar with that (or Swaroop ;-) >or are you saying that "ps" looks inside sys.argv on your machine? > Nope. Hm, I wrote a little C a few years ago utility that prints a date-time prefix and the raw command line string but skipping arg 0. It uses win32's GetCommandLine, which returns a string pointer. [18:58] C:\pywk\clp>logline arg1 arg2 note preserved spaces. 20051110 18:58:24 arg1 arg2 note preserved spaces. Maybe ctypes could be used to get the pointer and carefully poke in a mod. But I don't know if the cmd line string is within a static fixed size array so you could lengthen it, or what. Or have they opened the source for that? Anyway, I don't know if that is where ps (pstat on my NT box) looks. Not handy to experiment ATM ;-) Regards, Bengt Richter From dduerrenmatt at swissonline.ch Fri Nov 18 16:52:58 2005 From: dduerrenmatt at swissonline.ch (David Duerrenmatt) Date: Fri, 18 Nov 2005 22:52:58 +0100 Subject: func(*params) In-Reply-To: <1132350579.176139.252840@z14g2000cwz.googlegroups.com> References: <1132350579.176139.252840@z14g2000cwz.googlegroups.com> Message-ID: Great, this is exactly what I was looking for. Thanks all of you for your immediate answer! Nick Smallbone schrieb: > David Duerrenmatt wrote: > >>Hi there >> >>For some reasons, I've to use Python 1.5.2 and am looking for a workaround: >> >>In newer Python versions, I can call a function this way: >> >>func = some_function >>func(*params) >> > > > I think the "apply" function is what you want: > > apply(object[, args[, kwargs]]) -> value > > Call a callable object with positional arguments taken from the tuple > args, and keyword arguments taken from the optional dictionary kwargs. > Note that classes are callable, as are instances with a __call__() > method. > > Deprecated since release 2.3. Instead, use the extended call syntax: > function(*args, **keywords). > From pwatson at redlinepy.com Tue Nov 15 23:10:50 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 15 Nov 2005 22:10:50 -0600 Subject: Newb ? In-Reply-To: References: Message-ID: <3tvpqaFv0q48U1@individual.net> Chad Everett wrote: > Hello all, > > Have a problem here with a challenge from a book I am reading. > Any help is much appreciated. > > I am trying to run a program that asks the user for a statement and then > prints it out backwards. > this is what I have. > It does not print anything out. I assume that I have something out of whack > with my high and low statements. > > Thanks for you help. > > > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > > high = len(message) > low = -len(message) > print > print message[high:low] > print > print raw_input("Please Press Enter to Exit") Are you sure that this is not a class assignment? You can search the messages here for the answer. From blahman Fri Nov 4 01:10:50 2005 From: blahman (blah@blah.blah) Date: Fri, 04 Nov 2005 00:10:50 -0600 Subject: Can Anyone Help me on this References: <1h5gzpu.12vbiw59vgyrfN%aleax@mail.comcast.net> Message-ID: Thx Alex. -- * Posted with NewsLeecher v3.0 Beta 7 * http://www.newsleecher.com/?usenet From ken.faulkner at gmail.com Wed Nov 16 05:23:45 2005 From: ken.faulkner at gmail.com (ken.faulkner at gmail.com) Date: 16 Nov 2005 02:23:45 -0800 Subject: JMS yet again Message-ID: <1132136625.101816.40520@g49g2000cwa.googlegroups.com> I've seen various posts over the years asking if python can be used to communicate with JMS queues (whether MQ series, Jboss queues etc etc). I've seen solutions such as pymqi (good for MQ, but not for jboss I believe), and JPype. This must seem an obvious question, but has anyone actually tried to reimplement JMS messaging nativelly in Python? I personally dont know the details of JMS, or if there is *something* about it which would make it only really possible in Java (cant think of what it could possibly be), but surely a Python version should be possible? Isn't the JMS spec publically available? Yes, this isn't a trivial application.... but *surely* someone has tried it? KenF From stefan.kanev at gmail.com Wed Nov 2 11:21:47 2005 From: stefan.kanev at gmail.com (Aquarius) Date: 2 Nov 2005 08:21:47 -0800 Subject: Python and MySQL Message-ID: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> I appologize in advance for this strange (and possibly stupid) question. I want to know if there is a way to interface a MySQL database without Python-MySQL or without installing anything that has C files that need to be compiled. The reason for this, is that I want to develop a certain web application, but my hosting provider (!#@$!@#%) isn't very eager to supply Python-MySQL (or any modules to python). Is there an alternative approach I could use to pass around this ridiculos lack of functionality? From i.failed.turing.test at gmail.com Sun Nov 13 12:41:55 2005 From: i.failed.turing.test at gmail.com (David T) Date: Sun, 13 Nov 2005 12:41:55 -0500 Subject: No subject Message-ID: <518E81F9-7FF3-4980-A38E-2A48C668412B@local> > > Thomas Edison (I think it was him) once said it took 999 failures to > make 1 success. That makes SourceForge 10 times more successful. > > >> The world is filled with >> millions of wanna-be poets, writers and creators whose sum total >> contribution to the artistic wealth of the world is negative. >> > > >> I'm not just using hyperbole. By poisoning the well with their >> garbage, >> they just make it that little bit harder for genuinely talented >> artists to >> be heard. >> > > Whose opinion? Yours, or the market's? > Just my $0.02: Individuals, and perhaps groups of individuals are the creators of works. Walt Disney was a creator. Disney Inc. is not the creator, but has managed to twist copyright laws to maintain control of Walt's mouse. Tom Edison moved to California so _he_ could skirt copyright laws of the works _he_ was stealing. (See episode 7 of "From the Earth to the Moon" miniseries, re Georges M?li?s' 1902 silent film ?Le Voyage dans la lune?) Edwin Howard Armstrong invented FM radio (and even got the patent), but RCA won the war. The giant corporation was able to twist regulations to drive Edwin to a despairing death. Today, Anne A. Mator might create a new character for Disney Inc., but the copyright belongs to Disney Inc., not Anne. Professor Suchn Such of Abig University might write a book, but "The Regents of Abig University" get the copyright. Annin Ventor might build a better widget for Transnational Megacorp, but Annin will probably never see a dime of profit or recognition. Why? IMHO, most inventors, writers and artists have too much to do and too little spare money to pay lobbyists to have laws written for them. Giant corporations do have the money to get laws written for them. Still, I've never seen a creative corporation or a creative law. The best corporations and governments can do is foster an environment where creativity flourishes and is justly rewarded. Thus, I must express my gratitude to all of those programmers who write open-source code (even if it doesn't go anywhere), and even shareware, and other works which are made available and open at no or reasonable cost. The Python community most of all. A free and open marketplace of ideas and products is quite capable of separating the triticale from the chaff. It makes all of us more productive! --David From ishtar2020 at hotmail.com Fri Nov 18 13:23:04 2005 From: ishtar2020 at hotmail.com (ishtar2020) Date: 18 Nov 2005 10:23:04 -0800 Subject: BisonGen parser generator. Newbie question Message-ID: <1132338184.846375.199390@g14g2000cwa.googlegroups.com> Hello everybody! I'm trying to run the calculator example included with the "BisonGen" parser generator, but I've been unable to put it to work. When I compile the xml file "simple.bgen" with the script "BisonGen.bat", the only parser I get is a C file. I've heard BisonGen generates also a python file, which is, I believe, the one used imported by "test.py" to run the testing. Does anybody know what I'm doing wrong here? Thank you in advance! From lycka at carmen.se Fri Nov 4 07:46:01 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 04 Nov 2005 13:46:01 +0100 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > Would it be too much to ask that in a line like. > > x = x + 1. > > both x's would resolve to the same namespace? They always do Antoon. There is no such issue for local (or global) varibles. The issue has to do with c.x = c.x + 1. In this case it's clearly designed and documented that this corresponds to: setattr(c, 'x', getattr(c, 'x') + 1) The result of these operations depends on e.g. how the __setattr__ and __getattr__ methods in the class in question are defined. You need to understand that the dot-operaterator always involves a lookup-operation that can be implemented in various ways. It's well defined that you can do things like: >>> class Counter: ... c=0 ... def __call__(self): ... self.c+=1 ... def __str__(self): ... return str(self.c) ... >>> c=Counter() >>> c() >>> print c 1 >>> c() >>> print c 2 >>> class C5(Counter): ... c=5 ... >>> c5=C5() >>> c5() >>> print c5 6 Of course, you could design a language, say Pythoon or Parthon, where this is illegal, and you force the programmer to do something longer such as: >>> class APCounter: ... c=0 ... def __init__(self): ... self.c = self.__class__.c ... def __call__(self): ... self.c+=1 ... def __str__(self): ... return str(self.c) ... I don't see this as an improvement though... From lycka at carmen.se Fri Nov 4 05:58:50 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 04 Nov 2005 11:58:50 +0100 Subject: Learning multiple languages (question for general discussion) In-Reply-To: <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > Yes, but I haven't found knowing (and using) Python dampens my > enthusiasms for learning new languages. But you're more enthusiatic than most of us Alex. I wish I could say the same, but I must admit that I only did halfhearted attempts at learning new languages after Python. I've looked a bit at most of the ones you mentioned, but there was nothing that gave me the drive to really follow it through. I've somehow become content in this regard. This doesn't mean that I'm not evolving. I regularly program in three languages (Python, C++ and SQL) and I must learn new things the whole time to keep interested, whether it's in the current problem domain, in architectural matters, in regards to libraries or development tools or whatever. Now it's Twisted for instance. Still, finding Python was a lot like finding a permanent home (which doesn't exclude various excursions, or prevent another move or two in this life.) From johnnie.pittman at gmail.com Mon Nov 14 12:19:19 2005 From: johnnie.pittman at gmail.com (johnnie pittman) Date: Mon, 14 Nov 2005 09:19:19 -0800 Subject: Not enough arguments for format string In-Reply-To: References: Message-ID: Hey Kevin, I think I see your issue. So from http://docs.python.org/lib/typesseq-strings.html: If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary). On 11/14/05, Kevin Walzer wrote: > os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export > DISPLAY; echo %s | sudo -S %s; sudo -k' %password %binpath) > > > So the line above should be: os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export DISPLAY; echo %s | sudo -S %s; sudo -k' % (password binpath)) try that. johnnie -------------- next part -------------- An HTML attachment was scrubbed... URL: From deepankar.sharma at gmail.com Wed Nov 30 22:20:49 2005 From: deepankar.sharma at gmail.com (Deep) Date: 30 Nov 2005 19:20:49 -0800 Subject: How to list currently defined classes, methods etc In-Reply-To: <438e66e7.356479220@news.oz.net> References: <1133401234.314572.315550@g47g2000cwa.googlegroups.com> <438e66e7.356479220@news.oz.net> Message-ID: <1133407248.992997.257320@z14g2000cwz.googlegroups.com> Awesome just what i was looking for now sheepishly i shall RTFM :) From gregory.petrosyan at gmail.com Tue Nov 15 16:38:08 2005 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 15 Nov 2005 13:38:08 -0800 Subject: Default method arguments In-Reply-To: <86u0edpq5v.fsf@bhuda.mired.org> References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <867jb9r6qr.fsf@bhuda.mired.org> <1132087833.419559.122310@g43g2000cwa.googlegroups.com> <86u0edpq5v.fsf@bhuda.mired.org> Message-ID: <1132090688.823913.232250@g43g2000cwa.googlegroups.com> Thanks a lot, I understood the rule. Let's don't discuss this (containers etc.) anymore, or it'll be offtopic. From siona at chiark.greenend.org.uk Fri Nov 11 09:27:44 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Nov 2005 14:27:44 +0000 (GMT) Subject: What do you use as symbols for Python ? References: <4372f88a$0$31833$636a15ce@news.free.fr> Message-ID: Gary Herron wrote: >Another similar approach that keeps those values together in a single >namespace is this (my favorite): > > class State: > OPENED, CLOSED, ERROR = range(3) > >Then you can refer to the values as > State.OPENED > State.CLOSED > State.ERROR > >The extra clarity (and slight wordiness) of the dotted notation seems, >somehow, quite Pythonic to me. I have here an implementation (written by a colleague) of a whole pile of such -- in this particular case it's helpful to do it in this style rather than the class OPENED: pass because the values are coming from/ going to a database. And it goes a little further, with class State: Enum = range(3) OPENED, CLOSED, ERROR = Enum Names = { OPENED: "OPENED", CLOSED: "CLOSED", ERROR: "ERROR" } so you can used State.Names[state] to provide something user-readable, and state in State.Enum to check data consistency. (OK, that probably doesn't make much sense with this particular State, but it does when your getting value-as-number from an external source.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From bokr at oz.net Mon Nov 28 23:13:22 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 29 Nov 2005 04:13:22 GMT Subject: General question about Python design goals References: Message-ID: <438ba299.175154008@news.oz.net> On 27 Nov 2005 21:01:49 -0800, aahz at pythoncraft.com (Aahz) wrote: >In article , >Christoph Zwerschke wrote: >>Aahz wrote: >>> Christoph deleted his own attribution: >>>> >>>>For instance, I just wanted to use the index() method on a tuple which >>>>does not work. ... >>> >>> Because Guido believes that tuples should be primarily used as >>> lightweight replacements for C structs. Therefore they have minimal >>> functionality. >> As has been pointed out list(atuple).alistmethod(thelistmethodsargs) works to get the benefit of list methods. In fact, list(anyiterable).alistmethod(thelistmethodsargs) works too. Maybe list is not the best possible unifier for defining sequence-applicable methods. I'm getting at something ;-) Tuples are iterable. Therefore, once a tuple is e.g. turned into an iterator object, Guido's feelings about the appropriate uses for tuples have been laundered away. Someone is saying "I want to treat this as a sequence" when they write, e.g., iter(atuple). If iter were a type instead of a built-in function, it could have methods that apply to all sequences. Then you could write iter(any_iterable).count(match_element) and know that that .count is uniformly available that way for any sequence passed to the iter constructor. IMO this would be better than demanding that all iterable objects themselves have all the handy sequence-applicable methods. ISTM many of the itertools goodies could be written as methods of iter, especially if you expanded the iter call signature to accept multiple iterables, so e.g., iter('abc', '12').zip() would produce an iterator like izip. Note this iterator would also be an iter or iter subclass instance, and so would have methods available so you could chain them like iter('abc','123').zip().slice(1,2) (I am dropping the prefixed 'i'). Also, these methods might have useful variants controlled by arguments, e.g., iter(seq1, seq2).zip(pad='') might insert the pad keyword argument (if present) for to pad out shorter sequences to the same length as the longest, like map(None, ...) IOW, all the methods that apply orthogonally to sequences should perhaps be methods available to iter instances. Currently you can only pass a single iterable or a callable, sentinel pair to iter, but that could be expanded. Further example... iter(open('afile')).filter(lambda line:line.strip().startswith('From:') would return a suitable filtering iterator, which in turn would have further iter methods available if desired, so iter(open('afile')).filter(lambda line:line.strip().startswith('From:').len() might return the length (hopefully optimized for iterators that have the opportunity to pass though actual length from their source, but otherwise working through the sequence). (Of course, if open returned a standard iter subclass instance, you wouldn't have to write iter(open(...))) ISTM this would be a powerful way of composing pipelined iterators and unifying treatment of sequences, as well as providing a logical place to add useful general sequence-applicable methods. Later you could talk about syntactic sugar for spelling e.g. iter(atuple).count(thing) more concisely. Maybe a double attribute dot (for sequence mnemonic)? E.g., obj.. <=> iter(obj) so atuple..count(thing) would be sugar for __builtins__.iter(atuple).count(thing) (I added __builtins__ to let you be perverse and define a local iter for use as iter(atuple).surprising(thing) also if you wanted to). But sugar aside, I think it would be nice just to have a subclassable iter type with good base methods. But (perhaps ;-) the main point here is not my latest OTTOMH idea/BF. The point is to illustrate that there may be unexplored avenues available to satify those who say, "But a tuple is a sequence a lot like list, so why don't they have the same handy sequence methods?" Which means that I suspect there is something like premature NIH-idea-xenophobic rejection going on sometimes, where imagination might be more helpful and a way could be found to make a concept fit satisfyingly in a place not immediately recognized. IOW, I generally like orthogonality, so I sympathize with the desire to have .count available easily for any sequence, including tuples. But I don't think that means that all iterable objects should _themselves_ have all list methods etc. Another idea would be to tag names with '!' to indicate that a name space "path" should be searched before or after normal name search. So e.g. if there were a __nspath__ visible, e.g. like __nspath__ == [__builtins__.__dict__, dict(index=lambda obj, el:list(obj).index(el))] then atuple.!index(42) would mean something like (untested ;-) (d['index'] for d in __nspath__ if 'index' in d).next().__get__(atuple, type(atuple))(42) this could also be written as atuple.index!(42) which would mean if atuple had and index method, that would immediately satisfy the search, but the search would continue at the '!' point if not. The default nspath could be in __builtins__ optimized unless a module gets a global __nspath__ at import time. But that's premature optimization ;-) Hm, that means that obj.!method produces a bound method with a function dynamically borrowed potentially from anywhere ;-) Hm2, should it be an error if there's no __get__, or should that be a mechanism for supplycing a default attribute value through an extended (by __nspath__) search? Should I have started a new thread for this kind of idea musing? ;-) >>But the problem is that the tutorials and manuals give the impression >>that the difference between lists and tuples is only mutablity versus >>immutability. They don't talk about such considerations and honestly >>speaking even now I know that it does seem more plausible for me. > >Then feel free to submit patches for the docs. This is easy to say, and maybe the docs maintainers are accomodating, but I'd be the average reader wouldn't have a concept of how a "patch" should be prepared. I know the info is not far away in the python.org site but still, is there an interface that will bring up a doc page in a browser and let you select e.g. a paragraph and pop up a form for a before/after rewrite proposal (maybe with integrated preview, a la slashdot submissions)? That's wiki-like, but I'm thinking a tailored utility. Given reasonably structured doc sources, I wouldn't think it would be too bad a project. Not that I'm volunteering to write that particular thing ;-) Regards, Bengt Richter From fredrik at pythonware.com Wed Nov 9 04:53:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 10:53:52 +0100 Subject: not able to HTTPS page from python References: <1131527678.640177.118930@g43g2000cwa.googlegroups.com> Message-ID: wrote: > AM NOT GETTING ANY ERRORS EITHER BUT ITS NOT READING THE LINKS, THAT > ARE PRESENT IN THE GIVEN HTTPS PAGE HAVE YOU TRIED ADDING A PRINT STATEMENT TO THE FEED LOOP SO YOU CAN SEE WHAT YOU'RE GETTING BACK FROM THE SERVER ? From peter at engcorp.com Sun Nov 20 09:27:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Nov 2005 09:27:28 -0500 Subject: Underscores in Python numbers In-Reply-To: <1132476670.992305.106250@o13g2000cwo.googlegroups.com> References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> <1132476670.992305.106250@o13g2000cwo.googlegroups.com> Message-ID: Dan Bishop wrote: > Roy Smith wrote: >>creditCardNumber = myInt ("1234 5678 9012 3456 789") > > Or alternatively, you could write: > > creditCardNumber = int('1234''5678''9012''3456''789') Or creditCardNumber = int("1234 5678 9012 3456 789".replace(' ','')) Or make a little function that does the same job and looks cleaner, if you need this more than once. But why would anyone want to create numeric literals for credit card numbers? -Peter From __peter__ at web.de Wed Nov 23 13:09:33 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Nov 2005 19:09:33 +0100 Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <1132708265.941224.186550@g44g2000cwa.googlegroups.com> Message-ID: David Isaac wrote: > def ireduce(func, iterable, init=None): > if init is None: > iterable = iter(iterable) > init = iterable.next() > yield init > elif not iterable: You are in for a surprise here: >>> def empty(): ... for item in []: ... yield item ... >>> bool(empty()) True >>> bool(iter([])) True # python 2.3 and probably 2.5 >>> bool(iter([])) False # python 2.4 > yield init > for item in iterable: > init = func(init, item) > yield init Peter From fredrik at pythonware.com Fri Nov 25 03:12:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Nov 2005 09:12:02 +0100 Subject: defining the behavior of zip(it, it) (WAS: Converting a flatlist...) References: <1132778601.776080.80100@g44g2000cwa.googlegroups.com> <1132862512.146221.33970@g44g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Now, see, that's the thing. The more ways there are to write the same > program, the harder any given program will be to understand. > > This is indeed a fairly deliberate approach in the Python world, and > contrasts with languages where readability is low because of the > multiple different ways of expressing the same idea. you can express ideas in many ways in Python (just witness all the web frameworks and xml toolkits ;-). the deliberate approach you're referring to is more about using a consistent spelling. seriously, if anyone has a job so boring that his only way to express his creativity is to be able call a trivial library operation in many different ways somewhere deep inside his program, his problems are a lot more fundamental than the choice of programming language. (in a way, this is related to what creative programmers sometimes refer to as python's "pencil-like qualities"; the fact that once you've grokked python's way to do things, the language pretty much disappears from sight. *your* ideas is what matters. see e.g. the venners interview with bruce eckel: http://www.artima.com/intv/aboutme.html http://www.artima.com/intv/prodperf.html http://www.artima.com/intv/typing.html http://www.artima.com/intv/tipping.html for more on this. here's the keynote they're referring to, btw: http://www.mindview.net/FAQ/FAQ-012 From sjdevnull at yahoo.com Mon Nov 21 17:03:18 2005 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 21 Nov 2005 14:03:18 -0800 Subject: running functions In-Reply-To: References: <1132179612.759373.130900@g43g2000cwa.googlegroups.com> <437d2a78@nntp0.pdx.net> Message-ID: <1132607698.565665.104720@o13g2000cwo.googlegroups.com> Tom Anderson wrote: > > If you program threads with shared nothing and communication over Queues > > you are, in effect, using processes. If all you share is read-only > > memory, similarly, you are doing "easy" stuff and can get away with it. > > In all other cases you need to know things like "which operations are > > indivisible" and "what happens if I read part of this from before an > > update and the other after the update completes, ..... > > Right, but you have exactly the same problem with separate processes - > except that with processes, having that richness of interaction is so > hard, that you'll probably never do it in the first place! It's not all that hard, but you do have to think about it and really engineer your communications (and SHM segments) ahead of time. Which is a good thing, IMO. Really the only difference between threads and processes is that threads share all your memory. When you consider that OS designers spent a lot of time and effort to implement protected memory, maybe that's not often the right thing. Certainly threads have their place, but I avoid them whenever there's an equally easy multiprocess solution (which is the overwhelming majority of the time, but certainly not always). To diverge from the Python world for a moment, imagine a network server that services each connection with a thread (possibly from a thread pool rather than creating a new one for each connection). And imagine another that uses multiple process. Now suppose there's a bug in some extension that segfaults (for instance, when serving large media files). It's very easy for such a bug to bring down the whole server in the multithreaded server; in the multiprocess server it naturally brings down only the one connection, so the rest of the site continues to run happily. Many other stability and security holes are easy to introduce when you eliminate memory protection. I don't really understand the "process are really hard" thing, either. It's a 5 line wrapper or so to make it look just like the threads interface if you really want to, and you only have to do that once. You do need to worry about IPC, but that is generally simpler than just mucking about in process-wide memory, especially when it comes to maintenance. But... > I've done a fair amount of threads programming, although in java rather > than python (and i doubt very much that it's less friendly in python than > java!), and i found it really fairly straightforward. Java certainly doesn't have any real support for multiprocess programming. I view the lack of good multiprocess solutions in Java to be one of the few major design flaws therein. Indeed, I view the poor performance of processes on Windows (and the accompanying need to use threads for reasons other than memory sharing) to be the biggest single problem with Windows. From onurb at xiludom.gro Fri Nov 11 05:25:03 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 11 Nov 2005 11:25:03 +0100 Subject: Command-line tool able to take multiple commands at one time? In-Reply-To: References: Message-ID: <43747181$0$19231$626a54ce@news.free.fr> Peter A. Schott wrote: > Per subject - I realize I can copy/paste a line at a time into an interactive > session when I'm trying to debug, but was wondering if there is any tool out > there that allows me to copy sections of working Python scripts to paste into my > interactive console and let those run so I don't have to copy line-by-line. There's much better than that : emacs + python-mode let you evaluate either the whole script, a single class or def statement, or an arbitrary region in an interactive Python interpreter running as an emacs sub-process. Of course, this interpreter don't die after, so you can inspect/play with/do whatever with the results of this evaluation. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From erniedude at gmail.com Wed Nov 16 16:04:28 2005 From: erniedude at gmail.com (Ernesto) Date: 16 Nov 2005 13:04:28 -0800 Subject: subprocess terminate help Message-ID: <1132175068.069738.299430@o13g2000cwo.googlegroups.com> def launchWithoutConsole(command, args): """Launches 'command' windowless and waits until finished""" startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return subprocess.Popen([command] + args, startupinfo=startupinfo).wait() handle = launchWithoutConsole("program.exe",["disconnect"]) ------------------------------------------------------------------------------------------------------------------------------ I've been searching for ways to terminate this process so I can exit my program. program.exe is a text based interface which I'm running with python subprocess in a DOS command window. I tried using 'sys.exit()' to end my program, but nothing works. I think I have to somehow terminate the subprocesses I create. Any suggestions? From peter at engcorp.com Sat Nov 19 13:19:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Nov 2005 13:19:59 -0500 Subject: Can a function access its own name? In-Reply-To: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> References: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> Message-ID: bobueland at yahoo.com wrote: [edited slightly] > def cap(): > print "the name of this function is " + "???" > cap () sys._getframe() would help you here: >>> import sys >>> sys._getframe() >>> def f(): ... global x ... x = sys._getframe() ... >>> f() >>> x >>> dir(x) [..., 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', ...] >>> dir(x.f_code) [...'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames'] >>> x.f_code.co_name 'f' So your function could be: >>> import sys >>> def cap(): ... print 'function name is', sys._getframe().f_code.co_name ... >>> cap() function name is cap -Peter From xray_alpha_charlie at yahoo.com Sun Nov 6 16:00:29 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Sun, 6 Nov 2005 13:00:29 -0800 (PST) Subject: "how to think like a computer scientist" Message-ID: <20051106210029.79381.qmail@web35914.mail.mud.yahoo.com> I am using the book "how to think like a computer scientist" and am finding the examples are not working with Python 2.4.2...I have typed them exactly as they appear in the text....can someone relate to this?...is this typical b/c 2.4.2 is a newer version? -xray- --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From WYWAL_TOmich202 at o2.pl Tue Nov 8 06:12:22 2005 From: WYWAL_TOmich202 at o2.pl (mo) Date: Tue, 8 Nov 2005 12:12:22 +0100 Subject: how to stop a loop with ESC key? [newbie] References: Message-ID: "Fredrik Lundh" wrote: > works for me, when running it from a stock CPython interpreter in a windows > console window, with focus set to that window. > what environment are you using? I use IDLE 1.0.3, Python 2.3.4 The same problem is when running in a win console. mo From free.condiments at gmail.com Sat Nov 12 19:29:21 2005 From: free.condiments at gmail.com (Sam Pointon) Date: 12 Nov 2005 16:29:21 -0800 Subject: Multikey Dict? In-Reply-To: <437682b5$0$2108$edfadb0f@dtext02.news.tele.dk> References: <437682b5$0$2108$edfadb0f@dtext02.news.tele.dk> Message-ID: <1131841761.745972.249830@o13g2000cwo.googlegroups.com> > If I could just say to Python: john and graham (and ...) are all a part > of a "superdict" and either their id or their name can be used as keys. > Can I do that somehow? Sure you can. There are two obvious ways to do this - enlist the aid of a Superdict (or similar) class to take care of the details. A simple implementation would be: class Superdict(object): def __init__(self, by_id, by_name): self.by_id = by_id self.by_name = by_name def __getitem__(self, value): if value.isdigit(): return self.by_id[value] else: return self.by_name[value] The alternative is to use some sort of database for storing these values. It doesn't really matter which (hell, you could even reinvent a relational wheel pretty simply in Python), as any DB worth its salt will do exactly what you need. Hope that helps, -Sam From princismo at yahoo.com.tw Tue Nov 8 04:28:35 2005 From: princismo at yahoo.com.tw (Hako) Date: 8 Nov 2005 01:28:35 -0800 Subject: How to convert a number to hex number? Message-ID: <1131442115.025438.326670@g49g2000cwa.googlegroups.com> I try this command: >>> import string >>> string.atoi('78',16) 120 this is 120 not 4E. Someone can tell me how to convert a decimal number to hex number? Can print A, B, C,DEF. Thank you. From mde at micah.elliott.name Tue Nov 29 15:02:04 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Tue, 29 Nov 2005 12:02:04 -0800 Subject: newbie question concerning formatted output In-Reply-To: References: Message-ID: <20051129200204.GA4032@kitchen.client.attbi.com> On Nov 29, Fredrik Lundh wrote: > inp = open("xyplan.nobreaks","r") > data = inp.read() > > import textwrap > for line in textwrap.wrap(data, 15): > print line Right -- if the data is that regular then every 15th item is the split-point. A variation on this theme then is: for i in range(0, len(data), 15): print data[i:i+15] -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From qwweeeit at yahoo.it Wed Nov 2 16:22:16 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 2 Nov 2005 13:22:16 -0800 Subject: Web automation with twill References: <1130934838.388039.297650@o13g2000cwo.googlegroups.com> <1130945598.627911.264390@g49g2000cwa.googlegroups.com> Message-ID: <1130966536.697459.250700@g49g2000cwa.googlegroups.com> I solved the problem by myself with the classical method of newbyes (trial and error). Bye. From peter at engcorp.com Mon Nov 21 15:47:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Nov 2005 15:47:46 -0500 Subject: Numeric array in unittest problem In-Reply-To: <1132586037.388588.323670@g44g2000cwa.googlegroups.com> References: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> <1132586037.388588.323670@g44g2000cwa.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > Sorry Peter, > Try this.... > > import unittest > import Numeric > > class myTest(unittest.TestCase): > def runTest(self): > var1 = Numeric.array([1,22]) > var2 = Numeric.array([1,33]) > self.assertEqual(var1,var2) > > if __name__ == '__main__': > unittest.main() My apologies, as I thought I was pointing out an obvious error, but it turns out I was totally wrong about it. My own use of module unittest has always involved defining methods whose names start with "test", as in "def test01(self):" and "def test_this(self):" and so forth. I had no idea that there was a method runTest() that you could override, so I was trying to point out that the test case wasn't even executing -- though clearly it was! (Try defining even a single method starting with "test" in addition to the runTest() method you have above, and you'll see that runTest() stops executing... but obviously this isn't your problem.) -Peter From nyamatongwe+thunder at gmail.com Wed Nov 16 17:53:41 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 16 Nov 2005 22:53:41 GMT Subject: path module / class In-Reply-To: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> References: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> Message-ID: Chris: > What is the status of the path module/class PEP? Did somebody start > writing one, or did it die? I would really like to see something like > Jason Orendorff's path class make its way into the python standard > library. There is no PEP yet but there is a wiki page. http://wiki.python.org/moin/PathClass Guido was unenthusiastic so a good step would be to produce some compelling examples. Neil From apardon at forel.vub.ac.be Fri Nov 4 07:10:11 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 12:10:11 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Op 2005-11-04, Steven D'Aprano schreef : > On Fri, 04 Nov 2005 07:31:46 +0000, Antoon Pardon wrote: > >>> The model makes sense in my opinion. If you don't like it then there are >>> plenty of other languages to choose from that have decided to implement >>> things differently. >> >> And again this argument. Like it or leave it, as if one can't in general >> like the language, without being blind for a number of shortcomings. >> >> It is this kind of recations that make me think a number of people is >> blindly devoted to the language to the point that any criticism of >> the language becomes intollerable. > > There are good usage cases for the current inheritance behaviour. I asked > before what usage case or cases you have for your desired behaviour, and > you haven't answered. Perhaps you missed the question? Perhaps you haven't > had a chance to reply yet? Or perhaps you have no usage case for the > behaviour you want. There are good use cases for a lot of things python doesn't provide. There are good use cases for writable closures, but python doesn't provide it, shrug, I can live with that. Use cases is a red herring here. > Some things are a matter of taste: should CPython prefer <> or != for not > equal? Some things are a matter of objective fact: should CPython use a > byte-code compiler and virtual machine, or a 1970s style interpreter that > interprets the source code directly? > > The behaviour you are calling "insane" is partly a matter of taste, but it > is mostly a matter of objective fact. I believe that the standard > model for inheritance that you call insane is rational because it is > useful in far more potential and actual pieces of code than the behaviour > you prefer -- and the designers of (almost?) all OO languages seem to > agree with me. I didn't call the model for inheritance insane. > The standard behaviour makes it easy for code to do the right thing in > more cases, without the developer taking any special steps, and in the > few cases where it doesn't do the right thing (e.g. when the behaviour you > want is for all instances to share state) it is easy to work around. By > contrast, the behaviour you want seems to be of very limited usefulness, > and it makes it difficult to do the expected thing in almost all cases, > and work-arounds are complex and easy to get wrong. Please don't make this about what I *want*. I don't want anything. I just noted that one and the same reference can be processed multiple times by the python machinery, resulting in that same reference referencing differnt variables at the same time and stated that that was unsane behaviour. > The standard behaviour makes it easy for objects to inherit state, and > easy for them to over-ride defaults. The behaviour(s) you and Graham want > have awkward side-effects: your proposed behaviour would mean that class > attributes would mask instance attributes, or vice versa, meaning that > the programmer would have to jump through hoops to get common types of > behaviour like inheriting state. You don't know what I want. You only know that I have my criticism of particular behaviour. You seem to have your idea about what the alternative would be like, and project that to what I would want. > The behaviour you want would make it too easy to inadvertently have > instances share state. Normally we want instances to share behaviour but > have unique states -- you would change that. Why? If it is just a matter > of taste, you are welcome to your opinion. But you don't say that the > standard behaviour is "ugly", you say it is "insane", that is, irrational, > and that the behaviour you want is rational. I called it unsane, not insane. I think I paid enough attention to never use the word "insane", yes I once used "madness" but that was after you were already all over me for this. Even should I have used the word insane, I used it for a lot less than you are implying. > That's an objective claim: please explain what makes your behaviour more > rational than the standard behaviour. Is your behaviour more useful? Does > it make code easier to write? Does it result in more compact code? What > usage cases? What my behaviour? I don't need to specify alternative behaviour in order to judge specific behaviour. -- Antoon Pardon From bonono at gmail.com Tue Nov 22 18:03:29 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 15:03:29 -0800 Subject: about sort and dictionary In-Reply-To: References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> Message-ID: <1132700609.023186.150360@z14g2000cwz.googlegroups.com> Steven D'Aprano wrote: > There are four possibilities for a construction like list.sort(): > > (1) sort the list in place and return a reference to the same list; > (2) sort the list in place and return a copy of the same list; > (3) sort the list in place and return None; > (4) don't sort in place and return a sorted list. > > No solution is always right, no solution is always wrong, but the most > flexible is a combination of (3) and (4). Python now has that with sort() > and sorted(). Prior to the addition of sorted() to the language, (3) was > considered the best solution because of a simple Python principle: never > duplicate objects unless explicitly told to. > I don't see the reason that (3) and (4) are the most flexible. Again, "never duplicate objects unless explicitly told to" combined with "=" is name binding gives me a very strong message that list.sort() it will change things in place and which is why it is quite natural(for me at least) 3 2 1 1 2 3 for this language. Wether it is "best" or make more sense doesn't really matter to me, though I am curious to know why. But basically, I just use the language as it is, and the way I want to. So long it solves my problem and gives me the result I want. From deets at nospam.web.de Wed Nov 23 17:40:20 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Nov 2005 23:40:20 +0100 Subject: newbie class question In-Reply-To: <1132784286.143394.15740@f14g2000cwb.googlegroups.com> References: <1132783589.533488.51460@g44g2000cwa.googlegroups.com> <1132784286.143394.15740@f14g2000cwb.googlegroups.com> Message-ID: <3uk9elF11bb91U1@uni-berlin.de> >>What I am trying to accomplish should be pretty self explanatory when >>looking at the following: It seems to me that what you are after is a nested or inner class like in JAVA. You can't do that in the same way as in JAVA, as nested classes in python don't know about their surrounding class/context. So, to accomplish what you want, you need e.g. this recipe from aspn: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231520 Regards, Diez From cito at online.de Mon Nov 28 18:55:52 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 29 Nov 2005 00:55:52 +0100 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > there should be comma after "ist", Sorry, *before* "ist". I should probably stop posting for today... -- Christoph From onurb at xiludom.gro Thu Nov 3 04:14:23 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 03 Nov 2005 10:14:23 +0100 Subject: when and how do you use Self? In-Reply-To: References: Message-ID: <4369d4f0$0$18073$626a14ce@news.free.fr> Tieche Bruce A MSgt USMTM/AFD wrote: > I am new to python, > > > > Could someone explain (in English) how and when to use self? > Don't use self. Use other. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From petr at tpc.cz Sat Nov 12 12:32:23 2005 From: petr at tpc.cz (Petr Jakes) Date: 12 Nov 2005 09:32:23 -0800 Subject: convert string to the "escaped string" In-Reply-To: References: <1131804252.578525.312490@g43g2000cwa.googlegroups.com> Message-ID: <1131816743.249725.55490@o13g2000cwo.googlegroups.com> Fredrik, thanks for your posting. I really appretiate your reply and your way how you kindly answer even stupid newbie's questions on this mailing list. I was trying: int("0xf") but I did not have idea about the optional "base" parameter for the int function. Thanks a lot. Petr From roy at panix.com Tue Nov 29 16:02:38 2005 From: roy at panix.com (Roy Smith) Date: 29 Nov 2005 16:02:38 -0500 Subject: Looking for good beginner's tutorial Message-ID: My wife wants to learn Python. Can anybody suggest a good tutorial for her to read? She's a PhD molecular biologist who is a pretty advanced Unix user. She mucks about with Perl scripts doing things like text processing and even some simple CGI scripts, but has no formal programming training. I looked at Dive Into Python, but it's going to be way over her head. I didn't think the tutorial on www.python.org would do it for her either. Any other suggestions I might look at? From aleax at mail.comcast.net Wed Nov 9 22:53:21 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 9 Nov 2005 19:53:21 -0800 Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594460.098689.64140@g43g2000cwa.googlegroups.com> Message-ID: <1h5rz3b.1mpfn381yc51d9N%aleax@mail.comcast.net> George Sakkis wrote: ... > > > FP functions like dropwhile/takewhile etc. > > > > No way -- the itertools module is and remains a PRECIOUS resource. > > If you want an iterator rather than a list, itertools.ifilter is quite > > appropriate here. > > What about the future of itertools in python 3K ? IIRC, several > functions and methods that currently return lists are going to return > iterators. Could this imply that itertools.(imap/ifilter/izip) will > take the place of map/filter/zip as builtins ? I think the builtin namespace shouldn't get too crowded. But what I think matters little -- what __GvR__ thinks is more important...!-) Alex From bokr at oz.net Wed Nov 23 07:12:02 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 23 Nov 2005 12:12:02 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <43837bf7.485835644@news.oz.net> Message-ID: <43845a44.542744996@news.oz.net> On Wed, 23 Nov 2005 09:54:46 +0100, "Fredrik Lundh" wrote: >Bengt Richter wrote: > >> >Though it looks nice, it's an implementation dependant solution. What if >> >someone changes zip to fetch the second item first? >> >> That would be a counter-intuitive thing to do. Most things go left->right >> in order as the default assumption. > >it's not only the order that matters, but also the number of items >read from the source iterators on each iteration. > Not sure I understand. Are you thinking of something like lines from a file, where there might be chunky buffering? ISTM that wouldn't matter if the same next method was called. Here we have multiple references to the same iterator. Isn't e.g. buiding a plain tuple defined with evaluation one element at a time left to right? So an iterator it = xrange(4) can't know that it's being used in a context like (it.next(), it.next()), so why should zip be any different? Zip _is_ building tuples after all, and it's perfectly clear where they are coming from (or am I missing something?) Why not left to right like a normal tuple? Regards, Bengt Richter From duncan.booth at invalid.invalid Thu Nov 17 03:55:33 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Nov 2005 08:55:33 GMT Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1h62slm.up4s2tqyk1gjN%aleax@mail.comcast.net> <437C36EA.8010600@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > What should I do when I can't rely on functions that > don't exist in older versions of Python? > Ideally: if 'iter' not in dir(__builtins__): import sys sys.exit('Archaic Python not supported, please upgrade') Alternatively fill in the blanks with appropriate fallback code: if 'iter' not in dir(__builtins__): def iter(obj): ... remainder of definition left as an exercise ... __builtins__.iter = iter where iter does roughly what the iter builtin does. From finite.automaton at gmail.com Fri Nov 4 20:02:22 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 4 Nov 2005 17:02:22 -0800 Subject: C extension + libm oddity [fmod(2.0, 2.0) == nan ?!] Message-ID: <1131152542.351552.255140@g44g2000cwa.googlegroups.com> I've been trying to debug this for two days now, and it's a longshot but I'm hoping that someone here might recognize a solution. I've got a C extension which calls a function in a C library, which calls another function in another library, which calls another function, which calls fmod from the standard C math library. All of these are shared libraries on Linux (x86 Gentoo 2.6.9). In other words, the calling looks like this: Python -> Python C extension -> Function from library 1 -> Function from library 2 -> fmod from libm.so The critical line of C code looks like this: ans = fmod ( x, 2.0 ); .. where x is a double with value 2.0 (confirmed by gdb) and ans is a double. Now, fmod(2.0, 2.0) should be 0.0. The problem? ans is getting assigned nan! I have stepped through it in the debugger now dozens of times. Either fmod is putting the wrong return value on the stack, or the stack is getting corrupted by something else and "ans" is getting assigned the wrong value. This happens only inside of the layered Python extension mess; if I try to compile a test C program that makes similar calls to fmod, they work just fine. Likewise, a very simple Python wrapper around fmod also works (e.g. Python -> Python C extension -> fmod) This all runs in a single thread, so it doesn't seem like it would be a threading issue unless Python is making some threads under the hood. All of the intermediary libraries were compiled with (-g -fPIC), no optimization. The intermediary libraries represent thousands of lines of very old code. It is very possible that all sorts of memory leaks and other subtle bugs exist, but what kind of memory leak could even cause this kind of glitch!? How can I even approach debugging it? My next step right now is going to be stepping through the individual instructions... arrrrrrrrrrrrrgggh. Versions: Python 2.4.1, gcc 3.3.6, glibc 2.3.5, Gentoo Linux 2.6.9. From steve at REMOVETHIScyber.com.au Fri Nov 4 22:37:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 14:37:19 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <436bdc05.135552474@news.oz.net> Message-ID: On Sat, 05 Nov 2005 00:25:34 +0000, Bengt Richter wrote: > On Fri, 04 Nov 2005 02:59:35 +1100, Steven D'Aprano wrote: > >>On Thu, 03 Nov 2005 14:13:13 +0000, Antoon Pardon wrote: >> >>> Fine, we have the code: >>> >>> b.a += 2 >>> >>> We found the class variable, because there is no instance variable, >>> then why is the class variable not incremented by two now? > Because the class variable doesn't define a self-mutating __iadd__ > (which is because it's an immutable int, of course). If you want > b.__dict__['a'] += 2 or b.__class__.__dict__['a'] += 2 you can > always write it that way ;-) > > (Of course, you can use a descriptor to define pretty much whatever semantics > you want, when it comes to attributes). > >> >>Because b.a += 2 expands to b.a = b.a + 2. Why would you want b.a = > > No, it doesn't expand like that. (Although, BTW, a custom import could > make it so by transforming the AST before compiling it ;-) > > Note BINARY_ADD is not INPLACE_ADD: Think about *what* b.a += 2 does, not *how* it does it. Perhaps for some other data type it would make a difference whether the mechanism was BINARY_ADD (__add__) or INPLACE_ADD (__iadd__), but in this case it does not. Both of them do the same thing. Actually, no "perhaps" about it -- we've already discussed the case of lists. Sometimes implementation makes a difference. I assume BINARY_ADD and INPLACE_ADD work significantly differently for lists, because their results are significantly (but subtly) different: py> L = [1,2,3]; id(L) -151501076 py> L += [4,5]; id(L) -151501076 py> L = L + []; id(L) -151501428 But all of this is irrelevant to the discussion about binding b.a differently on the left and right sides of the equals sign. We have discussed that the behaviour is different with mutable objects, because they are mutable -- if I recall correctly, I was the first one in this thread to bring up the different behaviour when you append to a list rather than reassign, that is, modify the class attribute in place. I'll admit that my choice of terminology was not the best, but it wasn't misleading. b.a += 2 can not modify ints in place, and so the effect of b.a += 2 is the same as b.a = b.a + 2, regardless of what byte-codes are used, or even what C code eventually implements that add-and-store. In the case of lists, setting Class.a = [] and then calling instance.a += [1] would not exhibit the behaviour Antoon does not like, because the addition is done in place. But calling instance.a = instance.a + [1] would. My question still stands: why would you want instance.a = to operate as instance.__class__.a = ? -- Steven. From jmdeschamps at gmail.com Sun Nov 6 21:11:08 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 6 Nov 2005 18:11:08 -0800 Subject: text widget example? In-Reply-To: <1131323136.640414.143030@f14g2000cwb.googlegroups.com> References: <1131323136.640414.143030@f14g2000cwb.googlegroups.com> Message-ID: <1131329468.631825.165230@g44g2000cwa.googlegroups.com> Well, in the 'give me a free example' type questions, I guess I'm a bit blue tonight, so here goes: ( no personal pun intended, just look up some recent post in this newsgroup...) # Start the example Python code to show some text file in a text widget from Tkinter import * # import Tkinter in __main__ namespace root = Tk() # initialize Tkinter myTextWidget= Text(root) # set up a text widget as a root (window) child myFile=file("myTextFile.txt") # get a file handle myText= myFile.read() # read the file to variable myFile.close() # close file handle myTextWidget.insert(0.0,myText) # insert the file's text into the text widget myTextWidget.pack(expand=1, fill=BOTH) # show the widget root.mainloop() #run the events mainloop # End the example here You need a text file *myTextFile.txt* in your current working directory for this to work. Read-up on the different objects and properties for detail. Good luck! BTW, now that this is posted, I guess one could say that it's an example on the Internet From martin at v.loewis.de Fri Nov 25 17:41:59 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 25 Nov 2005 23:41:59 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <86br09wsos.fsf@bhuda.mired.org> References: <43850a7a$0$8074$9b622d9e@news.freenet.de> <868xvex8d6.fsf@bhuda.mired.org> <86veyhx5fb.fsf@bhuda.mired.org> <43864076.8050603@v.loewis.de> <86br09wsos.fsf@bhuda.mired.org> Message-ID: <43879337.3060508@v.loewis.de> Mike Meyer wrote: > I would have phrased it as "identical" instead of equal. Sets should > hold unique elements, where "unique" depends on the use at hand. For > some uses, "==" might be appropriate. For others, "is" might be > appropriate. Sets, as currently defined, require hashable objects, i.e. objects which has same all the time and hash same as all other equal objects. Phrasing it as "identical" would be incorrect: hashes currently operate on equality, not identity. > Would you care to suggest an improved wording? No - I have learned that I cannot write documentation that others can understand. I usually write documentation which only attempts to be correct, and others than make it understandable. Regards, Martin From kylotan at gmail.com Tue Nov 15 06:06:31 2005 From: kylotan at gmail.com (Ben Sizer) Date: 15 Nov 2005 03:06:31 -0800 Subject: Python obfuscation In-Reply-To: <867jbbrowx.fsf@bhuda.mired.org> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> Message-ID: <1132052791.374452.206310@g49g2000cwa.googlegroups.com> Mike Meyer wrote: > "Ben Sizer" writes: > > Decompyle (http://www.crazy-compilers.com/decompyle/ ) claims to be > > pretty advanced. I don't know if you can download it any more to test > > this claim though. > > No, it doesn't claim to be advanced. It claims to be good at what it > does. There's no comparison with other decompilers at all. In > particular, this doesn't give you any idea whether or not similar > products exist for x86 or 68k binaries. That's irrelevant. We don't require a citable source to prove the simple fact that x86 binaries do not by default contain symbol names whereas Python .pyc and .pyo files do contain them. So any decompilation of (for example) C++ code is going to lose all the readable qualities, as well as missing any symbolic constants, enumerations, templated classes and functions, macros, #includes, inlined functions, typedefs, some distinctions between array indexing and pointer arithmetic, which inner scope a simple data variable is declared in, distinctions between functions/member functions declared as not 'thiscall'/static member functions, const declarations, etc. > I've dealt with some very powerfull disassemblers and > decompilers, but none of them worked on modern architectures. You can definitely extract something useful from them, but without symbol names you're going to have to be working with a good debugger and a decent knowledge of how to use it if you want to find anything specific. Whereas Python could give you something pretty obvious such as: 6 LOAD_FAST 0 (licensed) 9 JUMP_IF_FALSE 9 (to 21) > > It makes a lot of difference when you're hunting around for something > > or trying to understand a bit of code. Python bytecode (or at least, > > the output from dis) is also a lot more straightforward than x86 or 68K > > assembly to decipher. > > I'm not convinced of the former. I'll grant you half of the > latter. 68K machine language is fairly straightforward. On the other > hand, it's also seems to be irrelevant. What platform are you > developing for that's still based on the 68K? There are several embedded/portable devices based on 68K derivatives. That's not really the point though. I chose 68K assembly as an example as it's considered to be simpler than x86 assembly, yet it's still significantly more complex and less readable than the output from dis.dis() > > The term I should > > probably have used was 'distribute usable additional copies'. > > My question still stands, though - and unanswered. I'm not really sure where we're going here. I have made the point that I am not obliged to make my software copyable to facilitate your right to copy it any more than any given newspaper is obliged to publish you to facilitate your right to free speech. Therefore I find it hard to see how anything is infringing upon a right here. My interest lies in being able to use encrypted data (where 'data' can also include parts of the code) so that the data can only be read by my Python program, and specifically by a single instance of that program. You would be able to make a backup copy (or 20), you could give the whole lot to someone else, etc etc. I would just like to make it so that you can't stick the data file on Bittorrent and have the entire world playing with data that was only purchased once. > But we can be > explicit if you want: How do you do that without requiring that your > software be given special consideration in the distaster recovery and > preparedness planning? I should state that I am not at all claiming a "one size fits all" policy for software development. Firstly, from a personal point of view I am talking about simple consumer entertainment software which is not mission critical or anything like it. For more important software, there will surely be different expectations and requirements. In my case, providing a free download of any lost executables or data upon presentation of a legitimate license key should be adequate. -- Ben Sizer. From vinjvinj at gmail.com Mon Nov 7 22:53:49 2005 From: vinjvinj at gmail.com (vinjvinj) Date: 7 Nov 2005 19:53:49 -0800 Subject: Using python for writing models: How to run models in restricted python mode? In-Reply-To: References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> <1131401624.263258.185730@z14g2000cwz.googlegroups.com> <43700DDB.3020009@REMOVEMEcyber.com.au> <7x4q6nvogt.fsf@ruckus.brouhaha.com> <1131418706.748711.296820@g43g2000cwa.googlegroups.com> Message-ID: <1131422029.740753.144460@o13g2000cwo.googlegroups.com> No. I was hoping to leverage the work done for restricted pythonscript by zope at: http://www.zope.org/Control_Panel/Products/PythonScripts/Help/PythonScript.py which is similar to what I want to do as well. vinjvinj From gh at ghaering.de Thu Nov 10 12:15:49 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 10 Nov 2005 18:15:49 +0100 Subject: python + ODBC + Oracle + MySQL - money In-Reply-To: <1131636986.824373.178720@g43g2000cwa.googlegroups.com> References: <1131631172.260603.201050@o13g2000cwo.googlegroups.com> <1131636986.824373.178720@g43g2000cwa.googlegroups.com> Message-ID: <43738045.8070807@ghaering.de> Grig Gheorghiu wrote: > In my testing, I need to connect to Oracle, SQL Server and DB2 on > various platforms. I have a base class with all the common code, and > derived classes for each specific database type using specific database > modules such as cxOracle, mxODBC and pyDB2. The derived classes are > pretty thin, containing only some syntax peculiarities for a given > database type. The code is clean and portable. So maybe you're lucky that all your database modules use the same access to query parameters. MySQLdb and cx_Oracle would be different in that MySQLdb has paramstyle = "format" and cx_Oracle has paramstyle = "qmark/named", i. e. to query a specific record of the person table you would use p_id = 4711 cur.execute("select firstname from person where person_id=%s", (p_id,)) using MySQLdb, and: cur.execute("select firstname from person where person_id=?", (p_id,)) using cx_Oracle. Now, probably a lot of people have written wrappers for DB-API modules that translate one paramstyle to the other. The most sensible solution is to translate the format/pyformat one to others. Often, one other solution is to use a higher-level database interface uses your database modules internally, but has the same consistent interface for the outside. In my recent evaluations, I liked PyDO2 for this (http://skunkweb.sourceforge.net/pydo2.html). Unlike SQLObject, it is able to use MySQL and Oracle now, though there is work underway to add Oracle support to SQLObject. OTOH, the advice to use MySQLdb and cx_Oracle directly is probably a good one, especially for a newcomer to Python. It's a good way to learn Python and learning the Python DB-API is a good idea if you want to do a database application in Python. You can use higher-level interfaces (or write them yourself) later on. And if this is serious work with business value, then just buying a mxODBC license and go on with the real problem is probably the most sensible solution. You can use the time saved for learning Python, then, which is perhaps more fun :-) Cheers, -- Gerhard From samrobertsmith at gmail.com Sun Nov 20 08:32:53 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 05:32:53 -0800 Subject: about sort and dictionary Message-ID: <1d987df30511200532xf717e4ha480dfd82fe2248f@mail.gmail.com> Got confused by the following code: >>> a [6, 3, 1] >>> b [4, 3, 1] >>> c {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]} >>> c[2].append(b.sort()) >>> c {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]} #why c can not append the sorted b?? >>> b.sort() >>> b [1, 3, 4] From maxerickson at gmail.com Fri Nov 11 21:09:19 2005 From: maxerickson at gmail.com (Max Erickson) Date: Sat, 12 Nov 2005 02:09:19 +0000 (UTC) Subject: tutorial example References: <20051112015026.74881.qmail@web35903.mail.mud.yahoo.com> Message-ID: >>> import math >>> def distance1(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) print result return result >>> def distance2(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) print result They don't do the same thing here... >>> distance1(1,2,3,4) 2.82842712475 2.8284271247461903 >>> distance2(1,2,3,4) 2.82842712475 the 'return result' line passes the result object in the function back to where the function was called. Functions without a return statement default to returning 'None'. Calling the functions within a print statement illustrates the difference: >>> print distance1(1,2,3,4) 2.82842712475 2.82842712475 >>> print distance2(1,2,3,4) 2.82842712475 None >>> As you can see, distance2 does not actually return the result of the calculation to the interactive prompt... max From steve at REMOVETHIScyber.com.au Thu Nov 3 05:15:12 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 03 Nov 2005 21:15:12 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: On Thu, 03 Nov 2005 01:43:32 -0800, Graham wrote: [snip] > print instance_b.var # -> 5 > print _class.var # -> 5 > > > > Initially this seems to make sense, note the difference between to last > two lines, one is refering to the class variable 'var' via the class > while the other refers to it via an instance. That's not correct. The line instance_b.var is referring to an instance attribute. According to the usual Object Oriented model of inheritance, if the instance does not have an attribute, the class is searched next. So instance_b.var and _class.var are asking for two different things. The first says, "Search the instance for attribute var, then the class." The second says "Search the class." BTW, a leading underscore is the convention for a private(ish) variable. The convention for naming a variable after a reserved word is a trailing underscore class_. In this case, there is also the convention that classes should start with a capital, so you have Class and instance. (instance, of course, is not a reserved word.) > However if one attempts the following: > > > > instance_b.var = 1000 # -> _class.var = 5 > _class.var = 9999 # -> _class.var = 9999 > > > > An obvious error occurs. I see no error. No exception is raised when I try it: I get the expected results. Assigning to an instance assigns to the instance, assigning to the class assigns to the class. That's normal OO behaviour. > When attempting to assign the class variable > via the instance it instead creates a new entry in that instance's > __dict__ and gives it the value. You might *want* to assign to the class attribute, but that's not what you are doing. You are assigning to the instance. Admittedly, it might not be the behaviour you expect, but it is the standard behaviour in (as far as I know) all OO languages. If you want to assign to the class attribute, you either assign to the class directly, or use instance_b.__class__.var. > While this is allowed because of > pythons ability to dynamically add attributes to a instance however it > seems incorrect to have different behavior for different operations. Surely you can't mean that? Why would you want different operations to have the same behaviour? > There are two possible fixes, either by prohibiting instance variables > with the same name as class variables, which would allow any reference > to an instance of the class assign/read the value of the variable. Or > to only allow class variables to be accessed via the class name itself. There is also a third fix: understand Python's OO model, especially inheritance, so that normal behaviour no longer surprises you. -- Steven. From tim.golden at viacom-outdoor.co.uk Tue Nov 8 05:46:50 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 8 Nov 2005 10:46:50 -0000 Subject: Pywin32: How to import data into Excel? Message-ID: <9A28C052FF32734DACB0A288A3533991044D22FC@vogbs009.gb.vo.local> [Dmytro Lesnyak] > I need to import some big data into Excel from my > Python script. I have TXT file (~7,5 Mb). I'm using > Pywin32 library for that, but if I first try to read > the TXT file and then save the values one by one like > xlBook.Sheets(sheet_name).Cells(i,j).Value = value_from_TXT_file > it takes about 10 hours to process whole data A few suggestions: + When trying to automate anything in Excel, it's usually illuminating to record a macro which does what you want, and then to translate that VBA code into Python. + To find documentation on the Microsoft object models, MSDN is usually a good bet. Googling for: site:msdn.microsoft.com excel object model gives some hopeful-looking hits + I fiddled around for a few moments, and found that the following code at least worked: import win32com.client xl = win32com.client.gencache.EnsureDispatch ("Excel.Application") xl.Visible = 1 xl.Workbooks.OpenText ("c:/temp/temp.txt") + If you needed more control, bear in mind that you can put lists and lists of lists directly into an Excel range. So, something like this: import win32com.client a = [1, 2, 3] b = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] xl = win32com.client.gencache.EnsureDispatch ("Excel.Application") xl.Visible = 1 wb = xl.Workbooks.Add () ws = wb.ActiveSheet ws.Range (ws.Cells (1, 1), ws.Cells (1, 3)).Value = a ws.Range (ws.Cells (2, 1), ws.Cells (4, 3)).Value = b + Finally, you might look at PyExcelerator. I've toyed with it only a little, but it seems to do the business, and doesn't need Excel installed (so you can even run it on Linux, if that takes your fancy). It's had a very recent release, so it's definitely being maintained: http://sourceforge.net/projects/pyexcelerator/ TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From stefan.arentz at gmail.com Fri Nov 4 05:04:58 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 04 Nov 2005 11:04:58 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> Message-ID: <871x1wu3sl.fsf@keizer.soze.com> Antoon Pardon writes: > Op 2005-11-03, Mike Meyer schreef : > > Antoon Pardon writes: > >>> What would you expect to get if you wrote b.a = b.a + 2? > >> I would expect a result consistent with the fact that both times > >> b.a would refer to the same object. > > > > Except they *don't*. This happens in any language that resolves > > references at run time. > > Python doesn't resolve references at run time. If it did the following > should work. > > a = 1 > def f(): > a = a + 1 > > f() No that has nothing to do with resolving things at runtime. Your example does not work because the language is very specific about looking up global variables. Your programming error, not Python's shortcoming. S. From bearophileHUGS at lycos.com Sat Nov 19 13:01:22 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 Nov 2005 10:01:22 -0800 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: <1132423282.380661.170740@f14g2000cwb.googlegroups.com> Roy Smith>We already have a perfectly good syntax for entering octal and hex integers, There is this syntax: 1536 == int("600", 16) that accepts strings only, up to a base of 36. There are the hex() and oct() functions. There is the %x and %o sintax, that isn't easy to remember. There are the 0x600 and 0600 syntaxes that probably look good only from the point of view of a C programmer. I think some cleaning up, with a simpler and more consistent and general way of converting bases, can be positive. But probably no one shares this point of view, and compatibility with C syntax is probably positive, so you are right. I am still learning the correct way of thinking in python. Bye, bearophile From cito at online.de Thu Nov 24 15:13:57 2005 From: cito at online.de (Christoph Zwerschke) Date: Thu, 24 Nov 2005 21:13:57 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <86veyhx5fb.fsf@bhuda.mired.org> References: <43850a7a$0$8074$9b622d9e@news.freenet.de> <868xvex8d6.fsf@bhuda.mired.org> <86veyhx5fb.fsf@bhuda.mired.org> Message-ID: Mike Meyer schrieb: > If the hash changes, you've screwed up the set. What it really should > say is "collection of objects with fixed hashes", or words to that > effect. Do you want to file a PR on this? I fear I have not enough understanding of Python's hashing concepts to make a suggestion for improvement here. > How so? As I demonstrated, you can subclass any class that doesn't > have a hash to add one, and then use the subclass, which - except for > having a hash - will have exactly the same behavior as your original > class. But you surely wouldn't want to do this to the list of items just to be able to return it as a set. -- Christoph From luismgz at gmail.com Fri Nov 25 07:58:37 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 25 Nov 2005 04:58:37 -0800 Subject: Python book for a non-programmer In-Reply-To: References: Message-ID: <1132923517.399110.101980@o13g2000cwo.googlegroups.com> Read my reply here from another thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/25aada3c22ce6e66/cc69fd0c78384e5b?q=luis+cogliati's&rnum=1#cc69fd0c78384e5b From fredrik at pythonware.com Mon Nov 21 02:55:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Nov 2005 08:55:48 +0100 Subject: How to draw a dash line in the Tkinter? References: <8c11e4350511171722r2edbf6bgc40c98fcfb1e57bc@mail.gmail.com> <1d987df30511201536r403797e1kbdd7e05d772ba11b@mail.gmail.com> Message-ID: "Shi Mu" wrote: > > > How to draw a dash line in the Tkinter? > > > > use the dash option. e.g. > > > > canvas.create_line(xy, fill="red", dash=(2, 4)) > > canvas.create_line(xy, fill="red", dash=(6, 5, 2, 4)) > > > > (the tuple contains a number of line lengths; lengths at odd positions > > are drawn, lengths at even positions are gaps. note that not all com- > > binations are supported on all platforms; if Tkinter cannot find an exact > > match, it will pick a the "closest possible"). > where can I find the option settings for dash line? in the post you replied to? or here (same, but without examples): http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_line-method or here (using tcl syntax): http://www.tcl.tk/man/tcl8.4/TkLib/GetDash.htm From mrbmahoney at gmail.com Sat Nov 19 22:40:28 2005 From: mrbmahoney at gmail.com (B Mahoney) Date: 19 Nov 2005 19:40:28 -0800 Subject: Can a function access its own name? References: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> Message-ID: <1132458028.404160.166040@g44g2000cwa.googlegroups.com> Decorate any function with @aboutme(), which will print the function name each time the function is called. All the 'hello' stuff is in the aboutme() decorator code. There is no code in the decorated functions themselves doing anything to telling us the function name. # The decorator def aboutme(): def thecall(f, *args, **kwargs): # Gets to here during module load of each decorated function def wrapper( *args, **kwargs): # Our closure, executed when the decorated function is called print "Hello\nthe name of this function is '%s'\n" \ % f.func_name return f(*args, **kwargs) return wrapper return thecall @aboutme() def testing(s): print "string '%s' is argument for function" % s @aboutme() def truing(): return True # Try these testing('x') testing('again') truing() From malvert at telenet.be Sat Nov 5 17:14:02 2005 From: malvert at telenet.be (malv) Date: 5 Nov 2005 14:14:02 -0800 Subject: Using Which Version of Linux References: Message-ID: <1131228842.327509.217400@g44g2000cwa.googlegroups.com> blah at blah.blah wrote: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. > -- > * Posted with NewsLeecher v3.0 Beta 7 > * http://www.newsleecher.com/?usenet You have to look out for the version of Python the distro comes with 2.4. Some don't and it may be nasty having to deal with different versions installed next to one another. (You will probably not be able to safely remove the original version as the distro uses it for many things.) Another point to watch for is things like Python bindings and easyness of gui (free) installation. FWIW, I like Suse10.0 (Novell). It has kde-Python bindings to Qt installed. It also has eric3 available. So without any additional cost or trouble, you'll have a powerful, dream developer's system. malv From steve at holdenweb.com Tue Nov 8 10:47:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 Nov 2005 15:47:13 +0000 Subject: image In-Reply-To: <1d987df30511080107y7fa289b0n676245789494a26d@mail.gmail.com> References: <1d987df30511080018h1111aaa0t79e885438f8e2956@mail.gmail.com> <1d987df30511080107y7fa289b0n676245789494a26d@mail.gmail.com> Message-ID: Shi Mu wrote: > On 11/8/05, Fredrik Lundh wrote: > >>Shi Mu wrote: >> >> >>>why the following code report the error: >>>Traceback (most recent call last): >>> File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", >>>line 310, in RunScript >>> exec codeObject in __main__.__dict__ >>> File "C:\Python23\Examples\AppB\text.py", line 24, in ? >>> text.image_create(END, image=photo) >>> File "C:\Python23\lib\lib-tk\Tkinter.py", line 2882, in image_create >>> return self.tk.call( >>>TclError: image "pyimage4" doesn't exist >> >>works for me, when running it from a stock CPython interpreter. >> >>have you tried running the script outside the pywin environment? >> > yes. I use both cmd and pythonwin to run it. why both of them can not work? > You'll notice I have moved your reply underneath the posting it replied to, which is normally the easiest way for readers to follow a thread. Please try to avoid "top posting". The reason you can't run Tkinter applications under PythonWin is that PythonWin does not use a separate process to run the modules you ask it to execute. Since PythonWin used MFC-style windowing, there is a conflict between the event-handling loops of the two different windowing systems. 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 fredrik at pythonware.com Fri Nov 18 03:20:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Nov 2005 09:20:08 +0100 Subject: Newbie question: does file("text.txt', "w").write("stuff") ever get closed? References: <1132261192.858000-81686986-16815@walla.com> Message-ID: "John Doe" wrote: > In an effort to avoid another potential mistake, I am wondering if the > anonymous file object/class/thingy that I create when I do file("text.txt', > "w").write("stuff") gets closed properly on exit or garbage collection or > something yes. > or if I always need to hang on to these things and close them myself. only if you want to 1) know exactly when the files are closed, or 2) are using so many files that the garbage collector cannot keep up with you (this never happens on CPython, but can, at least in theory, happen on other Python implementations) From jeff at schwabcenter.com Sat Nov 5 07:40:43 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Sat, 05 Nov 2005 12:40:43 GMT Subject: Python doc problem example: gzip module (reprise) In-Reply-To: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > i've read the official Python tutorial 8 months ago, have spent 30 > minutes with Python 3 times a week since, have 14 years of computing > experience, 8 years in mathematical computing and 4 years in unix admin > and perl I can wiggle my ears. From joeyjwc at gmail.com Sat Nov 19 15:46:02 2005 From: joeyjwc at gmail.com (Joey C.) Date: 19 Nov 2005 12:46:02 -0800 Subject: Using win32ui.CreateFileDialog() to get the name of a file. In-Reply-To: References: <1132417639.273376.27820@g47g2000cwa.googlegroups.com> Message-ID: <1132433162.657199.150260@g49g2000cwa.googlegroups.com> Okay, thank you. This worked very well. From wahn at acm.org Fri Nov 18 21:07:36 2005 From: wahn at acm.org (wahn at acm.org) Date: 18 Nov 2005 18:07:36 -0800 Subject: Embedded Python interpreter and sockets Message-ID: <1132366056.922805.122480@g14g2000cwa.googlegroups.com> Hi, Here is a problem I came across and need some help with. I developed a little Python script with some classes which runs standalone and communicates with a database via sockets. So far everything works fine. I also successfully embedded the Python interpreter into a plugin for a commercial 3D package (in this case Houdini - http://www.sidefx.com/ - using the HDK). I can use the interpreter to run Python commands and get values back and forth between Python and C++. Anyway, I can also successfully import SOME modules, but unfortunately not ALL. One example would be the socket module which works fine in the standalone version of my Python script but NOT from the embedded interpreter: Traceback (most recent call last): File "", line 40, in ? File "/swdevl/jwalter/Houdini/ROPS/HoudiniToMayaBake/damn.py", line 10, in ? import socket File "/job/SYSTEMS/3PS/python/2.4.1/linux_intel//lib/python2.4/socket.py", line 45, in ? import _socket ImportError: /job/SYSTEMS/3PS/python/2.4.1/linux_intel/lib/python2.4/lib-dynload/_socket.so: undefined symbol: PyObject_GenericGetAttr Other modules which get imported before just work fine (e.g. re and string) ... The Python library gets linked into the plugin DSO as a static library ... Any ideas what's going wrong and why? Cheers, Jan From joe_public34 at yahoo.com Tue Nov 15 11:08:06 2005 From: joe_public34 at yahoo.com (joe_public34) Date: Tue, 15 Nov 2005 16:08:06 -0000 Subject: using openurl to log into Yahoo services Message-ID: Hello all, I'm trying to write a script to log into Yahoo! (mail, groups, etc), but when I pass the full URL with all form elements via Python, I get a resutling 400 - Bad Request page. When I just plop the full URL into a browser, it works perfectly. Is there something I need to specify in python to submit the correct info (headers, user agent, etc) to get the response I want? Here is the code I have that returns the Bad Request: import urllib, win32gui, win32clipboard, win32con, os, getpass, re yid = raw_input("Yahoo! ID: ") pw = getpass.getpass(prompt = 'Yahoo password: ') url = "https://login.yahoo.com/config/login?.tries=1&.src=ygrp&.intl=us&.v=0&.challenge=U4VY1YGqdPf8z3SaVccJdhV63YCw&.chkP=Y&.done=http://groups.yahoo.com&login="+yid+"&passwd="+pw+"&.persistent=y&.save=Sign In" temp = urllib.urlopen(url) grp_list_source = temp.read() Any thoughts or suggestions? Thanks. From duncan.booth at invalid.invalid Thu Nov 24 04:19:48 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Nov 2005 09:19:48 GMT Subject: return in loop for ? References: <1132812397.369787.214140@g47g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: >> Interestingly, I just saw a thread over at TurboGears(or is it this >> group, I forgot) about this multiple return issue and there are people >> who religiously believe that a function can have only one exit point. >> >> def f(): >> r = None >> for i in range(20): >> if i > 10: >> r = 10 >> break >> if r is None: something >> else: return r >> To bonono, not Steve: So if a function should religiously have only one exit point why does the example you give have two exit points? i.e. the 'return r', and the implied 'return None' if you execute the 'something' branch. > Well, I'm happy in this instance that practicality beats purity, since > the above is not only ugly in the extreme it's also far harder to read. > > What are the claimed advantages for a single exit point? I'd have > thought it was pretty obvious the eight-line version you gave is far > more likely to contain errors than Mike's three-line version, wouldn't > you agree? > Arguments include: any cleanup code you need when returning from a function is all in one place (mostly applicable to languages where you have to do your own memory management---see the recent AST discussion on the python dev list); or it stops you accidentally forgetting to return a value (as demonstrated above :^) ) In practice it is impossible to write code in Python (or most languages) with only one return point from a function: any line could throw an exception which is effectively another return point, so the cleanup has to be done properly anyway. From duncan.booth at invalid.invalid Tue Nov 1 09:17:23 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Nov 2005 14:17:23 GMT Subject: String Identity Test References: Message-ID: Thomas Moore wrote: > I am confused at string identity test: > > Does that mean equality and identity is the same thing for strings? > Definitely not. What is actually happening is that certain string literals get folded together at compile time to refer to the same string constant, but you should never depend on this happening. If 'a!=b' then it will also be the case that 'a is not b', but if 'a==b' then there are no guarantees; any observed behaviour is simply an accident of the implementation and could change: >>> a="test 1" >>> b="test 1" >>> a is b False >>> a="test" >>> b="test" >>> a is b True >>> Testing for identity is only useful in very rare situations, most of the time you are better just to forget there is such a test. From mwm at mired.org Thu Nov 24 22:15:32 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 22:15:32 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> Message-ID: <86y83dto2z.fsf@bhuda.mired.org> "bonono at gmail.com" writes: > Christoph Zwerschke wrote: >> jepler at unpythonic.net schrieb: >> > You can already get a set from a dictionary's keys in an efficient manner: >> >>>>l = dict.fromkeys(range(10)) >> >>>>set(l) >> > Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >> Good point. I expected that set(l) = set(l.items()) and not >> set(l.keys()), but the latter would not work with mutable values. See >> discussion with Martin. > puzzled. items() return tuples which I believe can be element of set ? > Or I misread you ? Not all tuples can be elements of a set. Elements of a set have to be hashable. Tuples compute their hash by hashing their contents. If their contents aren't hashable, the tuple isn't hashable, and hence can't be an element of a set. If the values in the dictionary aren't hashable, then the tuples returned by items() won't be hashable either, and hence can't be elements of a set. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From max at alcyone.com Sun Nov 13 17:58:57 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Nov 2005 14:58:57 -0800 Subject: Copyright [was Re: Python Obfuscation] In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > That is *not* generally true, although it is true in certain industries, > such as newspapers. It is true in many industries, including the software industry. My point was that the creator of a work and the copyright holder and not necessarily one and the same. Often, in fact, they are not. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Life is painting a picture, not doing a sum. -- Oliver Wendell Holmes, Jr. From larry.bates at websafe.com Tue Nov 1 17:40:29 2005 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 01 Nov 2005 16:40:29 -0600 Subject: array of Tkinter variables? In-Reply-To: References: Message-ID: <4367EEDD.5070405@websafe.com> Jo Schambach wrote: > I want to build an array of entry widgets in python with Tkinter that > all have similar textvariables. I was hoping that I could use an array > of StringVar variables to attach to these widgets, so that I can loop > through the widget creation. But my simple minded approach failed: > > for i in range(32): > self.dllAdjust[i] = StringVar() > self.dllAdjust[i].set('000') > > gives me the following error: > > File "./config.py", line 787, in setDefaultVals > self.dllAdjust[i] = StringVar() > AttributeError: Configurator instance has no attribute 'dllAdjust' > > > ("Configurator" is the class in which this code fragment appears) > > How does one define an array of StringVar? If that is not possible, what > would be an alternative approach to the idea in the code fragment above? > > Jo I think what you want is something like: self.dllAdjust=[] for i in range(32): sv=StringVar() sv.set('000') self.dllAdjust.append(sv) (not tested) Larry Bates From xray_alpha_charlie at yahoo.com Sun Nov 6 01:02:17 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Sat, 5 Nov 2005 22:02:17 -0800 (PST) Subject: newbie questions Message-ID: <20051106060217.52350.qmail@web35906.mail.mud.yahoo.com> have a few questions...i'm a newbie....so i'd appreciate any help 1- what is the difference between Python GUI and Python command line? 2-in Python command line when I hit enter after typing a command I cannot go back and "delete" "backspace" or otherwise edit a previous command...why? 3-I have tried the following example from "how to think like a computer scientist" def makeline(): print print "firstline" makeline() print "secondline" problem is....whenever I type -print "firstline"- and then hit enter...well it follows the command and gives "firstline" EX. print "firstline" firstline instead of giving me a chance to type in -makeline()- and thus completing the example Anybody help here?? thanks -xray- __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From samrobertsmith at gmail.com Wed Nov 9 07:14:22 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Wed, 9 Nov 2005 04:14:22 -0800 Subject: triangulation Message-ID: <1d987df30511090414m1864e236jdcd51e58a1d153ab@mail.gmail.com> is there any sample code to triangulation? many thanks! From fredrik at pythonware.com Fri Nov 11 11:44:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 17:44:18 +0100 Subject: Python-based Document Management System? References: <1131726757.4374c7a51cb7c@webmail.in-berlin.de> Message-ID: W. Borgert wrote: > > If you search for CONTENT management system, there is > > Plone: A user-friendly and powerful open source Content Management ... > > http://plone.org/ > > No, I'm looking for a DMS, not a CMS. My impression from > the Plone web page is, that it does not have DMS features. maybe this is what you want ? http://bscw.fit.fraunhofer.de/ for a hosted (and very polished) implementation of BSCW, see http://www.projectplace.com/index.html From steven.bethard at gmail.com Thu Nov 17 15:30:48 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Nov 2005 13:30:48 -0700 Subject: how to organize a module that requires a data file In-Reply-To: <437CE56D.8010606@websafe.com> References: <437CE56D.8010606@websafe.com> Message-ID: Larry Bates wrote: > Personally I would do this as a class and pass a path to where > the file is stored as an argument to instantiate it (maybe try > to help user if they don't pass it). Something like: > > class morph: > def __init__(self, pathtodictionary=None): > if pathtodictionary is None: > # Insert code here to see if it is in the current > # directory and/or look in other directories. > try: self.fp=open(pathtodictionary, 'r') > except: > print "unable to locate dictionary at: %s" % pathtodictionary > else: > # Insert code here to load data from .txt file > fp.close() > return > > def get_stem(self, arg1, arg2): > # Code for get_stem method Actually, this is basically what I have right now. It bothers me a little because you can get two instances of "morph", with two separate dictionaries loaded. Since they're all loading the same file, it doesn't seem like there should be multiple instances. I know I could use a singleton pattern, but aren't modules basically the singletons of Python? > The other way I've done this is to have a .INI file that always lives > in the same directory as the class with an entry in it that points me > to where the .txt file lives. That's a thought. Thanks. Steve From fredrik at pythonware.com Wed Nov 16 03:19:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 09:19:36 +0100 Subject: Python/ASP local characters and 500 server error References: <437ae3b1$0$46986$edfadb0f@dread15.news.tele.dk> Message-ID: Martin wrote: > Using Python / ASP on a IIS server with Mark Hammond's win32 extensions, > i have the following problem. > > All occurences of local characters (fx. danish ???) in comments or in > strings result in a HTTP/1.1 500 Server Error. > > Is there a solution to this problem? the first thing to do when you get a server error is to look in the server logs to see what the real error is. in this case, chances are that you'll see a warning message from the Python interpreter that points to you this page: http://www.python.org/peps/pep-0263.html (scroll down to "Examples" to see the solution) From bokr at oz.net Thu Nov 10 18:37:50 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 10 Nov 2005 23:37:50 GMT Subject: Recompile AST? References: <1131657716.197347.167740@g47g2000cwa.googlegroups.com> Message-ID: <4373d1cb.156169219@news.oz.net> On 10 Nov 2005 13:21:56 -0800, chrisspen at gmail.com wrote: >Is it possible to recompile the AST generated by compiler.parse, back >into code or an executable code object? My aim here is to allow a >script to manipulate Python code as elements within a list. However, it >doesn't look like the module has any native methods designed to do >this. > It is possible, but if you want code from a particular python source string that you are giving to compiler.parse, why not use compile? Or do you want to modify the AST and then compile? This can be done too, but modifying the AST can be tricky. Based on the starting point providided by http://groups.google.com/group/comp.lang.python/browse_thread/thread/5fa80186d9f067f4/7a2351b221063a8c I've done a few experiments, e.g., http://groups.google.com/group/comp.lang.python/msg/9a3f473ae5c23751 I've also posted sporadic musings about the possibilities for AST-transforming custom import functions to do optimizations and macros and special forms etc., but no one seemed much interested (or maybe they quietly went off to do something of their own ;-) I've seen some references to new AST stuff in the latest version, but I haven't got the new version. I really must clean up my disk for space ;-/ Regards, Bengt Richter From deets at nospam.web.de Sat Nov 19 13:09:18 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 19 Nov 2005 19:09:18 +0100 Subject: Can a function access its own name? In-Reply-To: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> References: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> Message-ID: <3u982aF109s4hU1@uni-berlin.de> bobueland at yahoo.com wrote: > Look at the code below: > > # mystringfunctions.py > > def cap(s): > print s > print "the name of this function is " + "???" > > cap ("hello") > > > Running the code above gives the following output > > >>> > hello > the name of this function is ??? > >>> > > I would like the output to be > > >>> > hello > the name of this function is cap > >>> > > Is that possible ? Yes, use the moduloe inspect to access the current stack frame: def handle_stackframe_without_leak(): frame = inspect.currentframe() try: print inspect.getframeinfo(frame)[2] finally: del frame Diez From steve at holdenweb.com Thu Nov 24 00:59:47 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 05:59:47 +0000 Subject: Using Cron to run a python program In-Reply-To: <20051124014517.M83381@uniqsys.com> References: <1132791791.548850.186420@o13g2000cwo.googlegroups.com> <20051124014517.M83381@uniqsys.com> Message-ID: Carsten Haese wrote: > On 23 Nov 2005 16:23:11 -0800, vagrantbrad wrote > >>I'm using python 2.4 running on Fedora Core 4. I have written a python >>program called ipscan.py that checks the external ip address of my >>cable internet connection, and on change, will update the dns records >>at my dns provider, zoneedit. So basically, I've setup dynamic dns >>using python. Once the ip compare and/or update is complete, I log the >>results to a text file called update.log. When I run the program in >>a bash shell with the command "python ipscan.py", the program runs fine >>and the results are appended to update.log. When I run this program >>as a cron job under the root user with the previously mentioned >>command, the program runs without errors but does not append an >>entry to the log. The permissions on the update.log file should not >>be an issue since I'm running the cron job as root, but I've given >>root write permissions just to be safe. What would cause the >>logging to work at a command prompt but fail in cron? I'm not >>getting any errors in the cron logs or /var/spool/mail/root. > > > You're not giving us much detail about your script, so we can only guess. My > guess is that your python script is either not invoked at all or it dies > (raises an exception) before appending to the update.log. > > You should keep in mind that cron jobs don't run in a normal login shell, > don't have the normal environment variables, and are not attached to a tty. > Any of those factors can conceivably cause a script to fail under cron when it > works fine from a shell. > Since we're guessing, *my* guess would be that the cron-triggered runs are running in some directory other than the one the manually-triggered jobs are, and that there is a separate update.log file in that directory. The fix, of course, would be to use an absolute path to identify the log file (if I'm right). 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 DonQuixoteVonLaMancha at gmx.net Tue Nov 15 17:48:44 2005 From: DonQuixoteVonLaMancha at gmx.net (DonQuixoteVonLaMancha at gmx.net) Date: 15 Nov 2005 14:48:44 -0800 Subject: is parameter an iterable? In-Reply-To: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> Message-ID: <1132094924.841645.197260@g47g2000cwa.googlegroups.com> How about hasattr("__iter__")? Regards, Karsten. From nospam at here.com Tue Nov 8 08:51:07 2005 From: nospam at here.com (Matt Feinstein) Date: Tue, 08 Nov 2005 08:51:07 -0500 Subject: any python module to calculate sin, cos, arctan? References: Message-ID: On Tue, 08 Nov 2005 12:30:35 GMT, "Raymond L. Buvel" wrote: >Shi Mu wrote: >> any python module to calculate sin, cos, arctan? > >The other answers in this thread point you to the standard modules. If >you need arbitrary precision floating point versions of these functions >check out: > >http://calcrpnpy.sourceforge.net/clnumManual.html Unless you're using Windows. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From volker.lenhardt at uni-due.de Thu Nov 17 09:56:33 2005 From: volker.lenhardt at uni-due.de (Volker Lenhardt) Date: Thu, 17 Nov 2005 15:56:33 +0100 Subject: PyQt layout question: QScrollView and QGridLayout? Message-ID: <3u3jq1Fv4h36U1@news.dfncis.de> For a QApplication (PyQt) on the small screen of my Zaurus 5500 PDA I try to layout my data output in a QScrollView as the central widget. I'd prefer to use QGridLayout, but cannot add it to the scroll view. sc=QScrollView(self) layout=QGridLayout(..., sc.viewport()) sc.addChild(layout) results in a TypeError. Is there a way to get it to work? Filling a box viewport with lots of padding boxes and white space labels to establish grids is very cumbersome. And I need 4 different layouts to change places. Best wishes Volker -- Volker Lenhardt E-Mail: volker.lenhardt at uni-duisburg-essen.de From bucodi at yahoo.fr Tue Nov 8 12:45:33 2005 From: bucodi at yahoo.fr (Rony) Date: Tue, 08 Nov 2005 17:45:33 -0000 Subject: tkinter and visual ocx Message-ID: I've managed to register succesfuly an oxc with makepy and my python programm reconises the ocx. But now i have a problem to place the ocx on a tkinter frame. Perhaps somebody could show me a code snippet how to do it ? tia Rony From alanmk at hotmail.com Tue Nov 8 15:52:28 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 08 Nov 2005 20:52:28 +0000 Subject: Map of email origins to Python list In-Reply-To: References: <1131390365.721288.272070@g47g2000cwa.googlegroups.com> <1131396963.363256.12250@g47g2000cwa.googlegroups.com> <1131400439.260344.19880@g44g2000cwa.googlegroups.com> <8pRbf.18342$R5.1653@news.indigo.ie> Message-ID: [Claire McLister] > I've made the script available on our downloads page at: > > http://www.zeesource.net/downloads/e2i [Alan Kennedy] >> I look forward to the map with updated precision :-) [Claire McLister] > Me too. Please let me know how we should modify the script. Having examined your script, I'm not entirely sure what your input source is, so I'm assuming it's an mbox file of the archives from python-list, e.g. as appears on this page http://mail.python.org/pipermail/python-list/ or at this URL http://mail.python.org/pipermail/python-list/2005-November.txt Those messages are the email versions, so all of the NNTP headers, e.g. NNTP-Posting-Host, will have been dropped. You will need these in order to get the geographic location of posts that have been made through NNTP. In order to be able to get those headers, you need somehow to get the NNTP originals of messages that originated on UseNet. You can see an example of the format, i.e. your message to which I am replying, at this URL http://groups.google.com/group/comp.lang.python/msg/56e3baabcd4498f2?dmode=source The NNTP-Posting-Host for that message is '194.109.207.14', which reverses to 'bag.python.org', which is presumably the machine that gatewayed the message from python-list onto comp.lang.python. So there are a couple of different approaches 1. Get an archive of the UseNet postings to comp.lang.python (anybody know where?) A: messages sent through email will have the NNTP-Posting-Host as a machine at python.org, so fall back to your original algorithm for those messages B: messages sent through UseNet, or a web gateway to same, will have an NNTP-Posting-Host elsewhere than python.org, so do your geo-lookup on that IP address. 2. Get the python-list archive A: Figure out which messages came through the python.org NNTP gateway (not sure offhand if this is possible). Automate a query to Google groups to find the NNTP-Posting-Host (using a URL like the one above). Requires being able to map the python-list message-id to the google groups message-id. Do your geo-lookup on that NNTP-Posting-Host value B: Use your original algorithm for messages sent through email. 2A message-id lookup should be achievable through the advanced google groups search, at this URL http://groups.google.com/advanced_search?q=& See the "Lookup the message with message ID" at the bottom. Sorry I don't have time to supply code for any of this. Perhaps some one can add more details, or better still some code? -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From apardon at forel.vub.ac.be Thu Nov 3 07:20:35 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Nov 2005 12:20:35 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> Message-ID: Op 2005-11-03, Stefan Arentz schreef : > Antoon Pardon writes: > >> Op 2005-11-03, Steven D'Aprano schreef : >> >> >> There are two possible fixes, either by prohibiting instance variables >> >> with the same name as class variables, which would allow any reference >> >> to an instance of the class assign/read the value of the variable. Or >> >> to only allow class variables to be accessed via the class name itself. >> > >> > There is also a third fix: understand Python's OO model, especially >> > inheritance, so that normal behaviour no longer surprises you. >> >> No matter wat the OO model is, I don't think the following code >> exhibits sane behaviour: >> >> class A: >> a = 1 >> >> b = A() >> b.a += 2 >> print b.a >> print A.a >> >> Which results in >> >> 3 >> 1 > > I find it confusing at first, but I do understand what happens :-) I understand what happens too, that doesn't make it sane behaviour. > But really, what should be done different here? I don't care what should be different. But a line with only one referent to an object in it, shouldn't be referring to two different objects. In the line: b.a += 2, the b.a should be refering to the class variable or the object variable but not both. So either it could raise an attribute error or add two to the class variable. Sure one could object to those sematics too, but IMO they are preferable to what we have now. -- Antoon Pardon From fredrik at pythonware.com Wed Nov 23 12:18:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 18:18:34 +0100 Subject: strange behaviour when writing a large amount of data on stdout References: <7879o1t3acnq7dq9f60pspt6rhkpkbppsv@4ax.com> Message-ID: Manlio Perillo wrote: > >>>>> print data > >> > >> Traceback (most recent call last): > >> File "xxx", line xxx, in ? > >> print data > >> IOError: [Errno 12] Not enough space > > > >errno 12 is ENOMEM (that is, the system did not have enough memory > >to finish an operation). > > However I think the error message is not a good one. > Better a "Not enough memory" the message text is provided by the operating system (or rather, by the C library). I'm not sure rewriting error messages is a good thing... (if Python itself runs out of memory, it'll raise a MemoryError instead) From p at ulmcnett.com Tue Nov 29 15:37:41 2005 From: p at ulmcnett.com (Paul McNett) Date: Tue, 29 Nov 2005 12:37:41 -0800 Subject: wxGrid and Focus Event In-Reply-To: <1133294056.952406.108890@g44g2000cwa.googlegroups.com> References: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> <438CACF1.1020909@ulmcnett.com> <1133294056.952406.108890@g44g2000cwa.googlegroups.com> Message-ID: <438CBC15.5070308@ulmcnett.com> lux wrote: > Can you try this code? Sure, thanks for posting it! > If you press only the TAB key > the focus go from the TextCtrl to the Grid (I suppose) > but onGridFocus in not called. Confirmed, at least on Gtk. > any idea? Yep, the grid is actually a collection of subwindows, and I made the guess that the first window to get the focus is actually that little corner window at the intersection of the column labels and the row labels. Try this instead: >>> g.GetGridCornerLabelWindow().Bind(wx.EVT_SET_FOCUS, onGridFocus) -- Paul McNett http://paulmcnett.com http://dabodev.com From steve at REMOVETHIScyber.com.au Mon Nov 28 09:06:29 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 29 Nov 2005 01:06:29 +1100 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: On Mon, 28 Nov 2005 10:02:19 +0100, Sybren Stuvel wrote: > Duncan Booth enlightened us with: >> I would have thought that no matter how elaborate the checking it is >> guaranteed there exist programs which are correct but your verifier >> cannot prove that they are. > > Yep, that's correct. I thought the argument was similar to the proof > that no program (read: Turing machine) can determine whether a program > will terminate or not. No, that is not right -- it is easy to create a program to determine whether *some* programs will terminate, but it is impossible to create a program which will determine whether *all* programs will terminate. -- Steven. From bos at REMOVETHIShack.org Sun Nov 27 05:23:53 2005 From: bos at REMOVETHIShack.org (Rikard Bosnjakovic) Date: Sun, 27 Nov 2005 10:23:53 GMT Subject: wxPython Licence vs GPL In-Reply-To: References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <1h6lmts.1fr63yddwj4y4N%aleax@mail.comcast.net> <1h6mkzb.meaeo31vesla6N%aleax@mail.comcast.net> Message-ID: Steven D'Aprano wrote: > (Kids! Pirating software is stealing!!!) Or evaluating, depending of how you look at it. -- Sincerely, | http://bos.hack.org/cv/ Rikard Bosnjakovic | Code chef - will cook for food ------------------------------------------------------------------------ From pmartin at snakecard.com Sun Nov 13 12:29:59 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Sun, 13 Nov 2005 11:29:59 -0600 Subject: SnakeCard goes open source References: Message-ID: I forgot SC-School-ID and SC-Corporate-ID: software = Python, GUI = wxWidget, Applets JavaCard and BasicCard. Regards, Philippe Philippe C. Martin wrote: > Dear all, > > I have decided to focus my activities on development and support. > > I will release SnakeCard's produt line source code under the GPL licence > this week (www.snakecard.com) ... I need to fix the site. > > It includes: > SCF: SnakeCard Framework (software=Python) > SCFB: SnaleCard Framework Bundle (software=Python, applets BasicCard T=1, > JavaCard T=0) > SCALS: (software: Python (core), VB6 (GUI), C++ (GINA DLL), applets > BasicCard T=1, JavaCard T=0) > SC PCSC Server(software=Python) > > Best regards, > > > Philippe From pinkfloydhomer at gmail.com Tue Nov 8 04:12:07 2005 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: 8 Nov 2005 01:12:07 -0800 Subject: Addressing the last element of a list In-Reply-To: References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> Message-ID: <1131441127.076800.59110@o13g2000cwo.googlegroups.com> I knew there was an easy way :) Just to satisfy my curiousity: Is there a way to do something like the reference solution I suggest above? From duncan.booth at invalid.invalid Thu Nov 17 03:37:23 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Nov 2005 08:37:23 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <86r79ji8lt.fsf@bhuda.mired.org> <86k6f9r9sh.fsf@bhuda.mired.org> <863blwpfxd.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Wouldn't one.__dict__ = dict(**two.__dict__) be a bit better? > Those stars are redundant here. It would be cleaner to write: one.__dict__ = dict(two.__dict__) From apardon at forel.vub.ac.be Thu Nov 10 10:06:23 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Nov 2005 15:06:23 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> Message-ID: Op 2005-11-10, Steven D'Aprano schreef : > On Thu, 10 Nov 2005 06:47:41 +0000, Donn Cave wrote: > >> Quoth Steven D'Aprano : >> ... >> | So when working with ints, strs or other immutable objects, you aren't >> | modifying the objects in place, you are rebinding the name to another >> | object: >> | >> | py> spam = "a tasty meat-like food" >> | py> alias = spam # both names point to the same str object >> | py> spam = "spam spam spam spam" # rebinds name to new str object >> | py> print spam, alias >> | 'spam spam spam spam' 'a tasty meat-like food' >> >> The semantics of assignment are like that, period. If the right hand >> side is an int, a string, a class instance, a list, whatever, doesn't >> matter at all. The question of mutability at this point can be a red >> herring for someone who doesn't already understand these matters. > > Yes, but in the context we were discussing, the original poster was > specifically asking to do something that is only possible with mutable > objects. > > He wanted to do something like this: > > data = [0, None, 2, ["hello"]] > ref = data[-1] > ref.append("world") > > and end up with [0, None, 2, ["hello", "world"]]. That will work, because > the last item in data is mutable. But this will NOT work: > > data = [0, None, 2, 0] > ref = data[-1] > ref = 1 > assert data[-1] == 1 > > because ints are immutable. So the distinction between modifying a > mutable object in place and assigning is important. I wonder couldn't this be done with properties? Write somekind of property so that if you manipulate a.x it would manipulate data[-1] -- Antoon Pardon From thomas.info at hol.gr Tue Nov 29 09:46:16 2005 From: thomas.info at hol.gr (Thomas G. Apostolou) Date: Tue, 29 Nov 2005 16:46:16 +0200 Subject: Problem cmpiling M2Crypto Message-ID: Hello all. i am trying to make some win32 binaries of M2Crypto 0.15 What I use is: Python 2.3.3 openssl-0.9.7i swigwin 1.3.27 I have build the openssl binaries and have installed the Swig binary python dir is C:\Program Files\Plone 2\Python openssl dir is c:\openssl Swig dir is c:\swig so I have modified the setup.py of m2crypto to : if os.name == 'nt': openssl_dir = 'c:\\openssl' include_dirs = [my_inc, openssl_dir + '/include'] swig_opts_str = '-I"' + openssl_dir + os.sep + 'include"' library_dirs = [openssl_dir + '\\lib'] libraries = ['ssleay32', 'libeay32'] when i execute python setup.py build from the command prompt i get the following erros: C:\Program Files\Plone 2\Python\lib\distutils\extension.py:128: UserWarning: Unknown Extension options: 'swig_opts' warnings.warn(msg) running build running build_py running build_ext building '__m2crypto' extension C:\SWIG\swig.exe -python -ISWIG -I"c:\openssl\include" -o SWIG/_m2crypto.c SWIG/_m2crypto.i SWIG\_lib.i(527): Warning(121): %name is deprecated. Use %rename instead. SWIG\_lib.i(528): Warning(121): %name is deprecated. Use %rename instead. SWIG\_lib.i(529): Warning(121): %name is deprecated. Use %rename instead. SWIG\_lib.i(530): Warning(121): %name is deprecated. Use %rename instead. SWIG\_lib.i(531): Warning(121): %name is deprecated. Use %rename instead. SWIG\_lib.i(532): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(17): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(18): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(19): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(20): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(21): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(22): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(24): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(25): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(26): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(27): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(28): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(29): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(30): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(31): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(33): Warning(121): %name is deprecated. Use %rename instead. SWIG\_bio.i(34): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rand.i(7): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rand.i(8): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rand.i(9): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rand.i(10): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rand.i(11): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(26): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(27): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(28): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(29): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(31): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(32): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(33): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(34): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(35): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(36): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(37): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(38): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(39): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(40): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(41): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(42): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(43): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(44): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(45): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(46): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(53): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(54): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(55): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(56): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(63): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(64): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(65): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(66): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(67): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(68): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(69): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(70): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(71): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(72): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(73): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(74): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(75): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(76): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(78): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(79): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(80): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(81): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(82): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(83): Warning(121): %name is deprecated. Use %rename instead. SWIG\_evp.i(84): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dh.i(14): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dh.i(15): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dh.i(16): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dh.i(17): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dh.i(18): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rsa.i(14): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rsa.i(15): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rsa.i(16): Warning(121): %name is deprecated. Use %rename instead. SWIG\_rsa.i(17): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dsa.i(21): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dsa.i(22): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dsa.i(23): Warning(121): %name is deprecated. Use %rename instead. SWIG\_dsa.i(24): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(26): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(27): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(28): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(29): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(30): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(31): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(32): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(33): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(35): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(36): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(37): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(38): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(40): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(41): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(42): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(43): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(44): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(45): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(46): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(47): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(48): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(49): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(50): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(52): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(54): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(55): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(56): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(57): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(58): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(59): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(60): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(61): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(62): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(63): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(64): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(65): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(66): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(68): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(69): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(70): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(71): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(72): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(73): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(74): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(76): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(77): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(79): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(80): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(82): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(83): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(84): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(85): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(86): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(87): Warning(121): %name is deprecated. Use %rename instead. SWIG\_ssl.i(88): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(22): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(23): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(24): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(25): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(27): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(28): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(30): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(31): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(32): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(33): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(34): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(35): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(36): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(37): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(70): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(71): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(73): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(74): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(76): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(77): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(79): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(80): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(81): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(82): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(84): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(85): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(86): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(87): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(88): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(89): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(90): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(91): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(92): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(93): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(94): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(96): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(97): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(98): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(99): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(100): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(101): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(102): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(104): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(105): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(106): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(108): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(109): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(110): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(112): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(113): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(115): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(117): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(118): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(119): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(121): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(122): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(123): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(124): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(126): Warning(121): %name is deprecated. Use %rename instead. SWIG\_x509.i(127): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(19): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(20): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(21): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(22): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(23): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(24): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(26): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(31): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(32): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(33): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(34): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(36): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(37): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(38): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(39): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(40): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(41): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(43): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(44): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(45): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(46): Warning(121): %name is deprecated. Use %rename instead. SWIG\_asn1.i(47): Warning(121): %name is deprecated. Use %rename instead. SWIG\_pkcs7.i(18): Warning(121): %name is deprecated. Use %rename instead. SWIG\_pkcs7.i(19): Warning(121): %name is deprecated. Use %rename instead. C:\Program Files\Microsoft Visual Studio\VC98\BIN\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -IC:\m2crypto\SWIG -Ic:\openssl/include "-IC:\Program Files\Plone 2\Python\include" "-IC:\Program Files\Plone 2\Python\PC" /TcSWIG/_m2crypto.c /Fobuild\temp.win32-2.3\Release\SWIG/_m2crypto.obj -DTHREADING -DSWIG_COBJEC T_PYTHON _m2crypto.c SWIG/_m2crypto.c(80) : fatal error C1083: Cannot open include file: 'Python.h': No such file or directory error: command '"C:\Program Files\Microsoft Visual Studio\VC98\BIN\cl.exe"' failed with exit status 2 Then i open SWIG\_lib.i file and change all %name with %rename but still i get "SWIG\_lib.i(527): Error: Syntax error in input(1)." (line 527 is %rename(err_print_errors_fp) extern void ERR_print_errors_fp(FILE *);) and the same for all the following lines above appart from this i can not find Python.h anywhere ni my pc (WinXp) From sigzero at gmail.com Sun Nov 27 21:21:44 2005 From: sigzero at gmail.com (Robert Hicks) Date: 27 Nov 2005 18:21:44 -0800 Subject: PYTHONDOCS on OSX Message-ID: <1133144504.909363.219530@g49g2000cwa.googlegroups.com> How do I set this variable in my .bash_profile? I have the html docs in /usr/local/PythonDocs. Thanks for any help... Robert From michele.simionato at gmail.com Wed Nov 23 09:44:45 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 Nov 2005 06:44:45 -0800 Subject: Tutorials for Python + PostgreSQL In-Reply-To: <1132752765.953726.144150@g44g2000cwa.googlegroups.com> References: <1132752765.953726.144150@g44g2000cwa.googlegroups.com> Message-ID: <1132757085.775762.3720@f14g2000cwb.googlegroups.com> Steve: > I want to learn more about enterprise-level programming using Python > and PostgreSQL. From what I've searched, it seems that psycho is > interesting to improve runtime too. Do you have tutorials, articles and > tips to learn this combination? I've been working with PostgreSQL for 2 > years, and with Python for 6 months. > Thank you, Since Psyco is meant to speedup Python code, whereas the psycopg adapter is C-coded, I strongly doubt you will get any improvement from the combination. Michele Simionato From lard at tardis.ed.ac.molar.uk Tue Nov 1 05:54:00 2005 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Tue, 01 Nov 2005 10:54:00 GMT Subject: Need Python Pro for Help!! Plzz In-Reply-To: References: <5uSdnSSK7vYrTfneRVn-pQ@giganews.com> Message-ID: Gerhard H?ring wrote: > Alex Hunsley wrote: > >> blah at blah.blah wrote: >> >>> Need python Pro at newtopython at googlegroups.com , if u wanna help, >> >> [...] >> 2) Why should someone willing to help you enter into a private email >> discussion? [...] > > > Actually, it's a Google Group mailing list (formerly eGroups): > > http://groups.google.de/group/newtopython?lnk=sg&hl=de ah, I obviously didn't look closely enough at what appeared to be just an email address! > Maybe the people who set it up didn't know that there is perfectly good > mailing list for the same topic already: > > http://www.python.org/mailman/listinfo/tutor Didn't know about that one, thanks. > > -- Gerhard > From ronpro at cox.net Mon Nov 14 14:34:12 2005 From: ronpro at cox.net (Ron) Date: Mon, 14 Nov 2005 14:34:12 -0500 Subject: Tix BUG? Where to submit? Message-ID: <9E5ef.14634$4n5.2187@dukeread01> I've been developing a piece of software using Tix. In particular, I'm using the HList widget. I was attempting to use the info_bbox() mentod of that class to get the bounding box of a list entry. I'm using the release version Python 2.4.2. When I look in Tix.py I see that info_bbox() is not available. Well, I don't know much about the library, Tk or Tix but it appears that all the other methods are implemented. Using those as templates I attempted to add the function just to see what would happen. I added the folloing to Tix.py line 961. def info_bbox( self, entry ): coords = self.tk.call( self._w, 'info', 'bbox', entry ).split( ' ') return map( int, coords ) Surprising to myself, this was all that it took to make this work. So I'm not sure why this method was left out. Could it have been an oversight? Anyway, where would I subit this report to have it considered that this be added to Tix? Thanks for your help. Ron Provost From samantha7395 at hotmail.com Wed Nov 9 01:07:00 2005 From: samantha7395 at hotmail.com (Samantha) Date: Tue, 8 Nov 2005 22:07:00 -0800 Subject: Cursor Position. Message-ID: Looking at the goto(xy) thread. Is there a way to get the X,Y position from a cursor click and then use the position to apply something like a water mark on an image at that position? Thanks, From fredrik at pythonware.com Fri Nov 25 03:16:04 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Nov 2005 09:16:04 +0100 Subject: Draw a triangle... References: <1132883378.801303.265810@o13g2000cwo.googlegroups.com> <1132892375.761161.160630@o13g2000cwo.googlegroups.com> Message-ID: The Eternal Squire wrote: > PyGame is your best bet for pure graphics. Simple shapes can be done > in just a few statements. the same applies to Tkinter, of course. from Tkinter import * # set things up c = Canvas(); c.pack() # draw stuff c.create_polygon((0, 100, 50, 0, 100, 100), fill="red") # get things going mainloop() at the "draw a triangle" level, the main difference is mostly that Tkinter is a bit more likely to be installed on your machine... From skip at pobox.com Mon Nov 28 16:10:59 2005 From: skip at pobox.com (skip at pobox.com) Date: Mon, 28 Nov 2005 15:10:59 -0600 Subject: Death to tuples! In-Reply-To: <8664qcv6i5.fsf@bhuda.mired.org> References: <86y839ux1j.fsf@bhuda.mired.org> <8664qcv6i5.fsf@bhuda.mired.org> Message-ID: <17291.29283.304174.108113@montanaro.dyndns.org> Mike> Tuples have the problem that they are immutable, except when Mike> they're not (or for proper values of immutable, your Mike> choice). They're hashable, except when they're not. Or Mike> equivalently, they can be used as dictionary keys - or set Mike> elements - except when they can't. For those of us not following this thread closely, can you identify cases where tuples are mutable, not hashable or can't be used as dictionary keys? I've never encountered any such cases. Skip From darren at exoweb.net Wed Nov 9 04:09:42 2005 From: darren at exoweb.net (Darren Cui Liang) Date: Wed, 09 Nov 2005 17:09:42 +0800 Subject: Is it a bug? Message-ID: <4371BCD6.8090201@exoweb.net> Hi, there! Now I am working around with the "logging" module. Here is the code: >>> import logging >>> log1=logging.getLogger("a") >>> log1.critical("msg") No handlers could be found for logger "a" >>> logging.critical("msg") CRITICAL:root:msg Since every "logger" is under the "root logger", and if no handler is found for the logger, the message will be passed to upper level loggers, until the root, then why do I get the msg: No handlers could be found for logger "a" Thanks in advance! BR Darren Cui Liang From mensanator at aol.com Sat Nov 12 18:28:45 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 12 Nov 2005 15:28:45 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> <1131517112.247477.35030@g14g2000cwa.googlegroups.com> <1h5rxho.nxmo0z15zne5jN%aleax@mail.comcast.net> <1h5su7m.vwmk96qm9qplN%aleax@mail.comcast.net> <1131690799.409160.36930@g49g2000cwa.googlegroups.com> <1h5up32.1fa670mkz6a6bN%aleax@mail.comcast.net> <1131761668.269236.151100@g43g2000cwa.googlegroups.com> <1131762948.089130.326900@f14g2000cwb.googlegroups.com> Message-ID: <1131838125.395737.13670@g47g2000cwa.googlegroups.com> casevh at comcast.net wrote: > What processor are you running? Drat, didn't see this before I left work. I'm fairly certain it was a Pentium 4, definitely 1.7GHz, Win2000 and Python 2.3. So I thought I would run the test again on my home computers, a Pentium 4 1.5 GHz WinXP Python 2.3 and a laptop with a Celeron 2.8 GHz WinXP Python 2.4. Here are the Celeron/Python2.4 numbers (and original test times) BF: 27.89 sec gen6 (31.92) CF: 0.203 sec gen9 (0.234) V: 5.062 sec gen9 (8.766) > > I only have Windows running on an old Pentium 3. It is easy for me to > build a version that will running on almost any recent processor. I'm > willing to try and override the CPU detection and make a processor > specific build for you. I won't be able to test it, though. > > Thanks for the testing! > > Case From strombrg at dcs.nac.uci.edu Sat Nov 26 21:30:58 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Sun, 27 Nov 2005 02:30:58 GMT Subject: CGI question References: Message-ID: On Sat, 26 Nov 2005 13:26:11 +0100, Fredrik Lundh wrote: > Dan Stromberg wrote: > >> What's the best way of converting this: >> >> 'hide\\?http://www.dedasys.com/articles/programming_language_economics.html\x012005-07-20 >> 14:48' >> >> ...to something easily usable in a python CGI script? > > easily usable for what purpose? > > if you want to extract the URL that seems to be hidden in that string, > something like: > > url, junk = text.split("\x01", 1) > junk, url = url.split("\\?", 1) > > should work. Um, yeah. I can work out this sort of thing. But I thought there might be a python module intended for parsing inputs to CGI scripts? Sometimes using a pre-written module can contend with issues you didn't know where going to come up... Thanks! From free.condiments at gmail.com Wed Nov 2 00:37:42 2005 From: free.condiments at gmail.com (Sam Pointon) Date: 1 Nov 2005 21:37:42 -0800 Subject: Importing Modules References: Message-ID: <1130909862.743821.288020@z14g2000cwz.googlegroups.com> On the second point, a combination of sys.path, os.listdir and __import__ should do what you're after, although sifting through the whole of sys.path and subfolders from Python, rather than the interpreter itself, could be slow. (And it'll be redundant as well - __import__ will have do the same thing, though you could fix that by using the imp module). -Should- work, but not tested, so don't blame me if it doesn't: import sys, os, re def find_modules(str_pat): pat = re.compile(str_pat + '.py[co]?') init_pat = re.compile('__init__.py[co]?') for dir in sys.path: files = [n for n in os.listdir(path) if pat.search(n)] [__import__(name.rspit('.')) for name in files] for possible_dir in os.listdir(path): try: if True in [init_pat.match(n) for n in os.listdir(name + '/' + possible_dir): find_modules(str_pat) except OSError: #does os.listdir raise this? pass From aleax at mail.comcast.net Tue Nov 22 22:12:07 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 22 Nov 2005 19:12:07 -0800 Subject: Why are there no ordered dictionaries? References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> Message-ID: <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> Tom Anderson wrote: ... > > have a certain order that is preserved). Those who suggested that the > > "sorted" function would be helpful probably thought of a "sorted > > dictionary" rather than an "ordered dictionary." > > Exactly. > > Python could also do with a sorted dict, like binary tree or something, > but that's another story. However, since Christoph himself just misclassified C++'s std::map as "ordered" (it would be "sorted" in this new terminology he's now introducing), it seems obvious that the terminological confusion is rife. Many requests and offers in the past for "ordered dictionaries" (e.g. on this group) were also "sorted", NOT "ordered", in this new terminology. Maybe it would therefore be clearer to have the name of the new container reflect this, with a specific mention of *insertion* order... rather than just call it "ordered" and risk probable confusion. Alex From deets at nospam.web.de Wed Nov 9 16:42:01 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Nov 2005 22:42:01 +0100 Subject: Cursor Position. In-Reply-To: References: <3tds08Fsb3p1U1@uni-berlin.de> Message-ID: <3tf8paFsfgb8U1@uni-berlin.de> > That is my exact problem. I want to have the mouse event captured from > another application window. In this case an image window opened in Paint > Shop Pro that by the way uses Python to make scripts. I would like to be > able to click on the image and get the X,Y positions. I have been able to > get the X,Y from Tkinter own window as you say. Once I have those positions > I can use them in a Paint Shop Pro script. > Thanks for your reply. Do you have any advise as to how I can do what I am > trying or is it, in a practical matter, impossible. As I said - it certainly is doable. But I fear not in tkinter "as is" (you can use tk still for your _own_ gui), and not without deeper knowledge of the windows event system. Then mark hammond's win32 extensions are a starting point. And you should search for example code on MSDN or something like that (obviously _not_ in python), to get a starting point. Regards, Diez From fredrik at pythonware.com Fri Nov 11 17:51:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 23:51:36 +0100 Subject: directory listing References: <14cltzqwyklwl.17i7f7qnfnlh0$.dlg@40tude.net><192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu><1d987df30511111423o572172eay36870d09220233d7@mail.gmail.com> <1d987df30511111444m1ddfaca2qcf0acc32e49fc108@mail.gmail.com> Message-ID: "Shi Mu" wrote: > but i am curious why the line of "print x" does not show > anything. because your c:\temp directory is empty ? From mwm at mired.org Thu Nov 24 03:47:47 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 03:47:47 -0500 Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> Message-ID: <868xvezb2k.fsf@bhuda.mired.org> "Giovanni Bajo" writes: > Mike Meyer wrote: >> Note that this property of __slots__ is an implementation detail. You >> can't rely on it working in the future. > I don't "rely" on it. I just want to catch bugs in my code. I certainly hope you're not relying on it to catch bugs. You should do proper testing instead. Not only will that catch pretty much all the bugs you mention later - thus resolving you of the need to handcuff clients of your class - it will catch lots of other bugs as well. >> I'm curious as to why you care if people add attributes to your >> "immutable" class. Personally, I consider that instances of types >> don't let me add attributes to be a wart. > To catch stupid bugs, typos and whatnot. If an instance is immutable, you can't > modify it, period. If you do it, it's a bug. So why not have the bug raises an > exception, rather than go unnoticed? It's only a bug if you didn't mean to do it. If you meant to do it, you're taking advantage of a powerful feature of Python. If you feel the need to restrict the use of such features, maybe you should consider a less powerful language? There are lots of languages around that prevent accidental creation of attributes - and lots of other similar usages that are bugs if you don't mean to do them. > I don't see your point, either. Why would you want to add attributes to an > object documented to be immutable? The documentation is immaterial. The *need* is what's important. I've had use cases were some object was almost exactly what I wanted, except I needed another bit of data dragged along. Python lets me do that for most classes, which is one of the things that I like about it - it doesn't handcuff me. > >> If it's not a wart, why would it be a wart for user-defined types to > >> have the same behaviour? > > > > It's a wart because user-defined classes *don't* have the same > > behavior. > Then *my* solution for this would be to give user-defined classes a way to > behave like builtins, eg. explicitally and fully implement immutability. Well, if you want to propose a change to the language, you need a good use case to demonstrate the benefits of such a change. Do you have such a use case? Catching bugs doesn't qualify, otherwise Python would be radically different from what it is. > Immutability is an important concept in Python programs, and I'm impressed it > does not have explicit support. I'm not convinced that immutability is that important a concept. Yeah, you have to know about it, but it seems more like an implementation detail than a crucial concept. I'm not sure it's more important than things like interned strings and the sharing of small integers. Most of the discussion of immutables here seems to be caused by newcomers wanting to copy an idiom from another language which doesn't have immutable variables. Their real problem is usually with binding, not immutability. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From davidb at mcs.st-and.ac.uk Thu Nov 17 18:43:52 2005 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 17 Nov 2005 15:43:52 -0800 Subject: PyQt layout question: QScrollView and QGridLayout? References: <3u3jq1Fv4h36U1@news.dfncis.de> <3u44d4Fvb1uaU1@news.dfncis.de> Message-ID: <1132271032.388083.107230@g49g2000cwa.googlegroups.com> Volker Lenhardt wrote: > Phil Thompson schrieb: > > On Thursday 17 November 2005 2:56 pm, Volker Lenhardt wrote: [Using a QGridLayout in a QScrollView] > >>Is there a way to get it to work? Filling a box viewport with lots of > >>padding boxes and white space labels to establish grids is very > >>cumbersome. And I need 4 different layouts to change places. > > > > QGridLayout is not a sub-class of QWidget, which is what addChild() is > > expecting. You probably want QGrid. > > I hoped to find a more assuring answer. There's no MultiCellWidget, no > Col/RowStretching, no Col/RowSpacing in QGrid. I've got to patch up one > VBox with a whole bunch of QV/QHBoxes and QGrids not to mention the > white space QLabels to fill not used grid cells. You can still use QGridLayout, but you need to put a widget into the QScrollView in what the documentation describes as "Using One Big Widget" (http://doc.trolltech.com/3.3/qscrollview.html). Something along these lines should do basically what you want: sv = QScrollView() w = QWidget(sv.viewport()) sv.addChild(w) grid = QGridLayout(w, 3, 3) for i in range(0,3): for j in range(0,3): grid.addWidget(QLabel("(%i,%i)" % (i,j), w), i, j) Of course, the widget that contains the layout is only as large as it needs to be, so you may need to call its setMinimumSize() method if you want it to be larger. However, it's often a better idea to ensure that the child widgets have the sizes they need - their parent will then be as large as they require. Hope this helps, David From sverker.is at home.se Tue Nov 29 14:53:31 2005 From: sverker.is at home.se (Sverker Nilsson) Date: 29 Nov 2005 11:53:31 -0800 Subject: Compiling Guppy-PE extension modules Message-ID: <1133294011.245923.218130@z14g2000cwz.googlegroups.com> I have been informed that Guppy-PE (http://guppy-pe.sourceforge.net) has failed to compile its extension modules with a Microsoft .NET 2003 compiler under Windows 2000. [To the person who informed me about this in an email per 27 Nov: Thanks for your message. I couldn't reply to you because your email address bounced my mail.] One of the problems, seems to be string constants in the C source that contain newlines. I am using GCC on Linux so, I missed this with the standard warning options. Compiling with -pedantic reveals 'a lot' of places where this is a problem. I could fix this but it takes some work and it makes the source code less readable so I was wondering ... Is this a common problem? Or maybe it is just the compiler version mentioned that doesn't handle it? Does someone know of some switch to enable the Microsoft compiler to accept strings with newlines? If so, the setup could perhaps be made to pass this switch to the compiler when building under Windows. Or else,.. somebody knows about a script to convert the files to the format the Microsoft compiler wants? I guess the build compilation could then be setup to pipe them through this or otherwise convert the files as needed. Otherwise, I guess I'll just have to hand-hack around this problem, write a conversion script, or whatever. I will see. Sorry for any inconvenience so far. Regards, Sverker Nilsson PS. I know it's not ANSI-correct but why do we have to work to make our source codes less clear? From http Fri Nov 11 11:08:12 2005 From: http (Paul Rubin) Date: 11 Nov 2005 08:08:12 -0800 Subject: LARGE numbers References: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> <1131691903.961955.19950@o13g2000cwo.googlegroups.com> <1h5uqy3.sdzwkkuvu86mN%aleax@mail.comcast.net> Message-ID: <7xmzkbkw0j.fsf@ruckus.brouhaha.com> aleax at mail.comcast.net (Alex Martelli) writes: > As the author of gmpy, I'd like to point out that the speed difference > isn't all that large, if all you're doing is ordinary arithmetic -- a > few times at most (it can be better if you need some of GMP's > functionality which gmpy exposes, such as primality testing). For numbers of this size, won't gmpy use FFT-based multiplication? That's potentially orders of magnitude faster than ordinary n**2 multiplication. From pythonnew at gmail.com Sun Nov 13 01:25:55 2005 From: pythonnew at gmail.com (Ben Bush) Date: Sat, 12 Nov 2005 22:25:55 -0800 Subject: circle and point In-Reply-To: References: <8c11e4350511122051hc4ae8b9tc4ef54818ba44318@mail.gmail.com> Message-ID: <8c11e4350511122225i3da55c82gbbd8ed2267bc0a38@mail.gmail.com> On 11/12/05, Robert Kern wrote: > > Ben Bush wrote: > > is there any code to decide whether a point is located within the circle > > by three other points? > > # Converted from my C++ code. > # C.f. http://www.ics.uci.edu/~eppstein/junkyard/circumcenter.html > def circumcenter(x0, y0, > x1, y1, > x2, y2): > x0m2 = x0 - x2 > y1m2 = y1 - y2 > x1m2 = x1 - x2 > y0m2 = y0 - y2 > x0p2 = x0 + x2 > y1p2 = y1 + y2 > x1p2 = x1 + x2 > y0p2 = y0 + y2 > > D = x0m2*y1m2 - x1m2*y0m2 > # You probably want to test for D being close to 0 here > > centerx = (((x0m2*x0p2 + y0m2*y0p2)/2*y1m2) > - (x1m2*x1p2 + y1m2*y1p2)/2*y0m2) / D > centery = (((x1m2*x1p2 + y1m2*y1p2)/2*x0m2) > - (x0m2*x0p2 + y0m2*y0p2)/2*x1m2) / D > > return centerx, centery > > def incircle(x0, y0, > x1, y1, > x2, y2, > x, y): > centerx, centery = circumcenter(x0, y0, x1, y1, x2, y2) > return ((x-centerx)**2 + (y-centery)**2 <= > (x0-centerx)**2 + (y0-centery)**2) > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > > Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From p.c.j.kleiweg at rug.nl Wed Nov 16 13:37:09 2005 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Wed, 16 Nov 2005 19:37:09 +0100 Subject: Quitting a Tkinter application with confirmation Message-ID: I have an application written in Tkinter. There is a menu item 'quit' that calls the function 'quit'. If 'quit' is called, it first checks if there is unsaved data. If there is, it won't let the application exit unless you confirm to disregard the changes. So far, so good. I want the program to behave identical if the 'close' button of the application window is clicked. I tried the code below, using a class derived from Tk that redefines the destroy method. That seems to work. At least on Linux. My questions: Is this the correct and save way to do this? Will it work on any operating system? Shouldn't I do some event capturing instead? (Capture the SIGTERM or SIGQUIT, sent by the Window manager to the application.) from Tkinter import * import tkMessageBox def quit(): if not changes: root.quit() else: if tkMessageBox.askyesno(_('Quit'), _('Project is not saved. Ignore changes and quit?')): root.quit() class myTk(Tk): def destroy(self): quit() root = myTk() -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From hancock at anansispaceworks.com Thu Nov 17 14:52:21 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 17 Nov 2005 13:52:21 -0600 Subject: how to organize a module that requires a data file In-Reply-To: References: Message-ID: <20051117135221.16a63230@samwise.anansi> On Thu, 17 Nov 2005 12:18:51 -0700 Steven Bethard wrote: > My problem is with the text file. Where should I keep it? > > I can only think of a few obvious places where I could > find the text file at import time -- in the same > directory as the module (e.g. lib/site-packages), in the > user's home directory, or in a directory indicated by an > environment variable. Why don't you search those places in order for it? Check ~/.mymod/myfile, then /etc/mymod/myfile, then /lib/site-packages/mymod/myfile or whatever. It won't take long, just do the existence checks on import of the module. If you don't find it after checking those places, *then* raise an exception. You don't say what this data file is or whether it is subject to change or customization. If it is, then there is a real justification for this approach, because an individual user might want to shadow the system install with his own version of the data. That's pretty typical behavior for configuration files on any Posix system. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From bokr at oz.net Mon Nov 21 18:32:55 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 21 Nov 2005 23:32:55 GMT Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <43814BB8.9060206@REMOVEMEcyber.com.au> Message-ID: <4382591f.411379051@news.oz.net> On Mon, 21 Nov 2005 15:23:20 +1100, Steven D'Aprano wrote: >David (Alan) Isaac wrote: > >> What's the good way to produce a cumulative sum? >> E.g., given the list x, >> cumx = x[:] >> for i in range(1,len(x)): >> cumx[i] = cumx[i]+cumx[i-1] >> >> What's the better way? > >Is there something that this doesn't do, or something >it does do that it shouldn't? > >You could do it this way: > ># untested >def cumulative_sum(L): > CL = [] > csum = 0 > for x in L: > csum += x > CL.append(csum) > return CL > >Whether it is better or worse depends on what you >consider better or worse. I think x[:] ought to be a faster space allocation than building by appending, but I think there is too much indexing in the OP's version, so I think I would combine ideas, e.g., # (still ;-) untested def cumulative_sum(L): CL = L[:] csum = 0 for i, x in enumerate(L): csum += x CL[i] = csum return CL I minor nit might be in how/when promotions to long or float happen if L has mixed types. The OP didn't mention any requirements, but e.g. his version won't ever promote the first output element, since he walks replacements from L[1] on. ( posting delayed >12 hrs due to news server prob ;-/ ) Regards, Bengt Richter From frithiof.jensen at die_spammer_die.ericsson.com Wed Nov 9 07:35:57 2005 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 9 Nov 2005 13:35:57 +0100 Subject: python server References: <1131387737.953307.178470@g44g2000cwa.googlegroups.com> Message-ID: "Magnus Lycka" wrote in message news:dkpne7$h5e$1 at wake.carmen.se... > Thee are many solutions. An XML-RPC server springs to mind as a > solution. There are several Python XML-RPC servers ..... Good Idea. Seems that those particular batteries are included with Python 2.2 and up: OP: See help on: "SimpleXMLRPCServer" and "xmlrpclib" From onurb at xiludom.gro Thu Nov 10 08:14:19 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 10 Nov 2005 14:14:19 +0100 Subject: What do you use as symbols for Python ? In-Reply-To: <4372f88a$0$31833$636a15ce@news.free.fr> References: <4372f88a$0$31833$636a15ce@news.free.fr> Message-ID: <437347ad$0$21696$626a54ce@news.free.fr> Pierre Barbier de Reuille wrote: > When you need some symbols in your program, what do you use in Python ? > > For example, an object get a state. This state is more readable if > expressed as a symbols, for example "opened", "closed", "error". > Typically, in C or C++, I would use an enum for that: > enum OBJECT_STATE > { > opened, closed, error > } > > In CAML or Haskell I would use the union types: > > type ObjectState = Opened | Closed | Error > > In Ruby I would use the symbols : > > object.state = :opened > object.state = :closed > object.state = :error > > ... but I don't know what to use in Python ! Depends on the job... If I need to do bitmask operations, I'll use integer flags. If I want the symbol to be human-readable, I'll use strings. But everything in Python being an object, you can use whatever seems appropriate.... Since we're in a 'state' exemple, here's a possible state pattern implementation: class MyObject(object): def __init__(self, name): self.name = name self.__class__ = ClosedState state = property(fget=lambda self: self.__class__) def open(self, arg): if arg == 1: self.__class__ = OpenedState else: self.__class__ = ErrorState def close(self): self.__class__ = ClosedState class OpenedState(MyObject):pass class ClosedState(MyObject):pass class ErrorState(MyObject):pass m = MyObject('toto') assert m.state is ClosedState m.open(1) assert m.state is OpenedState m.close() assert m.state is ClosedState m.open(2) assert m.state is ErrorState I made states 'dummy' objects, but you could make this a real state pattern implementation by defining default methods in the base class and overriding appropriate methods in the 'state' subclasses. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From radek_ne at tlen.pl Thu Nov 24 05:07:19 2005 From: radek_ne at tlen.pl (radek_ne at tlen.pl) Date: Thu, 24 Nov 2005 11:07:19 +0100 Subject: =?iso-8859-2?Q?Problem_with_HtmlWindow_and_Widgets?= Message-ID: <20051124100719.7868E38012@rekin11.go2.pl> Hello I have problem with HtmlWindow and Widgets (wxPython). When I put on HtmlWindow TextCtrl all is ok, but when I try to use ComboBox then all controls not refresh. Where is problem? Thenks for help and sorry for my english ;) From steve at REMOVETHIScyber.com.au Fri Nov 25 21:14:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 26 Nov 2005 13:14:07 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <1132841680.454026.203420@z14g2000cwz.googlegroups.com> <11ocu1og1660965@corp.supernews.com> Message-ID: On Fri, 25 Nov 2005 02:34:32 +0000, Ed Jensen wrote: > Because I think a lot of well meaning software developers writing free > software don't performance due diligence to determine the true > motivation behind, and the chilling effect of, the GPL. It took me seconds, seconds I say, to open a web browser and google for "gpl" and discover www.gnu.org/copyleft/gpl.html And such chilling effects they are too! Why, if I use GPLed software, I'm forced to, er, um, well actually I'm not forced to do anything if I merely use GPLed software. I'm not forced to pay a licence fee. I'm not forced to maintain licences at great cost to myself. I'm not forced to get their permission before publishing benchmarks. I'm not forced to open up the rest of my source code to others. I'm not forced to redistribute the program to others. I'm not forced to contribute source code back to the developers. I'm not forced to allow the BSA to audit my software if they ask. I'm not even forced to send the developers a post card telling them how much I love their work. And if I *choose* of my own free will to redistribute that GPLed work, or a derivative work of such, the only restriction is that I may not take away rights granted to me from those I redistribute to. I'm not even forced to give the software away for free -- I am free to charge as much or as little as I wish, so long as I don't charge extra for the source code (excepting reasonable distribution costs of shipping extra media). Such chilling effects. That explains why Linux and other GPLed software has languished in obscurity over the last decade, while companies like IBM, Novell and Red Hat have flocked to support the much older BSD-licenced code. Yes, no wonder you hate the GPL, with all those chilling effects. -- Steven. From bonono at gmail.com Wed Nov 30 23:34:23 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 30 Nov 2005 20:34:23 -0800 Subject: Making immutable instances In-Reply-To: <86zmnll9z3.fsf@bhuda.mired.org> References: <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> <86u0duodzl.fsf@bhuda.mired.org> <1133333467.677454.134110@g49g2000cwa.googlegroups.com> <86acfloox6.fsf@bhuda.mired.org> <1133402729.430608.21400@g43g2000cwa.googlegroups.com> <86fypdmpi5.fsf@bhuda.mired.org> <1133410318.274544.326740@g47g2000cwa.googlegroups.com> <86zmnll9z3.fsf@bhuda.mired.org> Message-ID: <1133411663.611989.310590@g44g2000cwa.googlegroups.com> Mike Meyer wrote: > > If the authors go to the length of not allowing it, so be it. They > > are afterall define it for their use and how someone else will use > > it don't matter. > > I take it you never distribute your code, or otherwise expect other > people to reuse it? > No, distribute when necessary. But I define it and code it the way I want, how and others will use it, curse it doesn't matter to me. Of course, I would give suggestion(wish list bug as in debian term) when I use other people's stuff, and see a particular usage that is not there. But it ends just there, wish list. From metiu.uitem at gmail.com Fri Nov 25 04:05:28 2005 From: metiu.uitem at gmail.com (metiu) Date: 25 Nov 2005 01:05:28 -0800 Subject: Guification of console app References: <1132871970.821787.204830@g14g2000cwa.googlegroups.com> Message-ID: <1132909528.263090.326890@g47g2000cwa.googlegroups.com> Yes, I'll try to give you an example: you have a compression utility that works as a standard *nix filter, so it takes something from stdin and gives it back compressed to stdout you like to use it as such, because it's nice to call it from the command line now someone finds your utility quite nice, and says it would be nice to have a GUI that shows you, for example, how long it will take to compress... one way for sure it would be to fork your app, but this would be a waste of time you'd like to reuse the compression library you've already written for your GUI and your console, but: - you'd like to have your console app clean and simple, such as: import sys import CompressLib data = sys.stdin.read() cdata = CompressLib.compress(data) print cdata but you'd like the GUI to show some progress and status info. I guess the way is still to make the compress call split in microsteps and have the app call it, so you can use an EVT_IDLE call from the GUI, but maybe there's a better way... Thanks again Peter Hansen ha scritto: > metiu wrote: > > Say I have a console app that does something in three steps: > > - opens a file > > - transfers the file through a serial port > > - does some elaborations > > > > and I want to build a GUI around it that, for example, sets the file > > name to open or starts the different steps. > > > > I started using wxPython (actually boa-constructor) to build a frame > > with everything I want. > > The problem is: when the console app method is working, the GUI is > > locked... > > > > How can the console app communicate with the GUI in order to make it > > tick (think of status messages, progress bars, log messages...)? > > If I use threads and events, or wxYield, or EVT_IDLE, I'm tweaking the > > console app so that it won't work just in console anymore. > > Could you please explain what makes this a "console" app, specifically? > You are proposing wrapping a GUI around it, which would make it not a > console app (by definition), so it would help if you specified exactly > what elements (which functions, etc.) cause you to label it a "console" > app. (For example, maybe it calls msvcrt.kbhit/getch or something...) > > The reason for asking is that the specifics of your answer will make it > easier to describe how to modify this "console" so that the relevant > parts work equally well as a _real_ console app (no GUI) or with the > GUI. We could describe it in more general terms, but it might not be > apparent how to adapt that to your own case. > > -Peter From mwm at mired.org Mon Nov 7 17:17:44 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 07 Nov 2005 17:17:44 -0500 Subject: Web automation References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> <1131397945.832762.71070@g47g2000cwa.googlegroups.com> Message-ID: <86k6fk9k6v.fsf@bhuda.mired.org> qwweeeit at yahoo.it writes: > but I supposed the everyone knew that web automation (and in general > "automation") is only a problem in Linux. I don't know it. I don't believe it, either. I automate web tasks on Unix systems (I don't use many Linux systems, but it's the same tool set) on a regular basis. In fact, I automate *lots* of tasks on Unix systems on a regular basis, and have been doing it for decades. Most Unix tools are very amenable to automation, much more so than I've found either Windows or OS X tools to be. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From cookiecandyred at yahoo.com Sat Nov 5 17:52:00 2005 From: cookiecandyred at yahoo.com (Little) Date: 5 Nov 2005 14:52:00 -0800 Subject: mod_python Message-ID: <1131231120.914632.17790@g44g2000cwa.googlegroups.com> I can't figure out how to build this type of program using the publisher handler. I have the following connected to the program SetHandler python-program PythonHandler mod_python.publisher PythonDebug On But what I would like to do would be have a german word as the parameter in the HTTP request and have the english world printed out on the screen. Yes this will be a small dictionary but I just want to be able to understand how to build the program and have it work without any errors. Thanks for any help. PS I understand the example of printing the say portion in the mod_python manual but can't get past that. Again Thanks!! From nospam at please.net Wed Nov 16 20:19:33 2005 From: nospam at please.net (Todd7) Date: Thu, 17 Nov 2005 01:19:33 GMT Subject: Newbie wxPython ListCtrl Question References: Message-ID: Thank you very much. That is exactly what I needed. limodou wrote in news:mailman.773.1132189602.18701.python-list at python.org: > 2005/11/17, Todd7 : >> I am new to python and to wxWindows. I have tried searching google, >> reading the documentation and trying to figure out some of the >> examples, but I am stumped as to how to get information out of a >> listctrl at a certain row and column. I tried to write a simple >> example to learn to work with the listctrl as follows: > > I'v made some helper function as that: > > def getRowText(self, index, col): > if index >= 0: > return self.list_ctrl_1.GetItem(index, col).GetText() > else: > return '' > > def getSelRowText(self, col): > return self.getRowText(self.getSelection(), col) > > def getSelection(self): > return self.list_ctrl_1.GetNextItem(-1, wx.LIST_NEXT_ALL, > wx.LIST_STATE_SELECTED) > > You can just use self.getSelRowText(1) to gain the second column text > of selection row. > -- > I like python! > My Blog: http://www.donews.net/limodou > NewEdit Maillist: http://groups.google.com/group/NewEdit > From fgeiger at datec.at Fri Nov 18 05:05:10 2005 From: fgeiger at datec.at (F. GEIGER) Date: Fri, 18 Nov 2005 11:05:10 +0100 Subject: nanothreads: Want to use them from within wxPython app Message-ID: I've def'ed a handler for EVT_IDLE in the app's main frame. There I'd like to call the nanothreads' __iter__ method, somehow. When I copy the __iter__ method into a, say, runOnce() method and call the next() method of the generator returned by runOnce(), it works. But I can't get at the __iter__ method, which is already there and therefore should be used instead of messing up nanothreads with changes of mine. Any hint welcome Kind regards Franz GEIGER From mwm at mired.org Mon Nov 28 07:09:48 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 28 Nov 2005 07:09:48 -0500 Subject: type of form field References: <1133176003.342838.85460@g14g2000cwa.googlegroups.com> Message-ID: <86slthug6r.fsf@bhuda.mired.org> "Ajar" writes: > Is there any way to retrieve the type(checkbox,radio...) of the form > field from cgi.FieldStorage. I tried something like form['name'].type, > but this field seems to be None for all the form fields There isn't. cgi.FieldStorage parses data sent via an HTTP request. The type of the input element isn't part of the data sent in an HTTP request. So not only is there no way to get it from cgi.FieldStorage, there's no way to get it from any HTTP handling facility, unless it gets stored somewhere outside the element in question for you to retrieve. While you do have to store it outside the element, you don't have to store it outside the form. You could create a series of hidden input elements with names "foo.type" whose value was the type of the element foo. If your pages are dynamically generated, you could create a dictionary mapping element names -> types, and then pickle that and store the results in a hidden element. Or - well, I'm sure you get the idea. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From anton.vredegoor at gmail.com Sat Nov 19 08:13:58 2005 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 19 Nov 2005 05:13:58 -0800 Subject: Python obfuscation In-Reply-To: <1h67rkl.1rkx0mm1hpdql9N%aleax@mail.comcast.net> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> <1132249511.886027.93990@g14g2000cwa.googlegroups.com> <1h662eo.95qjyvd1bcnuN%aleax@mail.comcast.net> <437d0b86.63834689@news.oz.net> <1132325798.806457.91170@g47g2000cwa.googlegroups.com> <1h67rkl.1rkx0mm1hpdql9N%aleax@mail.comcast.net> Message-ID: <1132406038.650352.323390@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > Money is made in many ways, essentially by creating (perceived) buyer > advantage and capturing some part of it -- but market segmentation is > just one of many ways. IF your predictions are ENORMOUSLY better than > those the competition can make, then offering for free "slightly > damaged" predictions, that are still better than the competition's > despite the damage, MIGHT be a way to market your wares -- under a lot > of other assumptions, e.g., that there is actual demand for the best > predictions you can make, the ones you get paid for, so that your free > service doesn't undermine your for-pay one. It just seems unlikely that > all of these preconditions would be satisfied at the same time; better > to limit your "free" predictions along other axes, such as duration or > location, which doesn't require your predictions' accuracy advantage to > be ENORMOUS _and_ gives you a lot of control on "usefulness" of what > you're supplying for free -- damaging the quality by randomization just > seems to be unlikely to be the optimal strategy here, even if you had > determined (or were willing to bet the firm that) marked segmentation is > really the way to go here. Suppose I grant all your theories about optimal marketing strategies. This still doesn't account for the way the market is behaving *now*. It isn't in any way logical or optimal. For example in Holland (where I live) complete governmental departments are dedicated to make life miserable for the unemployed, for asylum seekers, for people that disagree with any official policy. If looking at the recent developments in France I find it hard to believe that such social inequality an injustice develops naturally. To me it looks more like it's caused by organized crime, where *official* legal governmental organizations are either crimimal organizations themselves or are cooperating with such organizations. You seem to tackle the problem of python obfuscation by first proving that it isn't feasible and then giving some kind of solution that will work and give the desired result: webservices. However when I look at obfuscation techniques I see a desire to profit from giving some person the idea that he or she is superior to someone else because he has a better product. In order to avoid copying we now need obfuscation. The difficulty to copy the thing (whether it is a swiss watch, a sportscar, designer clothes, the latest computer game, an ipod, a computer program) is part of the advertising game and is the basis for associating it with a certain status. If you look for a few minutes at a TV screen and notice what the commercials are trying to tell you, you will see that it's almost always that you will be better, stronger, more popular or beautyfull etc. if only you use product X. You are perfectly right if you would say that it is an illogical strategy to make people feel better relative to other people in order to get them to do something you want. Commercial entities could in principle be free of such things but we live in a world that is dominated by this worldview and if one tries to sell something one has to take that into account. So how to get the same kind of market segmentation (as you call it) when you deploy your program as a webservice and where essentially the cost for you (moving a few electrons to produce a solution to a problem) is exactly the same whether you give the user a good or a bad result. If you give optimal results to everyone, users will go to other sites just because these sites give them opportunity to feel better than other people, not because this is objectively better, but just because that is how they think the world "works". > I hope this analogy clarifies why, while I don't think deliberate damage > of result quality can be entirely ruled out, I think it's extremely > unlikely to make any sense compared to ofher market segmentation > tactics, even if you DO grant that it's worth segmenting (free samples > are an extremely ancient and traditional tactic in all kind of food > selling situations, after all, and when well-designed and promoting a > product whose taste is indeed worth a premium price, they have been > repeatedly shown to be potentially quite effective -- so, I'm hoping > there will be no debate that the segmentation might perfectly well be > appropriate for this "analogy" case, whether it is or isn't in the > originally discussed case of selling predictions-via-webservices). I agree it doesn't make sense. Like uncle Harry who thinks he can lay golden eggs. We could cure him but we need the egss :-) Alternatively, lets just forget about obfuscation and try to get people to freely share by promoting open source (and open webservices). Anton From fredrik at pythonware.com Tue Nov 22 05:03:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 11:03:20 +0100 Subject: How to paste python code on wordpress? References: <311b5ce10511211717q1d1cd6e7hd622c16d0f725745@mail.gmail.com><79021162-F73D-44DC-B621-1CE24E14F453@tangledhelix.com><311b5ce10511212130t68f4e562g298610fae121edb7@mail.gmail.com> Message-ID: Dan Lowe wrote > Replace < with < > > Replace > with > > > (where those abbreviations stand for "less than" and "greater than") > > Before: if x < 5: > > After: if x < 5: > > Another common character in code that you "should" do similarly is > the double quote ("). For that, use " > > Before: if x == "foo": > > After: if x == "foo": footnote: stricly speaking, > is a "should" as well (it only has special meaning in an open tag). and " is a "may" (it only has special meaning in attributes quoted by double quotes). the same applies to ' (') if you're escaping by hand, you usually only need to care about & and <. if you're using code to do the escaping, you might as well escape all give (< > & " '). From fredrik at pythonware.com Wed Nov 16 17:10:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 23:10:51 +0100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com><1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > This means we're no longer assuming what the error message will be, > which makes our code a lot more future-proof and implementation-proof: if > some version of Python changes the error string from "iteration over > non-sequence" to something else, the code should continue to work > correctly. Alex has already posted the right way to do this. can you please stop From sjdevnull at yahoo.com Wed Nov 16 17:20:12 2005 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 Nov 2005 14:20:12 -0800 Subject: running functions In-Reply-To: References: Message-ID: <1132179612.759373.130900@g43g2000cwa.googlegroups.com> Gorlon the Impossible wrote: > Hello > I'm not sure how to phrase this question. I have a Python function > that sends MIDI messages to a synth. When I run it, I of course have > to wait until it is finished before I can do anything else with > Python. Is it possible to run this function and still be able to do > other things with Python while it is running? Is that what threading > is about? Threading's a good answer if you really need to share all your memory. A multiprocess solution is probably preferrable, though it depends on the architecture. It may be possible to do it in a single process (if, say, the MIDI synth supports waitForMultipleObjects, select, async I/O, or an equivalent thereof) without blocking. From universal_used at hotmail.com Thu Nov 3 13:19:04 2005 From: universal_used at hotmail.com (questions?) Date: 3 Nov 2005 10:19:04 -0800 Subject: random number generator Message-ID: <1131041944.218053.16400@z14g2000cwz.googlegroups.com> How to generate a random number in Python. Is there any build in function I can call? Thanks From ziga.seilnacht at gmail.com Tue Nov 1 21:17:57 2005 From: ziga.seilnacht at gmail.com (ziga.seilnacht at gmail.com) Date: 1 Nov 2005 18:17:57 -0800 Subject: Problems with emulation of numeric types and coercion rules In-Reply-To: <1130887240.155333.112920@o13g2000cwo.googlegroups.com> References: <1130887240.155333.112920@o13g2000cwo.googlegroups.com> Message-ID: <1130897877.779567.322900@g49g2000cwa.googlegroups.com> Never mind, I forgot that class inheritance tree is a tree. Resulting type of adding Broken and Working from previous example would also depend on the order of operands. Ziga From bajwa_yasir at yahoo.ca Mon Nov 14 11:54:18 2005 From: bajwa_yasir at yahoo.ca (yb) Date: 14 Nov 2005 08:54:18 -0800 Subject: mp3 wav editing in python Message-ID: <1131987258.719059.15890@g47g2000cwa.googlegroups.com> Hi, Is there a python based tool to cut mp3 and wav file at a start and end time? I'm looking for a python script that can output a new wav or mp3 file based on star and endpoint. Thank you From http Tue Nov 8 18:37:26 2005 From: http (Paul Rubin) Date: 08 Nov 2005 15:37:26 -0800 Subject: random number generator thread safety References: <1131491545.398104.168110@z14g2000cwz.googlegroups.com> Message-ID: <7xirv2btjd.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > Thread-safety has nothing to do with preserving entropy or guarding > against attack. All of the entropy in an MT sequence is contained in > the seed (upto 624 bytes) and that entropy is preserved through all > subsequent calls. I think the concern is that there can be a thread switch after some intermediate result is computed but before the state is updated. That would mean two threads can get random numbers that are identical or anyway correlated. Whether that can happen with Python's MT, I don't know. > Nothing in the random module provides cryptographic guarantees. If you > want crypto-strength, then use real encryption. Search SourceForge for > patches that show how to use MD5 and other cryptographic hash functions > as a basis for random number generation. Or use os.urandom. From fredrik at pythonware.com Wed Nov 2 15:23:29 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Nov 2005 21:23:29 +0100 Subject: reading internet data to generate random numbers. References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: >> Hi, I'm working on a random number generator using the internet as a >> way to gather entropy, I have two questions. >> >> 1. is there a way to capture the internet stream? > > What specifically do you mean by the term "internet stream" here? > Generally speaking, the internet is not "streamed" at all, but perhaps > you have some special meaning in mind that isn't in general use. maybe it's something like this he's looking for: http://sourceforge.net/projects/pylibpcap/ From bignose+hates-spam at benfinney.id.au Sun Nov 13 08:50:51 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Nov 2005 00:50:51 +1100 (EST) Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> Message-ID: Pierre Barbier de Reuille wrote: > Mike Meyer a ?crit : > > Hmm. You know, $symbol$ doesn't seem nearly as bad as $symbol. It > > tickles TeX, not P***. I could live with that. > Yep, I like this $symbol$ notation ! Gets a big -1 here. I've yet to see a convincing argument against simply assigning values to names, then using those names. -- \ "Yesterday I parked my car in a tow-away zone. When I came back | `\ the entire area was missing." -- Steven Wright | _o__) | Ben Finney From codecraig at gmail.com Mon Nov 14 10:23:14 2005 From: codecraig at gmail.com (py) Date: 14 Nov 2005 07:23:14 -0800 Subject: screen capture Message-ID: <1131981794.231399.275940@f14g2000cwb.googlegroups.com> I need to take a screen shot of the computer screen. I am trying to use PIL and I saw there is ImageGrab...however it only works on Windows. Is there a platform-independent ability to work around this? thanks From samrobertsmith at gmail.com Sun Nov 20 08:19:08 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 05:19:08 -0800 Subject: about dictionary In-Reply-To: References: Message-ID: <1d987df30511200519i462e2bf3od81ef0b1831d81f@mail.gmail.com> On 11/20/05, przemek drochomirecki wrote: > > Uzytkownik "Peter Otten" <__peter__ at web.de> napisal w wiadomosci > news:dlppk4$f0v$00$1 at news.t-online.com... > > Shi Mu wrote: > > > > > how to do with it? > > > > Use Ben Finney's, not Przemek's approach if the values are mutables that > you > > plan to modify. If that's what you are asking. > > > > Peter > > Maybe he just want to use dictionary as a set. > He can use SET container instead. > > Przemek How to use SET? From noah at noah.org Thu Nov 3 20:26:14 2005 From: noah at noah.org (Noah) Date: 3 Nov 2005 17:26:14 -0800 Subject: How can I package a python script and modules into a single script? In-Reply-To: <3bmd220k.fsf@python.net> References: <1131030933.425241.142800@o13g2000cwo.googlegroups.com> <3bmd220k.fsf@python.net> Message-ID: <1131067574.703237.60610@f14g2000cwb.googlegroups.com> Bingo! That is what I was thinking of. http://effbot.org/zone/squeeze.htm It turns out that it doesn't quite do what I want because the resulting script is tightly coupled to the version of Python used to build the package. It compiles the PYC byte-code into the package. It's neat and I may be able to use the ideas to do what I want. Yours, Noah From peter at engcorp.com Mon Nov 28 08:04:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 28 Nov 2005 08:04:57 -0500 Subject: Comparison problem In-Reply-To: <1133155193.939460.65060@g47g2000cwa.googlegroups.com> References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> <1133155193.939460.65060@g47g2000cwa.googlegroups.com> Message-ID: Tim Henderson wrote: > peter (Thanks for clarifying to whom you were responding... I saw the other post but wouldn't have responded since it didn't seem to be in response to one of mine. :-) ) > would not the more correct way to do this be short circuit > evaluation. somthing along lines of > > if (len(item) > 0) and (item[0] == '-'): pass This is "correct" only in a narrow sense. I wouldn't call it "correct Python" if I saw it in code around here. Most likely (since this always depends on context), I would replace it with this: if item and item[0] == '-': pass I think it's probably unlikely that the first test would be needed only on that one line, so it's even more likely that "if item" test would be done first, by itself, and then other tests on item[0] would be done. If this was code that needed high performance (i.e. had been detected with proper profiling as a serious bottleneck) then the slicing approach would be better (as Fredrik demonstrated). Hmm... just realized we're going way off track, since we actually have the original code here and don't need to comment on hypotheticals. It appears to me that the original input is being treated as some sort of fixed-length record, with certain characters and text in predefined positions, specified by index number. With that in mind, I'd actually say the original code is just fine with "if item[0:1] == '-'" and given the context it is pretty readable (ignoring the awful formatting with no whitespace around operators) and "correct". Using ".startswith()" might have been equally appropriate, but without knowing more detail of the input data I couldn't say. -Peter From simon.brunning at gmail.com Tue Nov 22 14:17:46 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 22 Nov 2005 19:17:46 +0000 Subject: Controlling windows gui applications from python In-Reply-To: <4381A547.1000304@skynet.be> References: <437E2F0D.5030706@skynet.be> <8c7f10c60511181151o1d016efx@mail.gmail.com> <4381A547.1000304@skynet.be> Message-ID: <8c7f10c60511221117p14d0625eg@mail.gmail.com> On 21/11/05, tim wrote: > Thanks for this tip, this looks like exactly what I need. > > Is there a more extended documentation for watsup somewhere ? Err, not a lot, no. > I didn't find info on: > how to send keystrokes to a program. You don't do that. WATSUP uses WinGuiAuto, which is a fairly thin wrapper around the Win32 API. Oh, and it's rubbish. Rather than sending keysrokes, you instead just set the controls' text to whatever you want it to be. > how to control ComboBox elements... Should be a simple extension to what's already there. > trying out the examples, here are some problems I am running into: (snip) I'm afraid I can't really help you here. I'm a Mac user these days! You might have some luck with the WATSUP user mailing list - . Good luck! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From istvan.albert at gmail.com Wed Nov 30 20:12:30 2005 From: istvan.albert at gmail.com (Istvan Albert) Date: 30 Nov 2005 17:12:30 -0800 Subject: an intriguing wifi http server mystery...please help In-Reply-To: <1133380930.939356.74070@g14g2000cwa.googlegroups.com> References: <1133324893.968023.79050@z14g2000cwz.googlegroups.com> <1133379245.111462.173530@o13g2000cwo.googlegroups.com> <1133380930.939356.74070@g14g2000cwa.googlegroups.com> Message-ID: <1133399550.463915.303320@z14g2000cwz.googlegroups.com> > But if it's a problem with the software, why does the server work > great when wired (i.e. not wireless)...that's the weird part. Don't be so quick to eliminate software error ... when it comes to bugs there are few rules. You are using a recipe that is *known* to produce weird behavior. Make sure to eliminate that source before moving to more esoteric reasons such as bad routing table. For example run some other simple webservers that were written in some other language and see if you get the same behavior (tinyhttpd or its ilk) . Istvan. From daftspaniel at gmail.com Tue Nov 22 15:20:59 2005 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: 22 Nov 2005 12:20:59 -0800 Subject: Comp.Lang.Python Podcase Message-ID: <1132690859.901598.57560@f14g2000cwb.googlegroups.com> This is very experimental but here is a comp.lang.python Podcast. The backend is Python of course via PyTTS. It should be updated daily. Happy Listening! Comments welcome. Davy Mitchell Mood News - BBC News Headlines Auto-Classified as Good, Bad or Neutral. http://www.latedecember.com/sites/moodnews/ From hungbichvo at yahoo.com Thu Nov 3 06:59:05 2005 From: hungbichvo at yahoo.com (hungbichvo) Date: Thu, 03 Nov 2005 11:59:05 -0000 Subject: How to read all files in a directory Message-ID: Dear All, My python application is small. It reads data from a file. My code is: fileName = '900128.DAT' dataFile = open(fileName, 'r').readlines() I have to run 100 input files .DAT. Each time I run application, I have to change code fileName to a new one. For example, fileName = 'NewFile.DAT'. I do not know how I can process all file with extension .DAT in a specific directory once only. Any suggestion will be appreciated, Thank you. From rurpy at yahoo.com Sat Nov 19 10:15:26 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 19 Nov 2005 07:15:26 -0800 Subject: examining python objects In-Reply-To: <437ef75a$0$32754$626a14ce@news.free.fr> References: <1132339687.048155.252160@g47g2000cwa.googlegroups.com> <437ef75a$0$32754$626a14ce@news.free.fr> Message-ID: <1132413326.055040.315150@g44g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > rurpy at yahoo.com a ?crit : > > Is there a function/class/module/whatever I can use to > > look at objects? I want something that will print the object's > > value (if any) in pretty-printed form, and list all it's attributes > > and their values. And do all that recursively. > > I want to be able to find out everything about an object that > > Python can introspectively find out. > > Then check the inspect module I want a callable, ready-to-use class or function. Inspect provides soime funtions that would be useful for wrinting such a class or function, but does not provide one. I seems that nobody who has written or used such a tool reads this group, or feels like responding. FWIW, (for anyone looking for something similar in the future) I found http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/137951 which will format and print an object's attributes. By combining that and pprint in the Python distrib, I think can coble up what I am looking for. Still, it is discouraging that such a basic thing is not provided with python, or at lleast easily available in some library. From grahn+nntp at snipabacken.dyndns.org Sat Nov 26 15:24:33 2005 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 26 Nov 2005 20:24:33 GMT Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: On Sat, 26 Nov 2005 00:13:10 +0000, Tom Anderson wrote: ... > freedom - 'free software', 'free as in speech', etc. What you have to > realise is that they're not talking about the freedom of the programmers, > but about the freedom of the software. The logic, i think, is that the > freedom of the code is the key to the freedom of the end-users: applying > the GPL to your code means that other programmers will be forced to apply > to to their code, which means that users of that code will get the > benefits of open source. ... which implies that one believes that every end-user has the potential to become a hacker. That, I think, is at the core of the GPL, and RMS's rantings are easier to understand if you keep that in mind. But yes, let's not dive too deeply into all that here. > Oops! ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From http Tue Nov 22 15:06:12 2005 From: http (Paul Rubin) Date: 22 Nov 2005 12:06:12 -0800 Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132660017.743919.248060@g49g2000cwa.googlegroups.com> Message-ID: <7xk6f030sr.fsf@ruckus.brouhaha.com> Here's a silly recursive version (don't really use, it's too slow): def csum(s): if len(s)==0: return s return csum(s[:-1]) + [sum(s)] From everettcc at hotmail.com Wed Nov 16 17:29:51 2005 From: everettcc at hotmail.com (Chad Everett) Date: Wed, 16 Nov 2005 16:29:51 -0600 Subject: Newb ? References: Message-ID: Hey guys, Thanks for the hint. I found that info last night but I could never get it to print more than just the last letter. or it would only print partially. I was using just a single colon, the double colon did it. Thanks "Chad Everett" wrote in message news:f1yef.20597$xK1.18635 at bignews7.bellsouth.net... > Hello all, > > Have a problem here with a challenge from a book I am reading. > Any help is much appreciated. > > I am trying to run a program that asks the user for a statement and then > prints it out backwards. > this is what I have. > It does not print anything out. I assume that I have something out of > whack with my high and low statements. > > Thanks for you help. > > > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > > high = len(message) > low = -len(message) > print > print message[high:low] > print > print raw_input("Please Press Enter to Exit") > From lycka at carmen.se Wed Nov 2 10:05:45 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 02 Nov 2005 16:05:45 +0100 Subject: Flat file, Python accessible database? In-Reply-To: References: Message-ID: Karlo Lozovina wrote: > I've been Googling around for _small_, flat file (no server processes), > SQL-like database which can be easily access from Python. There are some suggestions in my EPC 2004 DB presentation: http://www.thinkware.se/epc2004db/epc04_mly_db.pdf From andis59 at gmail.com Tue Nov 29 02:40:47 2005 From: andis59 at gmail.com (Anders Eriksson) Date: Tue, 29 Nov 2005 08:40:47 +0100 Subject: books: Dive into Python vs Beginning Python References: Message-ID: <1efrcobs8fmk.dlg@morateknikutveckling.se> On Fri, 25 Nov 2005 11:25:43 +0100, Franz Mueller wrote: > Hi, > > which of the following books would you recommend: > "Dive into Python" or "Beginning Python: From Novice to Professional"? > Since "Dive into Python" is on the net, you can see for yourself if it's any good (which I think it is!) http://diveintopython.org/ // Anders -- English isn't my first, or second, language. So anything rude or strange are due to the translation From deets at nospam.web.de Sun Nov 20 18:30:28 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Nov 2005 00:30:28 +0100 Subject: combine doxygen and doc-strings? In-Reply-To: References: Message-ID: <3ucf8fF10ilcvU1@uni-berlin.de> Gabriel Zachmann wrote: > Is there a way to combine doxygen comments, like this one If you are not tied to doxygen, you might consider epydoc - it uses the docstrings, and restructured text which is friendly to the eye. Regards, Diez From claudio.grondi at freenet.de Thu Nov 17 09:22:35 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 17 Nov 2005 14:22:35 -0000 Subject: IDLE question References: <1132217965.434209.122200@f14g2000cwb.googlegroups.com> <3u3186FvbckvU1@individual.net> <1132221788.888868.8370@f14g2000cwb.googlegroups.com> <3u34abFv24c5U1@individual.net> <1132225335.948524.162190@g43g2000cwa.googlegroups.com> <3u3899Fv3vulU1@individual.net> <3u393bFtovgcU1@individual.net> <1132230637.099278.295980@z14g2000cwz.googlegroups.com> Message-ID: <3u3fddFurbi3U1@individual.net> wrote > This works! > > Thanks Claudio I am glad, that the time I put into it was not wasted. > For complete happiness I would also like to know what's hapening. > Is there anywhere I can read about PyShell.py. Not that I would know about (except reading the source code). Maybe this below is the right place to ask further questions (2004 there was a discussion about IDLE): http://mail.python.org/mailman/listinfo/tutor but I have to admit, I haven't used this forum myself yet. >From my experience with learning Python I suppose, that it will be not very easy to fully understand what is going on in IDLE (i.e. in PyShell.py) because this probably requires full understanding of the Tkinter interface and some insight into deep Python internals. Perhaps this is the reason why noone knowledgable in this area has responded here expecting from a response more trouble than success? Claudio From mwm at mired.org Tue Nov 8 16:30:49 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 16:30:49 -0500 Subject: Web automation References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> <1131397945.832762.71070@g47g2000cwa.googlegroups.com> <86k6fk9k6v.fsf@bhuda.mired.org> <1131415131.676626.7730@g49g2000cwa.googlegroups.com> <86r79r96qh.fsf@bhuda.mired.org> <1131481509.978954.25900@g49g2000cwa.googlegroups.com> Message-ID: <863bm6969i.fsf@bhuda.mired.org> qwweeeit at yahoo.it writes: > answering to Mike Meyer who replied to the following > assertion on my part: > >> but I supposed the everyone knew that web automation > >> (and in general "automation") is only a problem in Linux. > with...: >> I don't know it. I don't believe it, either. I automate web tasks on >> Unix systems (I don't use many Linux systems, but it's the same tool >> set) on a regular basis. In fact, I automate *lots* of tasks on Unix > Perhaps there is a misunderstanding: I intend not the > script (like bash) automation, but the user emulation on the GUI side, > which allows automation by programmatically emulating a lot of repetive > user tasks. That's a *very* silly way to automate a task. When I'm automating a task, the *last* thing I want to do is think about selecting menu entries and pressing buttons on a GUI. I want to think about the operations on the object in question. A good automation interface will let me do the latter. A poor one will force me to do the former. Further, a good automation interface will let my script work without needing to open a GUI, or even needing the resources required to open the GUI - unless my script explicitly wants to open a GUI, anyway. That's also a very silly way to define automation. Sort of like defining "transportation" as "a horse and buggy", and then declaring that people who only have access to Mac trucks or Lear jets have a "problem with transportation." > But if the html server only enables the access from a browser, I am > obliged to cheat and disguise twill as a browser. So? Most such sites actually enable access from a small set of browsers. So lots of off-brand browsers have setting to disguise themselves as other browsers, or even enter an arbitrary string. If your browser has to do it, why should it matter if your not-a-browser has to do it? > By the way you already took part in a discussion on sending keystrokes > to a GUI application, "fake" flags and low-level programming > (you proposed python-xlib to avoid indeed low-level programming). Yes, I'm aware of that. Just because I disagree with your definitions and think you're doing things the hard way doesn't mean I'm not going try and help you if I think I can. But when you then make a false statement - or even one that could be misinterpreted as false - disparaging solutions I've had excellent success with, I'm going to point it out. > But in that I disagree with you. For me it's better to spend my time > in strenghtening security (firewalls, antivirus etc...) and then choose > among the various solutions in Windows as far as macro languages are > concerned (very likely I will choose Autot). On the whole, I believe that Unix has better macro languages than Windows. That's because Unix scripting has been around since before there was MS Windows. Or before MS DOS, for that matter. > And I can keep on using Python if I want... > > The contribution of Paul Boddie is valuable. I too examined DCOP > and even chose as browser Konqueror, being a KDE application. > But DCOP doesn't go to such a low level. It is not possible > to send a simulated keystroke from one KDE application to another. That you *want* to do those things would seem to be an indication that you're trying to do the wrong thing. When scripting on Unix, you usually get to work at a *much* higher level than emulating keystrokes or mouse clicks. Why would you want to work at that low a level when high-level alternatives are available? Wanting to do that on Unix because that's how you'd do it on Windows is sort of like wanting to process a string character at a time in Python because that's how you'd do it in C/C++/Java/whatever. You're better off learning to use the tools on the platform to your advantage than trying to make the platform be what it isn't. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From xray_alpha_charlie at yahoo.com Sun Nov 27 23:33:04 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Sun, 27 Nov 2005 20:33:04 -0800 (PST) Subject: yahoo sender name Message-ID: <20051128043304.62404.qmail@web35904.mail.mud.yahoo.com> hey...I know this is off the "python" topic....but I have yahoo mail and would like to change my "sender name" I have gone to the "edit account" area and have changed all names that can be edited to a consistent name other than the current sender name...but for some reason it will not change the sender name...is anybody familiar with yahoo mail and changing names? -thanks in advance- --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mail.comcast.net Tue Nov 22 10:51:11 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 22 Nov 2005 07:51:11 -0800 Subject: Why are there no ordered dictionaries? References: <1h6c7sd.1z0nwvuy4g9c9N%aleax@mail.comcast.net> Message-ID: <1h6f46e.3foxxx1a8673cN%aleax@mail.comcast.net> Fredrik Lundh wrote: ... > But math folks usually name things after the person(s) who came > up with the idea, not just some random implementer. The idea of Wrong: you're forgetting Stigler's Law of Misonomy (which I imagine must have NOT been discovered by Stigler...;-). The Poisson distribution was in fact described earlier by Bernoulli, Gosset's z-test is universally known as Student's t-test, etc, etc. Salsburg's delightful "The Lady Tasting Tea" has a lot of fun with Stigler's law in the footnotes...;-) Alex From bignose+hates-spam at benfinney.id.au Sun Nov 27 19:25:15 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 28 Nov 2005 11:25:15 +1100 (EST) Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> Message-ID: Flavio wrote: > Class soandso: > def __init__(self): > self.this = 0 > self.that = 1 > def meth1(self): > ... > def meth2(self): > ... > def custom(self): > pass > > I want to allow the user to write a python module that declares a > function so that myprogram can import it and attribute it to the custom > method of the soandso object. So far so good, that is an easy thing to > do in Python. > > import usermodule > a=soandso() > a.custom = usermodule.function Apparently you haven't tested whether this works. It doesn't: >>> class Foo(object): ... pass ... >>> def bar(*args): ... print "bar() got arguments:", args ... >>> bar("spam", "eggs") bar() got arguments: ('spam', 'eggs') >>> Foo.bar_method = bar >>> Foo.bar_method("spam", "eggs") Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method bar() must be called with Foo instance as first argument (got str instance instead) > But, what if the method had to access the self attributes (self.this > and self.that) of the soandso object? To become a method, the function must be bound to an instance, and the method will then receive the instance as the first argument when called as a method. To do this on an already-defined function, use new.instancemethod. >>> import new >>> help(new.instancemethod) -- \ "One time a cop pulled me over for running a stop sign. He | `\ said, 'Didn't you see the stop sign?' I said, 'Yeah, but I | _o__) don't believe everything I read.'" -- Steven Wright | Ben Finney From sybrenUSE at YOURthirdtower.com.imagination Fri Nov 25 09:31:39 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 25 Nov 2005 15:31:39 +0100 Subject: Persist a class (not an instance) References: <43871516$1_1@newspeer2.tds.net> Message-ID: Kent Johnson enlightened us with: > Is there a way to persist a class definition (not a class instance, > the actual class) so it can be restored later? >From the docs: "Similarly, classes are pickled by named reference, so the same restrictions in the unpickling environment apply. Note that none of the class's code or data is pickled [...]" 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 fredrik at pythonware.com Mon Nov 7 13:24:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 7 Nov 2005 19:24:54 +0100 Subject: when and how do you use Self? References: <3C5387E42DA62B4EA1F1EBD2DB498381369627@usmtm-emh3.USMTM.SPPN.AF.MIL> Message-ID: "Tieche Bruce A MSgt USMTM/AFD" wrote: > Well, thanx for all the ... useful information. > > I thought that I would try, but this has turned out to be a waist of my time. did you perhaps miss that at least three people wrote proper replies to your post? http://article.gmane.org/gmane.comp.python.general/429472 http://article.gmane.org/gmane.comp.python.general/429703 http://article.gmane.org/gmane.comp.python.general/429858 (if you read the newsgroup in a threaded reader, spotting them should be relatively easy). From http Mon Nov 28 16:15:53 2005 From: http (Paul Rubin) Date: 28 Nov 2005 13:15:53 -0800 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> <86oe49wyky.fsf@bhuda.mired.org> <86acfsgols.fsf@bhuda.mired.org> <86sltjg2s8.fsf@bhuda.mired.org> <86y83bdmln.fsf@bhuda.mired.org> <7xek50iiic.fsf@ruckus.brouhaha.com> Message-ID: <7xacfoiid2.fsf@ruckus.brouhaha.com> Paul Rubin writes: > With the GPL, you get a slight restriction from the GPL author (you're > not allowed to redistribute the binary unless you offer source). Forgot to add: and under the GPL, you must not threaten to have the goverment clobber people for redistributing the source or binary after they have have gotten it from you. It's one of those "forbidding forbidden" types of restrictions. From 8273grkci8q8kgt at jetable.net Thu Nov 17 22:32:36 2005 From: 8273grkci8q8kgt at jetable.net (Lars Kellogg-Stedman) Date: Thu, 17 Nov 2005 21:32:36 -0600 Subject: Hot to split string literals that will across two or more lines ? References: <1132284614.326121.252250@g49g2000cwa.googlegroups.com> Message-ID: > Minor pedantry, but the plus sign is redundant. Thanks for catching that...I haven't been working with Python as much as I was a year or so ago and I'm forgetting some of the details. -- Lars -- Lars Kellogg-Stedman <8273grkci8q8kgt at jetable.net> This email address will expire on 2005-11-23. From steve at holdenweb.com Sat Nov 5 21:21:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 06 Nov 2005 02:21:42 +0000 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <436c0527.146082265@news.oz.net> <864q6rkfie.fsf@bhuda.mired.org> <436d0b61.213212052@news.oz.net> <7xirv639kb.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano wrote: [...] > > But I can't understand the position of folks who want inheritance but > don't want the behaviour that Python currently exhibits. > instance.attribute sometimes reading from the class attribute is a feature > of inheritance; instance.attribute always writing to the instance is a > feature of OOP; instance.attribute sometimes writing to the instance and > sometimes writing to the class would be, in my opinion, not just a wart > but a full-blown misfeature. > > I ask and I ask and I ask for some use of this proposed behaviour, and > nobody is either willing or able to tell me where how or why it would be > useful. What should I conclude from this? > > You should conclude that some readers of this group are happier designing languages with theoretical purity completely disconnected from users' needs. But of course we pragmatists know that practicality beats purity :-) 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 roy at panix.com Fri Nov 11 08:45:42 2005 From: roy at panix.com (Roy Smith) Date: Fri, 11 Nov 2005 08:45:42 -0500 Subject: Needed class whose instances are many test cases References: <1131706265.113961.63370@f14g2000cwb.googlegroups.com> Message-ID: In article , Ben Finney wrote: > This is a poor design; your tests will each be starting in a different > state, and will likely not run the same way if run in a different > order, making them fragile. > > Test cases should each run individually, from a known state, and not > depend on any other tests. You can define a fixture for several tests > in the unittest.TestCase methods setUp() and tearDown(), to establish > and clear up respectively for each test. In general, I certainly agree with the above. The problem is that sometimes setup is so expensive, it becomes impractical to do a full setup/teardown cycle for each test. From s99999999s2003 at yahoo.com Sat Nov 5 02:53:35 2005 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 4 Nov 2005 23:53:35 -0800 Subject: re sub help In-Reply-To: <86br0z7e3w.fsf@bhuda.mired.org> References: <1131173343.954029.211530@o13g2000cwo.googlegroups.com> <86br0z7e3w.fsf@bhuda.mired.org> Message-ID: <1131177215.248797.268670@f14g2000cwb.googlegroups.com> thanks for the reply. i am still interested about using re, i find it useful. am still learning it's uses. so i did something like this for a start, trying to get everything in between [startdelim] and [enddelim] a = "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" t = re.compile(r"\[startdelim\](.*)\[enddelim\]") t.findall(a) but it gives me []. it's the "\n" that prevents the results. why can't (.*) work in this case? Or am i missing some steps to "read" in the "\n"..? thanks. From jay.dow at gmail.com Sun Nov 13 17:40:59 2005 From: jay.dow at gmail.com (jay.dow at gmail.com) Date: 13 Nov 2005 14:40:59 -0800 Subject: something wrong in wx In-Reply-To: References: Message-ID: <1131921659.239555.51750@g44g2000cwa.googlegroups.com> Don't know if this will help or not because it seems like a strange error if this is the problem. I've always had to run my wxPython apps with pythonw, otherwise it will give you an error saying it needs the GUI interpreter or something like that. However, this could be an operating system specific codition. If that doesn't fix anything all I can say is check and recheck your path. From apardon at forel.vub.ac.be Mon Nov 7 04:06:35 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 09:06:35 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> <8764r8u3wr.fsf@keizer.soze.com> <86ek5whfw1.fsf@bhuda.mired.org> Message-ID: Op 2005-11-04, Steven D'Aprano schreef : > On Fri, 04 Nov 2005 10:48:54 +0000, Antoon Pardon wrote: > >> Please explain why this is illegal. >> >> x = 1 >> def f(): >> x += 1 > > Because names in function namespaces don't have inheritance. Your quibling about words. This certainly works. x = 1 def f(): a = x + 1 So you could say that function namespaces do inherit from outer scopes. Whether you want to name it inheritance or not, is not the issue. -- Antoon Pardon From fredrik at pythonware.com Mon Nov 21 02:50:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Nov 2005 08:50:20 +0100 Subject: Why are there no ordered dictionaries? References: <1132531775.399671.93120@o13g2000cwo.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Fredrik Lundh wrote: > > but you can easily generate an index when you need it: > > > > index = dict(d) > > > > name, type = index["pid"] > > print name > > > > the index should take less than a microsecond to create, and since it > > points to the members of the original dict, it doesn't use much memory > > either... > > > Using the same logic, we don't need types other than string in a DBMS > as we can always convert a string field into some other types when it > is needed. No, that's not the same logic. The dict() in my example doesn't convert be- tween data types; it provides a new way to view an existing data structure. There's no parsing involved, nor any type guessing. And given the use case, it's more than fast enough, and doesn't copy any data. If you think that's the same thing as parsing strings, you've completely missed the point. From bobueland at yahoo.com Thu Nov 17 03:53:59 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 17 Nov 2005 00:53:59 -0800 Subject: Python Library Reference - question Message-ID: <1132217639.080443.144910@g44g2000cwa.googlegroups.com> The "Python LIbrary Reference" at http://docs.python.org/lib/contents.html seems to be an important document. I have two questions Q1. How do you search inside "Python LibraryReference" ? Does it exist in pdf or chm form? Q2. In some other languages (for instance PHP if I recall correctly) readers can add comments and give examples to the various headings in the reference manual. This gives valuable information to the reader. Is there such a version of "Python Library Reference", and if not would it be a good idea to have such a version. Thanks Bob Ueland From fredrik at pythonware.com Wed Nov 16 14:48:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 20:48:25 +0100 Subject: Quitting a Tkinter application with confirmation References: Message-ID: Peter Kleiweg wrote: > I want the program to behave identical if the 'close' button of > the application window is clicked. I tried the code below, > using a class derived from Tk that redefines the destroy > method. That seems to work. At least on Linux. > > My questions: > > Is this the correct and save way to do this? Will it work on any > operating system? Shouldn't I do some event capturing instead? the right way to do this is to implement a WM_DELETE_WINDOW protocol handler: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols in your case, adding root.protocol("WM_DELETE_WINDOW", root.destroy) to the right place should be enough. > (Capture the SIGTERM or SIGQUIT, sent by the Window manager to > the application.) that's signals, not events, and should not be needed. (afaik, a properly written X Window application should shut down by itself, in response to DestroyWindow requests from the window manager. if the window manager has to use explicit kill signals to get rid of an application, something's wrong). From fredrik at pythonware.com Tue Nov 29 12:10:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Nov 2005 18:10:21 +0100 Subject: xpath support in python 2.4 References: <1133278253.523473.110800@g49g2000cwa.googlegroups.com> Message-ID: "And80" wrote: > I would like to use xpath modules in python2.4.... In my local machine > I am running python2.3.5 and on the server I run python2.4. I have seen > that while on my computer i am able to import xml.xpath, on the server > the module seems to not exist. Is it still part of the standard > library? if not, what should I use? sounds like you've installed http://pyxml.sourceforge.net/ on one of your machines, but not on the other. (afaik, xml.xpath has never been part of the standard library.) From steve at REMOVETHIScyber.com.au Thu Nov 3 11:15:47 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 03:15:47 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: On Thu, 03 Nov 2005 15:13:52 +0100, Eric Nieuwland wrote: > Stefan Arentz wrote: >> It is really simple. When you say b.a then the instance variable 'a' >> is looked up first. If it does not exist then a class variable lookup >> is done. > > This mixing of class and instance variable might be the cause of > confusion... > > I think of it as follows: > 1 When the class statement ends a class object is created which is > filled by all the statements inside the class statement > This means all variables and functions (methods) are created according > to the description. > NOTE This happens just once. Yes. > 2 When an instance of the class is created, what effectively happens is > that a shallow copy of the class object is made. > Simple values and object references are copied. No. py> class Parrot: ... var = 0 ... py> p = Parrot() py> Parrot.var is p.var True py> Parrot.var = {"Hello world": [0, 1, 2]} py> Parrot.var is p.var True It all boils down to inheritance. When Python does a look up of an attribute, it looks for an instance attribute first (effectively trying instance.__dict__['name']). If that fails, it looks up the class second with instance.__class__.__dict__['name'], and if that fails it goes into a more complex search path looking up any superclasses (if any). > This explains: > - why methods and complex objects (e.g. lists) are shared among > instances of a class and the class itself > - simple values are not shared No. it is all about the inheritance, and mutable/immutable objects. -- Steven. From bignose+hates-spam at benfinney.id.au Sun Nov 13 18:02:30 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Nov 2005 10:02:30 +1100 (EST) Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <43770305$0$5294$636a15ce@news.free.fr> Message-ID: Steven D'Aprano wrote: > On Mon, 14 Nov 2005 00:48:46 +1100, Ben Finney wrote: > > I believe Pierre is looking for a syntax that will save him from > > assigning values to names; that Python will simply assign > > arbitrary unique values for these special names. > > > What I still don't understand is why this justifies additional > > syntax baggage in the language, rather than an explicit assignment > > earlier in the code. > > The only advantage would be if you want to do something like this: > > MO, TU, WE, TH, FR, SA, SU = Symbols() I believe that's exactly what Pierre doesn't want to do. He wants to simply use names (marked special in some way) and have Python automatically determine a unique value for each name, with nary an assignment in sight. To me, that's a net loss. It makes names more complicated, it loses "explicit is better than implicit", and it loses the checks Python could do against using a name that hasn't been assigned a value (caused by e.g. a misspelled name). -- \ "Why should I care about posterity? What's posterity ever done | `\ for me?" -- Groucho Marx | _o__) | Ben Finney From lycka at carmen.se Fri Nov 4 13:07:21 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 04 Nov 2005 19:07:21 +0100 Subject: Shareware in Python In-Reply-To: References: Message-ID: Ivan Sas wrote: > I want to create some shareware program in Python. Can I distribute > this program with > python24.dll file from Python 2.4.2? I'm not sure if Python GPL > compatible license allowing for doing it. GPL compatible means "can be used as a component in GPL software". It doesn't imply that the Python licence is GPL equivalent in the way that it restricts the licence for software that includes it as a component. From kylotan at gmail.com Mon Nov 21 05:55:04 2005 From: kylotan at gmail.com (Ben Sizer) Date: 21 Nov 2005 02:55:04 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132531775.399671.93120@o13g2000cwo.googlegroups.com> Message-ID: <1132570504.077360.187490@z14g2000cwz.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > Using the same logic, we don't need types other than string in a DBMS > > as we can always convert a string field into some other types when it > > is needed. > > No, that's not the same logic. The dict() in my example doesn't convert be- > tween data types; it provides a new way to view an existing data structure. This is interesting; I would have thought that the tuple is read and a dictionary created by inserting each pair sequentially. Is this not the case? -- Ben Sizer From aleax at mail.comcast.net Thu Nov 3 22:14:33 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 19:14:33 -0800 Subject: How can I package a python script and modules into a single script? References: <1131030933.425241.142800@o13g2000cwo.googlegroups.com> <1h5fxbf.1cb8siquyt2qsN%aleax@mail.comcast.net> <1131072712.848129.129020@z14g2000cwz.googlegroups.com> Message-ID: <1h5gsz1.cvhtfgdadif2N%aleax@mail.comcast.net> Noah wrote: > This is interesting, but requires two separate files -- the ZIP file > and the boot script. No, it doesn't. > This is because zipimport can only import from file paths. It can import from a file, and the file (like all zipfiles) can have a prefix. That prefix is where you put the "boot" script. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215301 (though I believe I did some minor enhancements, as well as adding useful discussion, in the 2nd edition of the O'Reilly printed version of the cookbook, Raedler's basic idea is presented here; you can get all the sources as they appear in the printed version as an archive, a zipfile I believe, on the O'Reilly site for the book). > Anders Hammarquist has a Python Cookbook example that seems to do what > I want. > "Importing a Dynamically Generated Module". So far so good. I have to > check it out a bit more. I know Anders (known to his friends as "Iko") quite well, worked at his side in Sweden in past years, and I selected his recipe for the first edition of the O'Reilly printed version of the Cookbook -- but it does not address the specific problem you desire. Raedler's recipe does. Alex From steve at holdenweb.com Mon Nov 14 16:10:50 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 14 Nov 2005 21:10:50 +0000 Subject: more newbie help needed In-Reply-To: <20051114202826.66652.qmail@web35915.mail.mud.yahoo.com> References: <20051114202826.66652.qmail@web35915.mail.mud.yahoo.com> Message-ID: <4378FD5A.7000203@holdenweb.com> john boy wrote: [top-posting corrected] > > Steve Holden wrote:john boy wrote: > >>using the following program: >> >>fruit = "banana" >>index = 0 >>while index < len (fruit): >>letter = fruit[index-1] >>print letter >>index= index -1 >> >>this program is supposed to spell "banana" backwards and in a vertical patern...it does this....but after spelling "banana" it gives an error message: >>refering to line 4: letter = fruit[index-1] >>states that it is an IndexError and the string index is out of range >>Anybody know how to fix this? >> > > Change the termination condition on your loop. If you print out the > values of index as the loop goes round you'll see you are printing > characters whose index values are -1, -2, ..., -6 > > Unfortunately -7 is less than -6, so your loop keeps on going, with the > results you observe. > > Note, however, that there are more pythonic ways to perform this task. > You might try: > > for index in range(len(fruit)): > letter = fruit[-index-1] > print letter > > as one example. I'm sure other readers will have their own ways to do > this, many of them more elegant. > thanks for your example....but for information purposes so I can grasp the basics....could you give me an example of how I could terminate the "while" loop Well in this case, when fruit == "banana" the last value you want to use is -6 - you've already seen that using -7 causes the interpreter to raise an exception. So you could use, for example, while -index <= len(fruit) though I haven't tested that. Basically you need to work out a condition that's true for all useful values of index and false for the first non-useful value. By the way, I've copied this reply to the list. It's customary to keep follow-ups on the list, that way if I'd been too busy to answer somebody else might have been able to help. 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 mrossi19 at gmail.com Thu Nov 3 17:56:46 2005 From: mrossi19 at gmail.com (mr19) Date: 3 Nov 2005 14:56:46 -0800 Subject: ImportError with packages Message-ID: <1131058606.456629.224800@g47g2000cwa.googlegroups.com> I'm running into import problems trying to create a package that is similiar in layout to the one in the docs described here: http://www.boost.org/libs/python/doc/tutorial/doc/html/python/techniques.html#python.creating_packages So my package layout is as follows: xyzzy/ __init__.py research/ __init__.py _research.so stats.pyc My __init__.py file contains 2 lines: from stats import * from _research import * With the directory containing 'xyzzy' on my PYTHONPATH, the following occurs: Python 2.4.2 (#2, Nov 3 2005, 11:35:03) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import xyzzy.research Traceback (most recent call last): File "", line 1, in ? File "xyzzy/research/__init__.py", line 2, in ? from _research import * ImportError: No module named _research Running python with the -vv switch shows python does indeed look at _research.so but does not load it. However if I put the directory containing _research.so on my PYTHONPATH the following command is successful: >>> import _research Thanks for any help you can offer, Marc From fredrik at pythonware.com Wed Nov 30 13:14:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Nov 2005 19:14:36 +0100 Subject: UnicodeDecodeError References: <1133368054.944179.150920@f14g2000cwb.googlegroups.com> Message-ID: "ash" wrote: > one of the modules in my programs stopped wroking after i upgraded from > python 2.3 to 2.4. I also changed my wxPython to unicode supported one > during the process. > what the module essentially does is search for a stirng pattern form a > list of strings. > this is the function: > > def srchqu(self): > for i in range(1,len(qu)):#qu is the list of strings > if qu[i][0].lower().find(self.query)==-1: > pass > else: > #do some stuff here > > I get this error message on calling the function: > > Traceback (most recent call last): > File "E:\mdi\search.py", line 86, in OnSrchButton > self.srchqu() > File "E:\mdi\search.py", line 97, in srchqu > if qu[i][0].lower().find(self.query)==-1: > UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position > 66: ordinal not in range(128) > > what is the problem and the solution? thanks in advance for any help. one of qu[i][0] or self.query is a unicode string, and the other is an 8-bit string that contains something that's not ASCII. to make the code do what you do, make sure to decode the 8-bit strings into Unicode strings. From __peter__ at web.de Tue Nov 8 05:13:22 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Nov 2005 11:13:22 +0100 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> Message-ID: Jerzy Karczmarczuk wrote: > Peter Otten wrote: >> pinkfloydhomer at gmail.com wrote: >> >> >>>Just to satisfy my curiousity: Is there a way to do something like the >>>reference solution I suggest above? >> >> >> No. You cannot overload assignment. > > I have the impression that this is not an issue, to overload assignments, > which btw. *can* be overloaded, but the absence of *aliasing* > (undiscriminate handling of pointers) in Python. Am I wrong? I think so. a = b will always make a a reference to (the same object as) b. What can be overloaded is attribute assignment: x.a = b can do anything from creating an attribute that references b to wiping your hard disk. I don't understand what you mean by "absence of aliasing", but conceptually every python variable is a -- well-behaved -- pointer. Peter From samrobertsmith at gmail.com Sat Nov 12 03:31:31 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 00:31:31 -0800 Subject: about try statement Message-ID: <1d987df30511120031g6ecc3076mae2a72900a7661ff@mail.gmail.com> very hard for me to understand the difference between try...except and try...finally From gregory.petrosyan at gmail.com Tue Nov 15 11:24:49 2005 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 15 Nov 2005 08:24:49 -0800 Subject: Default method arguments In-Reply-To: <437a0a1b_1@newsgate.x-privat.org> References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a0a1b_1@newsgate.x-privat.org> Message-ID: <1132071889.676287.240030@o13g2000cwo.googlegroups.com> Thanks a lot, but that's not what I do really want. 1) f() may have many arguments, not one 2) I don't whant only to _print_ x. I want to do many work with it, so if I could simply write def f(self, x = self.data) (*) it would be much better. By the way, using class A(object): data = 0 .... def f(self, x = data) solves this problem, but not nice at all So I think (*) is the best variant, but it doesn't work :( From skip at pobox.com Mon Nov 28 16:48:47 2005 From: skip at pobox.com (skip at pobox.com) Date: Mon, 28 Nov 2005 15:48:47 -0600 Subject: Death to tuples! In-Reply-To: References: <86y839ux1j.fsf@bhuda.mired.org> <8664qcv6i5.fsf@bhuda.mired.org> <7x64qcii9o.fsf@ruckus.brouhaha.com> Message-ID: <17291.31551.224927.959409@montanaro.dyndns.org> >>> For those of us not following this thread closely, can you identify >>> cases where tuples are mutable, not hashable or can't be used as >>> dictionary keys? I've never encountered any such cases. >> >> t = ([1,2], [3,4]) ... >>>> t = ([1,2], [3,4]) >>>> t[0] += [5] aahz> Traceback (most recent call last): aahz> File "", line 1, in ? aahz> TypeError: object doesn't support item assignment >>>> t aahz> ([1, 2, 5], [3, 4]) aahz> (I'm pretty sure Skip has seen this before, but I figure it's a aahz> good reminder.) Actually, no, I hadn't. I don't use tuples that way. It's rare when I have a tuple whose elements are not all floats, strings or ints, and I never put mutable containers in them. Skip From NOmanlio_perilloSPAM at libero.it Wed Nov 23 11:51:15 2005 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 23 Nov 2005 16:51:15 GMT Subject: strange behaviour when writing a large amount of data on stdout References: Message-ID: On Wed, 23 Nov 2005 07:48:30 -0600, jepler at unpythonic.net wrote: >That code works here. > >Python2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 > >It's Windows XP, Pentium 4, unknown amount of RAM. I'm running python.exe in a >console window. It also worked in IDLE. > >Jeff Thanks. So, it's seem to be a specific problem of Windows XP(?). Nobody can test it on a Windows 98/2000 machine? Regards Manlio Perillo From apardon at forel.vub.ac.be Mon Nov 21 05:04:26 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Nov 2005 10:04:26 GMT Subject: Why are there no ordered dictionaries? References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> Message-ID: Op 2005-11-21, Christoph Zwerschke schreef : > bonono at gmail.com wrote: >> Personally, I have needs for ordered dict but I don't think it should >> be in standard library though, as different situation called for >> different behaviour for "ordered" and skewing my code to a standard lib >> way is no good. > > I have started the thread in the first place because I believed it is > pretty unabmiguous what an "ordered dictionary" is and how it should > behave. That's why I asked myself why something that straigthforward has > not been added to the standard lib yet. Maybe I'm wrong; I must admit > that I haven't meditated about it very much. Well it doesn't seem that obvious, because the two recipes you have gotten, do something different from what I understand as an ordered dictionary. The two recipes order the keys by insertion order. My idea would have been that some order was defined on your keys in advance and that when you iterated over the dictionary, the results would be ordered in sequence of key order. > Do you have an example for different options of behavior? Well you have two above. Maybe someone can think of something else. Which behaviour are you looking for? -- Antoon Pardon From noah at noah.org Thu Nov 3 21:51:52 2005 From: noah at noah.org (Noah) Date: 3 Nov 2005 18:51:52 -0800 Subject: How can I package a python script and modules into a single script? In-Reply-To: <1h5fxbf.1cb8siquyt2qsN%aleax@mail.comcast.net> References: <1131030933.425241.142800@o13g2000cwo.googlegroups.com> <1h5fxbf.1cb8siquyt2qsN%aleax@mail.comcast.net> Message-ID: <1131072712.848129.129020@z14g2000cwz.googlegroups.com> This is interesting, but requires two separate files -- the ZIP file and the boot script. This is because zipimport can only import from file paths. It can't import from a string or an IOString (as far as I can tell). If only they would let you import from an already open file. Damn! Squeeze is 99% of what I want except for the fact that it precompiles the py files to bytecode which locks you to the version of python you compiled on. Python byte code is not guaranteed to be portable across different versions of Python. Squeeze relies on ihooks, which is a standard module, but it is undocumented. Anders Hammarquist has a Python Cookbook example that seems to do what I want. "Importing a Dynamically Generated Module". So far so good. I have to check it out a bit more. It relies on the "imp" standard library module. With a bit of inspiration from "Squeeze" and help from the "imp" module I might have what I want. Yours, Noah From ejensen at visi.com Wed Nov 23 10:34:49 2005 From: ejensen at visi.com (Ed Jensen) Date: Wed, 23 Nov 2005 15:34:49 -0000 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> Message-ID: <11o930pojo086fd@corp.supernews.com> Paul Boddie wrote: > That would be "free as in freeloading", right? (And no, I'm not > intending to start a licensing flame war with that remark, but I think > it's inappropriate to ignore central licensing concepts such as > end-user freedoms, and then to make sweeping statements about how > "free" the GPL is or isn't. If people want to use the GPL as a > convenient punchbag, I think they have to work a bit harder justifying > their gym subscription.) Blame the GPL and FSF for the confusion. Try this little experiment: Walk up, at random, to 100 people on the street. Show them a software CD-ROM -- a game, a word processor, whatever. Tell them it's free. Then ask them what they think that means. 99 times out of 100, they'll think it means it's free-as-in-beer. They *won't* think it means they'll get the source code, and the right to tweak that source code. They *won't* think it means they have the right to infinitely redistribute it. At best, the GPL/FSF engaged in what I consider false advertising. Free Software (note the capital 'F' and 'S') *isn't*, by the most widely understood and assumed definition of "free". They should have called it "liberated software" or "share and share alike software" or "free as in herpes" software. Free Software is certainly not free software, since it comes heavily encumbered by licensing issues. The success of things like Python -- which is not GPL licensed, afaik -- pretty much proves the GPL is unnecessary for the success of free projects. The GPL is just some bizarre social agenda being pushed by some crazies, and a lot of programmers (who are not lawyers) fell for the hippie nonsense. So, you may like to bandy around the mildly offensive "free as in freeloading", but then that gives me the right to refer to GPL'd software as "free as in pushing my personal social agenda". From steve at holdenweb.com Wed Nov 23 03:06:11 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Nov 2005 08:06:11 +0000 Subject: Why are there no ordered dictionaries? In-Reply-To: References: Message-ID: <438422F3.5040205@holdenweb.com> Christoph Zwerschke wrote: > This is probably a FAQ, but I dare to ask it nevertheless since I > haven't found a satisfying answer yet: Why isn't there an "ordered > dictionary" class at least in the standard list? Time and again I am > missing that feature. Maybe there is something wrong with my programming > style, but I rather think it is generally useful. > > I fully agree with the following posting where somebody complains why so > very basic and useful things are not part of the standard library: > http://groups.google.com/group/comp.lang.python/msg/e652d2f771a49857 > > Are there plans to get it into the standard lib sometime? > We're always encouraging new posters to use "good" subject lines. Several hundred posts after your original question I think everyone can agree that this was a *very* good subject line :-) Perhaps now the answer top your question is more obvious: there is by no means universal agreement on what an "ordered dictionary" should do. Given the ease with which Python allows you to implement your chosen functionality it would be presumptuous of the core developers to favour any one of the several reasonable alternatives that might be chosen. 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 detlev at die-offenbachs.de Mon Nov 7 06:16:03 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Mon, 07 Nov 2005 12:16:03 +0100 Subject: ANN: eric3 3.8.0 released Message-ID: Hi, this is to inform you about the release of eric3 3.8.0. It is available via http://www.die-offenbachs.de/detlev/eric3.html The list below summarizes the difference between eric3 3.7.x and 3.8.x - too long list of bugfixes to mention here - these usability enhancements DEBUGGER -- added possibility for path translation for passive debugging and remote debugging (Configuration Dialog -> Debugger -> General) -- added support for project specific debugger settings (see Project menu -> Debugger) -- added support for special watchpoint conditions (variable is created, variable is changed) DOCUMENTATION GENERATOR: -- added capability to generate source documentation using CSS style sheets to the eric3-doc utility (including the default style and a style with reversed headers) (Note: eric3-helpviewer cannot show the styles due to the limited HTML support in QTextBrowser) -- added the flag '-t' to eric-doc and eric-api to tell them to look for additional files EDITOR: -- added additional lexers (CSS files, TeX files, Diff files, Make Files, Properties Files and Batch Files) (QScintilla > 1.5.x is required) GENERAL: -- some interface cleanups and little reorganization of the configuration dialog -- added action to open multiple files -- added the capability to use %-codes for entering command line arguments. Supported codes are: %D directory of the current editor %F filename of the current editor %H home directory of the current user %U user name of the current user %% the percent sign This functionality is available in the following dialogs: configuration dialog, Debugger->General page version control system, Command Options cvs, Execute Command subversion, Execute Command mercurial, Execute command Tools Configuration -- added a configuration option to set the default encoding for files, that don't contain an encoding marker GRAPHICS: -- added the capability to delete shapes to the graphics dialogs PROJECT MANAGEMENT -- some optimisations and additions in the project browsers -- added configurable filetype associations for projects -- changed "Add file dialog" to allow the addition of multiple files to the project RUBY: -- enhanced Ruby support (thanks to Richard Dale) SHELL: -- changed the shell completion to use the Scintilla userlist. It is activated by pressing the TAB key and deactivated by pressing the ESC key (without selection) or the TAB or ENTER key (with selection). TASKS -- extended task management with categorization and a colorized display TEMPLATES: -- added a templates system TOOLS: -- added support for cx_Freeze (FreezePython) -- added support for PyLint USER INTERFACE: -- added the commandline option "--nokde" to disable usage of the KDE dialogs -- switching the editor will highlight the current file in the project browser -- added a context menu for the "Listspace" view manager -- added an incremental quicksearch to the search toolbar VERSION CONTROL: -- added support for Mercurial VCS What is it? ----------- eric3 is a Python and Ruby IDE with batteries included. For details see the eric3 home page. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From steve at REMOVETHIScyber.com.au Thu Nov 10 09:30:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 11 Nov 2005 01:30:07 +1100 Subject: Python obfuscation References: <1131564878.074210.74640@z14g2000cwz.googlegroups.com> <1131600579.626993.146040@g47g2000cwa.googlegroups.com> Message-ID: On Thu, 10 Nov 2005 13:35:00 +0100, yepp wrote: > The Eternal Squire wrote: > >> >> 1) The decrypted modules should only reside in RAM, never in virtual >> memory. Those RAM locations should be rendered inaccessible to Python >> code. > > I'm starting to understand why FOSS developers are said to be productive > above the average: they don't have to mess their brains with stuff like > that. That's not *quite* true. There are FOSS programs that actually do care about security. For instance, if you are encrypting data, you don't want the memory containing the plaintext to be swapped to your swap partition, where raw disk tools can recover it. But as a general rule, you're right. If you, the developer, don't have to think of your users as the enemy, you'd be amazed the amount of make-work you don't have to do. -- Steven. From twic at urchin.earth.li Sat Nov 26 19:32:42 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 27 Nov 2005 00:32:42 +0000 Subject: Comparison problem In-Reply-To: References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: On Sat, 26 Nov 2005, Peter Hansen wrote: > Tom Anderson wrote: >> On Sat, 26 Nov 2005, Chris wrote: >> >>> if item[0:1]=="-": >> >> item[0:1] seems a rather baroque way of writing item[0]! I'd actually >> suggest writing this line like this: > > Actually, it's not so much baroque as it is safe... item[0] will fail if > the string is empty, while item[0:1] will return '' in that case. Ah i didn't realise that. Whether that's safe rather depends on what the subsequent code does with an empty string - an empty string might be some sort of error (in this particular case, it would mean that the loop test had gone wrong, since bool("") == False), and the slicing behaviour would constitute silent passing of an error. But, more importantly, egad! What's the thinking behind having slicing behave like that? Anyone got any ideas? What's the use case, as seems to be the fashionable way of putting it these days? :) tom -- This should be on ox.boring, shouldn't it? From bokr at oz.net Thu Nov 3 21:53:33 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 04 Nov 2005 02:53:33 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> Message-ID: <436acc0a.65925796@news.oz.net> On 3 Nov 2005 12:20:35 GMT, Antoon Pardon wrote: >Op 2005-11-03, Stefan Arentz schreef : >> Antoon Pardon writes: >> >>> Op 2005-11-03, Steven D'Aprano schreef : >>> >>> >> There are two possible fixes, either by prohibiting instance variables >>> >> with the same name as class variables, which would allow any reference >>> >> to an instance of the class assign/read the value of the variable. Or >>> >> to only allow class variables to be accessed via the class name itself. >>> > >>> > There is also a third fix: understand Python's OO model, especially >>> > inheritance, so that normal behaviour no longer surprises you. >>> >>> No matter wat the OO model is, I don't think the following code >>> exhibits sane behaviour: >>> >>> class A: >>> a = 1 >>> >>> b = A() >>> b.a += 2 >>> print b.a >>> print A.a >>> >>> Which results in >>> >>> 3 >>> 1 >> >> I find it confusing at first, but I do understand what happens :-) > >I understand what happens too, that doesn't make it sane behaviour. > >> But really, what should be done different here? > >I don't care what should be different. But a line with only one >referent to an object in it, shouldn't be referring to two different >objects. > >In the line: b.a += 2, the b.a should be refering to the class variable >or the object variable but not both. So either it could raise an >attribute error or add two to the class variable. > >Sure one could object to those sematics too, but IMO they are preferable >to what we have now. > A somewhat similar name space problem, where you could argue that "a" prior to += should be seen as defined in the outer scope, but lookahead determines that a is local to inner, period, so that is the reference that is used (and fails). >>> def outer(): ... a = 1 ... def inner(): ... a += 2 ... print a ... print 'outer a', a ... inner() ... print 'outer a', a ... >>> outer() outer a 1 Traceback (most recent call last): File "", line 1, in ? File "", line 7, in outer File "", line 4, in inner UnboundLocalError: local variable 'a' referenced before assignment Regards, Bengt Richter From claudio.grondi at freenet.de Thu Nov 17 07:35:12 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 17 Nov 2005 12:35:12 -0000 Subject: IDLE question References: <1132217965.434209.122200@f14g2000cwb.googlegroups.com> <3u3186FvbckvU1@individual.net> <1132221788.888868.8370@f14g2000cwb.googlegroups.com> <3u34abFv24c5U1@individual.net> <1132225335.948524.162190@g43g2000cwa.googlegroups.com> Message-ID: <3u3899Fv3vulU1@individual.net> schrieb im Newsbeitrag news:1132225335.948524.162190 at g43g2000cwa.googlegroups.com... > I did as you suggested, however > > after I make a new File (File/New Window) and save and then run (F5) I > get the following alert > > The Python Shell is already executing a command; please waith until it > is finished > > I also get the error message > > Traceback (most recent call last): > File "", line 1, in -toplevel- > import os; from path import path > ImportError: No module named path > >>> > > Bob > Sure you have to replace "import os; from path import path" with " from btools import *", than you avoid the error message but not the problem you have got with the message box. A "solution" to the problem with the message box may be as follows: " console.showprompt() # restart subprocess debugger # (-Patch) # making additional modules available in IDLE directly after re-start of it: self.runsource("import os; from path import path") time.sleep(0.1) # (Patch-) if debug: " If 0.1 doesn't work on your system, just increase the value, but this will delay the response. e.g. 0.001 doesn't work for me, but 0.1 does (Intel Pentium 4 running at 2.8 GHz). Claudio From fredrik at pythonware.com Mon Nov 28 11:10:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Nov 2005 17:10:10 +0100 Subject: General question about Python design goals References: Message-ID: Christoph Zwerschke wrote: > But the problem is that the tutorials and manuals give the impression > that the difference between lists and tuples is only mutablity versus > immutability. both the tutorial and the FAQ discusses the difference in terms of use cases and recommended usage. > Maybe I am I lacking the satori of a real Python Zen master? I suggest you look up the phrase "bike shed effect". next, go read some recent PEP:s to see what's really going on in the Python design universe. From ark at acm.org Sun Nov 27 13:56:36 2005 From: ark at acm.org (Andrew Koenig) Date: Sun, 27 Nov 2005 18:56:36 GMT Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: "mojosam" wrote in message news:1132947046.639811.14650 at g49g2000cwa.googlegroups.com... > I will be doing the bulk of the coding on my own time, because I need > to be able to take these tools with me when I change employers. > However, I'm sure that in the course of using these tools, I will need > to spend time on the job debugging or tweaking them. I do not want my > current employer to have any claim on my code in any way. Usually if > you program on company time, that makes what you do a "work for hire". > I can't contaminate my code like that. Does that mean the GPL is the > strongest defense in this situation? It probably means that the only reliable defense is to get a written release from your employer. If you want to be more confident about the situation, consult a lawyer. From sybrenUSE at YOURthirdtower.com.imagination Thu Nov 17 07:39:02 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 17 Nov 2005 13:39:02 +0100 Subject: sqlite utf8 encoding error References: <1132228020.486726.26630@g47g2000cwa.googlegroups.com> Message-ID: Greg Miller enlightened us with: > 'Keinen Text f?r ?bereinstimmungsfehler gefunden' You posted it as "Keinen Text fr ...", which is Latin-1, not UTF-8. > I thought that all strings were stored in unicode in sqlite. Only if you put them into the DB as such. Make sure you're inserting UTF-8 text, since the DB won't do character conversion for 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 timr at probo.com Thu Nov 3 01:43:08 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 03 Nov 2005 06:43:08 GMT Subject: String Identity Test References: Message-ID: <0acjm1t86krvao310k8cjutkdf8agp4t8q@4ax.com> "Richard Brodie" wrote: > >"Roy Smith" wrote in message news:dk81pf$s2p$1 at panix2.panix.com... > >> On the other hand, I can't imagine any reason why you would want to >> define such a class, > >PEP 754? My congratulations on a very subtle and somewhat multicultural joke... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From opstad at batnet.com Mon Nov 28 16:20:31 2005 From: opstad at batnet.com (Dave Opstad) Date: Mon, 28 Nov 2005 13:20:31 -0800 Subject: PYTHONDOCS on OSX References: <1133144504.909363.219530@g49g2000cwa.googlegroups.com> Message-ID: In article <1133144504.909363.219530 at g49g2000cwa.googlegroups.com>, "Robert Hicks" wrote: > How do I set this variable in my .bash_profile? I have the html docs in > /usr/local/PythonDocs. I have a line in my .profile like this: export PYTHONDOCS='/Users/opstad/Documents/Developer Docs/Python-Docs-2.4.1' So by analogy, you could try adding this to your profile: export PYTHONDOCS='/usr/local/PythonDocs' Dave From steve at holdenweb.com Sat Nov 5 21:45:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 06 Nov 2005 02:45:10 +0000 Subject: Using Which Version of Linux In-Reply-To: References: Message-ID: Dan M wrote: > On Sat, 05 Nov 2005 04:26:38 -0600, blahman wrote: > > >>ok, i m going to use Linux for my Python Programs, mainly because i >>need to see what will these fork() and exec() do. So, can anyone tell >>me which flavour of linux i should use, some say that Debian is more >>programmer friendly, or shold i use fedora, or Solaris. Because these >>three are the only ones i know of that are popular and free. > > > Personally I would recommend staying away from Fedora unless you have a > friend who is well-versed in it and willing to help. I like the > distributin ok (I run it on the laptop I'm writing this from) but it uses > RPMs for package distribution, and the rpm tools don't know how to > automatically downloaded dependencies like yum or apt do. Because of that > I have to say that the RPM package tools suck quite badly. > > Debian and SUSE are both pretty good choices. I used yum on Fedora Core 2, and it downloaded and installed dependencies fine. 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 bonono at gmail.com Sun Nov 20 19:45:23 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 16:45:23 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: Message-ID: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> Ben Finney wrote: > Another possibility: ordered dictionaries are not needed when Python > 2.4 has the 'sorted' builtin. > What does sorted() have anythng to do with orders like insertion order, or some arbitary order that instead of a,b,c,d,e, I want it as e, c, b, d, a ? Personally, I have needs for ordered dict but I don't think it should be in standard library though, as different situation called for different behaviour for "ordered" and skewing my code to a standard lib way is no good. What I think is better is like the itertools recipe of giving example of how one can make their own based on the needs. From bignose+hates-spam at benfinney.id.au Thu Nov 17 22:32:46 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Nov 2005 14:32:46 +1100 (EST) Subject: Immutable instances, constant values Message-ID: Howdy all, I've recently packaged 'enum' in PyPI. In its description, I make the claim that it creates "immutable" enumeration objects, and that the enumeration values are "constant" values. This raises questions. Is there any difference between a Python immutable value, and a constant? I suppose "constant" also implies that the *name* binds unchangeably to a particular value. Is that meaningful? How does one actually ensure an object is immutable? Is it a matter of overriding a bunch of methods, or is ther a neater way? Is it bad style to make a user-defined class that creates immutable objects? Why? In the case of 'enum', can anyone argue for or against an enumerated type being immutable? Its values being constant? -- \ "The best ad-libs are rehearsed." -- Graham Kennedy | `\ | _o__) | Ben Finney From jstroud at mbi.ucla.edu Mon Nov 7 23:14:52 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 7 Nov 2005 20:14:52 -0800 Subject: overloading *something Message-ID: <200511072014.52919.jstroud@mbi.ucla.edu> Hello All, How does one make an arbitrary class (e.g. class myclass(object)) behave like a list in method calls with the "*something" operator? What I mean is: myobj = myclass() doit(*myobj) I've looked at getitem, getslice, and iter. What is it if not one of these? And, how about the "**something" operator? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From everettcc at hotmail.com Tue Nov 15 22:54:03 2005 From: everettcc at hotmail.com (Chad Everett) Date: Tue, 15 Nov 2005 21:54:03 -0600 Subject: Newb ? Message-ID: Hello all, Have a problem here with a challenge from a book I am reading. Any help is much appreciated. I am trying to run a program that asks the user for a statement and then prints it out backwards. this is what I have. It does not print anything out. I assume that I have something out of whack with my high and low statements. Thanks for you help. print "\n\nWelcome to the Backwards Message Display." print message = raw_input("\nPlease Enter a Message.") high = len(message) low = -len(message) print print message[high:low] print print raw_input("Please Press Enter to Exit") From tim.tadh at gmail.com Mon Nov 28 01:00:36 2005 From: tim.tadh at gmail.com (Tim Henderson) Date: 27 Nov 2005 22:00:36 -0800 Subject: should python have a sort list-map object in the std-lib? In-Reply-To: <1h6pg7c.1q4nxaf4virbiN%aleax@mail.comcast.net> References: <1h6pg7c.1q4nxaf4virbiN%aleax@mail.comcast.net> Message-ID: <1133157636.793917.206740@g47g2000cwa.googlegroups.com> ahh, i hadn't thought of using a proirity queue but that is the correct solution most of the time, except i suppose when you have input that causes you to excessively reheap which could be problematic. i may still look into writing a general sorted map though, it could be useful especially if there were and easy way to set the type of functionality required with out resorting to several different types of sorted-maps. From bonono at gmail.com Tue Nov 29 22:49:42 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 29 Nov 2005 19:49:42 -0800 Subject: Computer Language Shootout In-Reply-To: <438d1bfd.271765047@news.oz.net> References: <1133298307.938958.186070@f14g2000cwb.googlegroups.com> <1133299669.010298.283100@g14g2000cwa.googlegroups.com> <1133302092.368063.235410@o13g2000cwo.googlegroups.com> <438d040d.265637266@news.oz.net> <1133318074.428631.320870@g14g2000cwa.googlegroups.com> <438d1bfd.271765047@news.oz.net> Message-ID: <1133322582.901444.115760@f14g2000cwb.googlegroups.com> Bengt Richter wrote: > >Interestingly, I find this response quite compatible with the > >personality of this group. > Which "this"? ;-) > I meant his response. From roy at panix.com Thu Nov 17 09:24:56 2005 From: roy at panix.com (Roy Smith) Date: Thu, 17 Nov 2005 09:24:56 -0500 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1h62slm.up4s2tqyk1gjN%aleax@mail.comcast.net> <437C36EA.8010600@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Alas and alack, I have to write code which is backwards > compatible with older versions of Python: > [...] > NameError: name 'iter' is not defined > > What should I do when I can't rely on functions that > don't exist in older versions of Python? It really sucks trying to support obsolete environments. Been there, done that. But sometimes you just have to pull out the duct tape and deal with the problem any way you can. Parsing undocumented exception strings is sort of like screen scraping; it's good to know that it's possible as an absolute last resort, but you really want to put some effort into finding a better way. You could use two nested try blocks that both catch TypeErrors, one enclosing the entire loop, the other enclosing just the body. Anything that gets caught by the outer try had to have been generated within the loop control code itself: ------------------------- Roy-Smiths-Computer:play$ cat iter.py #!/usr/bin/env python def doSomething (obj): sum = 0 try: for i in obj: try: sum += i except TypeError, ex: print "exception (%s) in the inner block" % ex return except TypeError, ex: print "non iterable object (%s)" % ex return print "sum = %d" % sum doSomething ([1, 2, 3]) doSomething (["one", "two", "three"]) doSomething (0) Roy-Smiths-Computer:play$ ./iter.py sum = 6 exception (unsupported operand type(s) for +=: 'int' and 'str') in the inner block non iterable object (iteration over non-sequence) ------------------------- This is pretty ugly, but I think it does what you want. It could be made a bit less ugly by refactoring the body of the for loop into another function. BTW, if you do resort to trying to parse the exception messages, and it breaks in some future code, you might have me to blame. I submitted a bug report a while back which, if it's ever acted on, would break your code! http://sourceforge.net/tracker/index.php?func=detail&aid=1187437&group_id=54 70&atid=105470 From jmdeschamps at gmail.com Thu Nov 10 10:59:19 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 10 Nov 2005 07:59:19 -0800 Subject: Recommendation please: forming an XML toolkit Message-ID: <1131638359.066478.186620@g44g2000cwa.googlegroups.com> I'm asking help on this topic of building a tools foundation for future XML projects because of the sheer volume of possibilities I will not have the time to check/try/test in detail. This question is a bit like the ones pertaining to 'Which web framework to use?', there is a lot of good stuff out there, and often it boils down to personnal preference, mind-fitting interface and such BUT... to make it more precise I will give more context on the future projects involved... I've done some homework trying out a few packages based on published tutorial: Boddie's Python and XML: An Introduction (for minidom), Lundh's elementTree examples, I read a bit about Amara, pyXML, others. I've read a bit on ease-of-use, benchmarks, pythonesque versus job-protection perspectives, I've even tried building my own xml2PythonObjects2xml tools Finally, I've read-up a few threads pertaining to the question 'which XML packages to use' ! Some considerations I have using XML : 1- representing inter-connected academic articles in text-based files whitout a sopecific BD package 2- being 'easily' able to modify the structure of these documents as search tools evolve 3- searching through these articles often, and with evolving algortihmic complexity (from word base search to RDF-type meta data, to OWL-type semantic information, etc) 4- In a context where I'm (in a practical form) evangelizing the use of Python as a great tool from going from 'this could be a new approach' to 'this piece of code realizes that approach' (managers need to be confident that they could choose to make this set of articles evolve using other languages (other developpers not caring for Python for example, but Java instead) and the infobase would be directly accessible and algorithms understandable from a 'popular' xml-manipulation point-of-view (Using DOM, I guess a regular DOM-SAX Java developper would understand Python code, but would they if the code relied heavily on elementTree (for example) 5- relying as less as possible on complex third-party libs (to use A, first get B from elsewhere, which itself requires C from still another place...) I DON'T mind the simple package (PIL comes to mind here) 6- VERY IMPORTANT CONSIDERATION - That I can keep my focus on developing algorithms, MINIMIZING XML clutter I don't want to become a XML guru - I like the simple principle of XML as a tree of tagged elements that have attributes and text data... Thanks for any and all who read this, and those who have experience ressembling what I'm about to embark on for your help ! Jean-Marc From s_david_rose at hotmail.com Sat Nov 26 14:14:18 2005 From: s_david_rose at hotmail.com (Dave Rose) Date: Sat, 26 Nov 2005 14:14:18 -0500 Subject: Dynamic classes References: Message-ID: Duh! how dumb am I? A dictionary solves all those problems, with each entry named, and the value of each name could be a class instace. plus all the class instances can be iterated by a loop. Thanks Piet & Alex for your guidance! -Dave "Piet van Oostrum" wrote in message news:m2sltk4n4m.fsf at ordesa.cs.uu.nl... >>>>>> "Dave Rose" (DR) wrote: > >>DR> Hello all. >>DR> I was wondering if creating classes could be dynamic. I want to know >>DR> if I can make a class Person, then read in a list of names (say >>DR> people's names) so then I can have a class instance created for each >>DR> name in the list? > > If you have the class Person, you are not creating it dynamically. And of > course you can create instances dynamically as you describe. > >>DR> Why do I want to do this? I was just thinking if I had a name on >>the >>DR> list, Dave, I could then be able to read the name in the list, and >>DR> assign Maria.birthday = <> and all the other attributes I would want >>DR> to use a class for, except this is dynamic. I don't know how to >>DR> iterate thru the list to assign the different attributes yet, but this >>DR> seemed reasonable to want to do, and thought I could learn from this. > > If I understand you correctly, you want to create a variable with name > 'Maria' when you read the name "Maria". Creating variables dynamically is > possible in Python but is almost always the wrong thing to do. Instead it > is usually better to use a dictionary. > > class Person: > def __init__(self, name): > self.name = name > > persons = {} > > now you have a loop that reads persons' names, say in name. > > myperson = persons[name] = Person(name) > > Now I suppose you want to read additional attributes, while the list of > possible attributes is in principle open. > > So suppose you have read the attribute name in attr and the value in val. > The you can dynamically create an instance attribute with: > > setattr(myperson, attr, val) > -- > Piet van Oostrum > URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] > Private email: piet at vanoostrum.org From peter.mosley at talk21.com Mon Nov 28 09:06:33 2005 From: peter.mosley at talk21.com (peter.mosley at talk21.com) Date: 28 Nov 2005 06:06:33 -0800 Subject: How to get started in GUI Programming? References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1133186792.984959.261550@g43g2000cwa.googlegroups.com> A big thank you to all who responded. There are too many to reply individually, but to summarise ... Thomas G?ttler gave a link to an example program, editMetadata.py which uses yes no dialogs and scaled images. I've not yet tried to learn from this, but looking at the code it seems to provide exactly what I am looking for. It uses the gtkMessageDialog class, which I hadn't come across (the tutorial doesn't seem to mention it?) Others recommended wxPython, PyQt and various derivatives. The trouble is there's too much choice! But my experience is that under Linux nothing ever works out of the box, and so I am reluctant to invite more grief by installing fresh packages until I am sure those already installed are not adequate. Easygui had some supporters. I had already come across this, and while I agree it is a delightfully simple tool to use, and ideal for i/o operations, it is not sufficiently flexible for my needs. One development is that my local public library has, to my surprise, managed to locate a copy of 'Python and Tkinter Programming' by J. Grayson. I've not read it yet, and an initial flick through doesn't look too promising but maybe I am mistaken.. I acknowledge that Tkinter is a bit dated, and may not have a native 'look and feel', but for me this would be outweighed by an accessible textbook. So currently the choice is between continuing with PyGtk, using the editMetadata.py code as a model, or Tkinter using Grayson's book. I'll try both and see which is more successful. Once again thank you to all who responded. From robert.dowell at gmail.com Tue Nov 8 13:58:14 2005 From: robert.dowell at gmail.com (robert.dowell at gmail.com) Date: 8 Nov 2005 10:58:14 -0800 Subject: debugger In-Reply-To: References: <1131474688.096736.173480@z14g2000cwz.googlegroups.com> Message-ID: <1131476294.676867.161230@f14g2000cwb.googlegroups.com> Benji York wrote: > robert.dowell at gmail.com wrote: > > Benji York wrote: > >>You might like Winpdb: > >>http://www.digitalpeers.com/pythondebugger/ > > > > Not Found > > > > The requested URL /pythondebugger/-- was not found on this server. > > Apache/2.0.52 (Red Hat) Server at www.digitalpeers.com Port 80 > > Works for me. > -- > Benji York Yeah, for some reason my browser was appending /-- to the link. I figured that out (little slow today) and pulled my post. From codecraig at gmail.com Wed Nov 9 10:21:22 2005 From: codecraig at gmail.com (py) Date: 9 Nov 2005 07:21:22 -0800 Subject: parse data Message-ID: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> I have some data (in a string) such as.... person number 1 Name: bob Age: 50 person number 2 Name: jim Age: 39 ...all that is stored in a string. I need to pull out the names of the different people and put them in a list or something. Any suggestions...besides doing data.index("name")...over and over? thanks! From grflanagan at yahoo.co.uk Fri Nov 18 09:39:10 2005 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 18 Nov 2005 06:39:10 -0800 Subject: Adding through recursion In-Reply-To: <1132324258.091428.287910@g44g2000cwa.googlegroups.com> References: <1132320167.127338.92460@g47g2000cwa.googlegroups.com> <1132324258.091428.287910@g44g2000cwa.googlegroups.com> Message-ID: <1132324750.303868.265700@f14g2000cwb.googlegroups.com> martin.clausen at gmail.com wrote: > I still don't get it. I tried to test with x = 0 and found that to > work. How come since the value of y is right and it is printed right it > "turns into" None when returned by the return statement ? Martin, -a function should either return something or not. Your function has two exit points, one explicitly returns a value, one doesn't (and so defaults to returning None). - trace through the function with pencil and paper for small values of x and y def add(x, y): if x: x -= 1 y += 1 add(x,y) else: print y def ADD(x, y): if x: x -= 1 y += 1 return ADD(x,y) else: return y >>>add(5,6) 11 >>>ADD(5,6) 11 >>>z = add(5,6) 11 >>>print z None >>>z = ADD(5,6) >>>print z 11 Gerard From falcon3166 at hotmail.com Tue Nov 15 20:33:40 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 15 Nov 2005 18:33:40 -0700 Subject: Can anyone tell me if pygame and Tkinter can work together? In-Reply-To: <20051116012828.GA13790@unpythonic.net> Message-ID: Thanks. I was going to use TKInter to pop up a message box, then use pygame to run the game and display the score on the playing surface. Is this still possible (I'm using Python 2.4.1 and Pygame 1.7.0 on WinXP with Service Pack 2)? Nathan Pinno Nathan Pinno, Owner/operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -----Original Message----- From: jepler at unpythonic.net [mailto:jepler at unpythonic.net] Sent: November 15, 2005 6:28 PM To: Nathan Pinno Cc: python-list at python.org Subject: Re: Can anyone tell me if pygame and Tkinter can work together? It's likely to be a challenge; each one has its own "event loop", and the exact pitfalls of trying to use both at the same time probably depend on the operating system too. For instance, on X, Tk and SDL probably both expect full control of the handlers registered with XSetErrorHandler and XSetIOErrorHandler, but Xlib only permits a single handler. Jeff From jzgoda at o2.usun.pl Wed Nov 2 12:23:21 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 02 Nov 2005 18:23:21 +0100 Subject: Xah's edu corner: the Journey of Foreign Characters thru Internet In-Reply-To: References: <1130852975.525590.145080@f14g2000cwb.googlegroups.com><1130874345.236356.248110@g14g2000cwa.googlegroups.com><86d5lk15ai.fsf@bhuda.mired.org> <1130895395.648837.9440@g43g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh napisa?(a): >>And if anyone wants to take the responsibiblity to warn the general >>public that it is troll so innocent readers may not be tempted into >>one, at least do it privately > > huh? Don't fed the troll, don't give him any public audience. Easy. -- Jarek Zgoda http://jpa.berlios.de/ From bokr at oz.net Wed Nov 30 00:53:34 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 30 Nov 2005 05:53:34 GMT Subject: newbie question concerning formatted output References: Message-ID: <438d2db4.276300649@news.oz.net> On Tue, 29 Nov 2005 17:40:08 GMT, Thomas Liesner wrote: [...] >This is the codesnippet i am using: Sorry, I made no comment on your actual code. Some follows. > >#!/usr/bin/python > >import string I'm not seeing the need for importing string >inp = open("xyplan.nobreaks","r") inp = open("xyplan.nobreaks") # defaults to "r" >data = inp.read() >for words in data.split(): At this point words would have to be a group of three successive words, joined with a single space separator. So we can still use your loop and only print with newline on the last of every group of three. So we can use a counter to tell where in the cycle we are, e.g., combining read() and split() and enumerating the split sequence, (untested) for i, words in enumerate(inp.read().split()): if i%3 < 2: print words, # trailing comma makes a space separator if next print continues line output else: # do as before and print final word with newline > print words >inp.close() > >Any hints? Upgrade if you don't have 2.4 ;-) Then you can do a oneliner with a single print ;-) Set up the data file example: >>> open('xyplan.nobreaks','w').write("""\ ... 3905 ... 3009 ... 0000 ... 4508 ... f504 ... 0000 ... 3707 ... 5a07 ... 0000 ... """) Show it as is: >>> print '----\n%s----'%open('xyplan.nobreaks').read() ---- 3905 3009 0000 4508 f504 0000 3707 5a07 0000 ---- Now the one-liner, FWIW ;-) >>> print '\n'.join(' '.join(z) for it in [(ln.strip() for ln in open('xyplan.nobreaks'))] for z in (zip(it, it, it) )) 3905 3009 0000 4508 f504 0000 3707 5a07 0000 Regards, Bengt Richter From amfr.org at gmail.com Mon Nov 21 18:24:16 2005 From: amfr.org at gmail.com (amfr) Date: 21 Nov 2005 15:24:16 -0800 Subject: Command line In-Reply-To: References: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> Message-ID: <1132615456.729570.85360@g44g2000cwa.googlegroups.com> What I am trying to do is call perl on the command line. Also, do any of these functions return the data recievved from the command? From petr at tpc.cz Sat Nov 19 03:58:57 2005 From: petr at tpc.cz (Petr Jakes) Date: 19 Nov 2005 00:58:57 -0800 Subject: termios.tcgetattr(fd) error: (22, 'Invalid argument') Message-ID: <1132390737.695615.167810@g47g2000cwa.googlegroups.com> On my box (Fedora Core4, Python 2.4.1) I am getting following error: >>> import termios, sys >>> fd = sys.stdin.fileno() >>> oldSettings = termios.tcgetattr(fd) Traceback (innermost last): File "", line 1, in ? error: (22, 'Invalid argument') Thanks for your comments. Petr Jakes From fuzzyman at gmail.com Tue Nov 29 04:23:06 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Nov 2005 01:23:06 -0800 Subject: New Ordered Dictionery to Criticise In-Reply-To: <438b64e0$0$21049$9b622d9e@news.freenet.de> References: <1133197857.754686.133740@g44g2000cwa.googlegroups.com> <438b64e0$0$21049$9b622d9e@news.freenet.de> Message-ID: <1133256186.829977.228030@f14g2000cwb.googlegroups.com> Martin v. L?wis wrote: > Fuzzyman wrote: > > Criticism solicited (honestly) :-) > > A couple of minor points: > - I would drop 2.2 compatibility There are a lot of cheap hosting accounts where Python 2.2 is all that is available. I would only drop support if there is some *compelling* reason to do so. > - self=self isn't needed in the functions, because of > nested scopes Cool, I'll test this out. > - popitem(self) can be rewritten as > > def popitem(self): > try: > key = self._sequence.pop() > except IndexError: > # always try to give the same exception string as > # dict > raise KeyError("popitem(): dictionary is empty") > return key, self.pop(key) > Yup, that's nicer - thanks. > - One problem with the FancyDict is that it allows > d.keys.append(100) Are you sure ? No file given. Alias System Command ------------------------------ cls cls copy copy ddir dir /ad /on dir dir /on echo echo ldir dir /ad /on ls dir /on mkdir mkdir ren ren rmdir rmdir ------------------------------ Total number of aliases: 10 Movable Python IPython Interactive Shell. See the manual for a list of features and tips. Ctrl-D to exit. >>> from odict import FancyODict >>> d = FancyODict() >>> d Out[3]:{} >>> d.keys ----------------------> d.keys() Out[4]:[] >>> d.keys.append('anything') --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) \configobj4\pythonutils\odict.py in append(self, item) 713 def __iadd__(self, other): raise TypeError('Can\'t add in place to keys') 714 def __imul__(self, n): raise TypeError('Can\'t multiply keys in place') --> 715 def append(self, item): raise TypeError('Can\'t append items to keys') 716 def insert(self, i, item): raise TypeError('Can\'t insert items into keys') 717 def pop(self, i=-1): raise TypeError('Can\'t pop items from keys') TypeError: Can't append items to keys >>> All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > Regards, > Martin From lucmult at gmail.com Thu Nov 17 07:08:59 2005 From: lucmult at gmail.com (lucmult at gmail.com) Date: 17 Nov 2005 04:08:59 -0800 Subject: Python Library Reference - question References: <1132217639.080443.144910@g44g2000cwa.googlegroups.com> Message-ID: <1132229339.079343.223590@z14g2000cwz.googlegroups.com> See this nice tool for Firefox. It's like a chm form live updated. :) http://projects.edgewall.com/python-sidebar []'s Luciano Pacheco From p.c.j.kleiweg at rug.nl Wed Nov 16 20:26:10 2005 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Thu, 17 Nov 2005 02:26:10 +0100 Subject: Quitting a Tkinter application with confirmation In-Reply-To: References: Message-ID: Fredrik Lundh schreef op de 16e dag van de slachtmaand van het jaar 2005: > Peter Kleiweg wrote: > > > I want the program to behave identical if the 'close' button of > > the application window is clicked. I tried the code below, > > using a class derived from Tk that redefines the destroy > > method. That seems to work. At least on Linux. > > > > My questions: > > > > Is this the correct and save way to do this? Will it work on any > > operating system? Shouldn't I do some event capturing instead? > > the right way to do this is to implement a WM_DELETE_WINDOW > protocol handler: > > http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols > > in your case, adding > > root.protocol("WM_DELETE_WINDOW", root.destroy) > > to the right place should be enough. Yes, that works. By the way, this example ends the program with root.destroy(). I used root.quit(). Is there a reason for using one or the other, or does it not matter? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/~kleiweg/ls.html From steve at REMOVEMEcyber.com.au Thu Nov 17 03:07:31 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 17 Nov 2005 19:07:31 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> <1132186931.445973.140900@o13g2000cwo.googlegroups.com> Message-ID: <437C3A43.1030303@REMOVEMEcyber.com.au> The Eternal Squire wrote: > Plenty of case law exists behind judgements made to repair loss of > sales opportunites... these are called infringement upon sales > territories.. Is that supposed to impress me? There are plenty of lousy laws on the books being enforced. Oh yeah, that's right, they are the Authorities, and the Authorities can do no wrong. -- Steven. From eurleif at ecritters.biz Thu Nov 10 09:34:04 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 10 Nov 2005 14:34:04 GMT Subject: Confusion about __call__ and attribute lookup In-Reply-To: <43734796$1_1@newspeer2.tds.net> References: <43734796$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > But why doesn't Foo.__call__ shadow type.__call__? Normally an instance > attribute takes precedence over a class attribute. Is it something > special about how function call syntax is handled internally, or do all > special methods work this way, or is there something else going on? New-style classes look up special methods on the class, not on the instance: >>> class Foo(object): ... def __invert__(self): ... return 'foo' ... >>> x = Foo() >>> ~x 'foo' >>> x.__invert__ = 123 >>> x.__invert__() Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable >>> ~x # equivalent to type(x).__invert__() 'foo' From sybrenUSE at YOURthirdtower.com.imagination Sat Nov 12 04:20:08 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 12 Nov 2005 10:20:08 +0100 Subject: about try statement References: Message-ID: Shi Mu enlightened us with: > very hard for me to understand the difference between try...except > and try...finally Within a 'try' block, if an exception is called and a matching 'except' block is found, that block will be used to handle the expression. >From the documentation of the "return" keyword: "When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function." Note that there is no talk about exceptions in this. 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 aleax at mail.comcast.net Fri Nov 18 12:02:18 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 18 Nov 2005 09:02:18 -0800 Subject: Importing a class without knowing the module References: <867jb6n7cw.fsf@bhuda.mired.org> <86veyqlnrn.fsf@bhuda.mired.org> <1h66rw8.wlp7nb19e5629N%aleax@mail.comcast.net> <86k6f6lgvy.fsf@bhuda.mired.org> <1h66w9j.1d82do2qfe2b1N%aleax@mail.comcast.net> <86zmo2jvsw.fsf@bhuda.mired.org> Message-ID: <1h67qx0.1y62ktrcq00pbN%aleax@mail.comcast.net> Mike Meyer wrote: ... > A classes __module__ attribute doesn't always tell you the name of the > module - or at least, not a name that would be usefull for the the OPs > use case. That's the case where you don't have the module name. The How do you arrange a module so that its classes' __module__ attributes don't tell you the name of the module "that would be useful", yet the module's __file__ DOES give you information that you can usefully process, heuristically I assume, to infer a module name that IS useful? I just don't see it, which of course doesn't mean it can't be done, with sufficient evil ingenuity. But since you're the one arguing that this case is important enough to be worth dwelling on, I'd rather see some specific examples from you, to understand whether my gut reaction "if possible at all, this has gotta be such a totally CORNER, ARTIFICIAL case, that it's absurd to bend over backwards to cover it" is justified, or whether I'm misjudging instead. > reference to a classes __file__ attribute was meant to be to the > modules __file__ attribute - I'm surprised that no one picked up on > that. Again, assuming that the module has an __file__ attribute at > all. Getting the __file__ attribute to a module you don't know the > name of is a bit tricky, but possible. If you have the module object, getting its __file__ isn't hard -- but then, neither is getting its module name... m.__file__ and m.__name__ are just about as accessible as each other. Of the two, the one more likely to be useless would be the __file__ -- import hooks (zipimport or more deviously sophisticated ones) might mean that string is not a file path at all; __name__ is supposed to be the string key of that module object within sys.modules, and it is, I think, far less likely that any tricks will have been played wrt that -- plus, you can easily doublecheck by scouring sys.modules. I just cannot see ANY case where I would want to try heuristics on some __file__ attribute (hopefully but not necessarily a filename) to try and recover a __name__ that appears to be missing, mangled, or incorrect; my instinct would be to raise exceptions informing the user that what they're trying to marshal is too weird and strange for their own good, and let them deal with the situation. But as I said, that may depend on a failure of the imagination -- if you can show me compelling use cases in which heuristics on __file__ prove perfectly satisfactory where just dealing with __name__ wouldn't, I'm quite ready to learn! Alex From twic at urchin.earth.li Wed Nov 9 12:45:07 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 9 Nov 2005 17:45:07 +0000 Subject: PyFLTK - an underrated gem for GUI projects In-Reply-To: <7xhdap47t1.fsf@ruckus.brouhaha.com> References: <7xhdap47t1.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 6 Nov 2005, it was written: > aum writes: > >> To me, wxPython is like a 12-cylinder Hummer, ... Whereas PyFLTK feels >> more like an average suburban 4-door sedan > > Interesting. What would Tkinter be at that car dealership? A '70s VW Beetle - it's been going for ever, but it's still rock solid, even if it does look a bit naff. Also, hippies love it. tom -- [of Muholland Drive] Cancer is pretty ingenious too, but its best to avoid. -- Tex From gregor.jan at NOSPAMquick.cz Sat Nov 5 04:50:34 2005 From: gregor.jan at NOSPAMquick.cz (Jan Gregor) Date: Sat, 5 Nov 2005 10:50:34 +0100 Subject: modifying source at runtime - jython case Message-ID: Hello folks I want to apply changes in my source code without stopping jython and JVM. Preferable are modifications directly to instances of classes. My application is a desktop app using swing library. Python solutions also interest me. Solution similiar to "lisp way" is ideal. Thanks for response, Jan From steve at REMOVETHIScyber.com.au Fri Nov 4 06:40:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 22:40:04 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: On Fri, 04 Nov 2005 07:31:46 +0000, Antoon Pardon wrote: >> The model makes sense in my opinion. If you don't like it then there are >> plenty of other languages to choose from that have decided to implement >> things differently. > > And again this argument. Like it or leave it, as if one can't in general > like the language, without being blind for a number of shortcomings. > > It is this kind of recations that make me think a number of people is > blindly devoted to the language to the point that any criticism of > the language becomes intollerable. There are good usage cases for the current inheritance behaviour. I asked before what usage case or cases you have for your desired behaviour, and you haven't answered. Perhaps you missed the question? Perhaps you haven't had a chance to reply yet? Or perhaps you have no usage case for the behaviour you want. Some things are a matter of taste: should CPython prefer <> or != for not equal? Some things are a matter of objective fact: should CPython use a byte-code compiler and virtual machine, or a 1970s style interpreter that interprets the source code directly? The behaviour you are calling "insane" is partly a matter of taste, but it is mostly a matter of objective fact. I believe that the standard model for inheritance that you call insane is rational because it is useful in far more potential and actual pieces of code than the behaviour you prefer -- and the designers of (almost?) all OO languages seem to agree with me. The standard behaviour makes it easy for code to do the right thing in more cases, without the developer taking any special steps, and in the few cases where it doesn't do the right thing (e.g. when the behaviour you want is for all instances to share state) it is easy to work around. By contrast, the behaviour you want seems to be of very limited usefulness, and it makes it difficult to do the expected thing in almost all cases, and work-arounds are complex and easy to get wrong. The standard behaviour makes it easy for objects to inherit state, and easy for them to over-ride defaults. The behaviour(s) you and Graham want have awkward side-effects: your proposed behaviour would mean that class attributes would mask instance attributes, or vice versa, meaning that the programmer would have to jump through hoops to get common types of behaviour like inheriting state. The behaviour you want would make it too easy to inadvertently have instances share state. Normally we want instances to share behaviour but have unique states -- you would change that. Why? If it is just a matter of taste, you are welcome to your opinion. But you don't say that the standard behaviour is "ugly", you say it is "insane", that is, irrational, and that the behaviour you want is rational. That's an objective claim: please explain what makes your behaviour more rational than the standard behaviour. Is your behaviour more useful? Does it make code easier to write? Does it result in more compact code? What usage cases? Or is it just a subjective judgement on your part that it would be neater? -- Steven. From norman at littletank.org Thu Nov 10 08:30:05 2005 From: norman at littletank.org (Norman Silverstone) Date: Thu, 10 Nov 2005 13:30:05 +0000 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> <1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: < snip> > I assume the way the computer is going to guess is by trying some > number, and you respond either that it's guessed right, or to go lower, > or to go higher. Yes, that is correct. > > In that case, think of "bisection". Originally, all the computer knows > is that the number is in some range, say 0 to 100. It can then guess > the midpoint, 50. If it's right, yay! Otherwise: if it's told to go > lower, then the range is now 0 to 49 -- if higher, it's 51 to 100; in > each case the range was just halved (actually, a bit more than halved). Thank you, I thought that might be the case. So, I will have to settle down and try to write some pseudo-code first. I hope to be back. Norman From qwweeeit at yahoo.it Thu Nov 3 10:36:53 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 3 Nov 2005 07:36:53 -0800 Subject: Filepath string manipulation help References: <1130959950.485233.230230@z14g2000cwz.googlegroups.com> Message-ID: <1131032213.559554.163730@g14g2000cwa.googlegroups.com> Hi mjakowlew, to get file basename in Linux I use simply: filepath.split('/')[-1] But in Windows, being the dir separator '\', you get into trouble if the dir or file name begins with one of the "escape sequences": \a ASCII Bell (BEL) \x07 \b ASCII Backspace (BS) \x08 \f ASCII Formfeed (FF) \x0c \n ASCII Linefeed (LF) \r ASCII Carriage Return (CR) \t ASCII Horizontal Tab (TAB) \v ASCII Vertical Tab (VT) \x0b (from the ref. suggested by Fredrik Lund). To solve the problem you must use "raw strings", as suggested by the aforementioned expert. So your filepath ('c:\documents\web\zope\file.ext') becomes r'c:\documents\web\zope\file.ext' which protects the '\' by escaping it ('\\'). With such a trick you can obtain the file basename with: filepath.split('\\')[-1]. Bye. From killet at killetsoft.de Tue Nov 22 08:54:29 2005 From: killet at killetsoft.de (killet at killetsoft.de) Date: 22 Nov 2005 05:54:29 -0800 Subject: Geodetic Functions as DLL Message-ID: <1132667669.647969.61320@g47g2000cwa.googlegroups.com> Hi, here is an information for the people who must develop programs with geodetic background and who asked me for a Englisch documentation of the geodetic functions included in GeoDLL. The DLL is present now with a complete English and German documentation! In the Dynamic Link Library are geodetic functions like coordinate transformation, reference systems, meridian strip changes, user defined coordinate and reference systems, distance calculation, maps functions and other more geodetic functions. Accurate and high performant coordinate transformations of all EU countries, US and Canadian state plane, Australien systems and other systems all over the world are contained. GeoDLL can be bind with different programming languages into WINDOWS applications. The DLL is delivered with interface source codes to many programming languages. You find a free linkable test version of GeoDLL and much more information on the site http://www.killetsoft.de/geodlle.htm. Best regards, Fred From erniedude at gmail.com Wed Nov 2 11:28:33 2005 From: erniedude at gmail.com (Ernesto) Date: 2 Nov 2005 08:28:33 -0800 Subject: Subprocess.Popen - passing args help Message-ID: <1130948913.627882.194220@g49g2000cwa.googlegroups.com> I'm trying to use Popen to do some command line work Windows XP style. I have devcon.exe which I would use on a Windows command line like so: devcon disable "@USB\VID_05E3&PID_0605\5&2CE74B9E&1&6" Using subprocess.Popen, I have something like this: subprocess.Popen([r"devcon.exe","disable",'"USB\VID_05E3&PID_0605\5&2CE74B9E&1&6"']).wait(); For some reason, the parameters are not getting passed to devcon correctly. Devcon executes, but doesn't behave the same way it does if I type in the command above at a Win Prompt. Any clues as to how to pass these parameters? Thanks, From ruach at chpc.utah.edu Tue Nov 22 13:05:52 2005 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Tue, 22 Nov 2005 11:05:52 -0700 Subject: python win32 and COM? for internet monitoring In-Reply-To: <1132681626.160678.237990@g47g2000cwa.googlegroups.com> References: <1132681626.160678.237990@g47g2000cwa.googlegroups.com> Message-ID: Graham Fawcett wrote: > You might want to look into PCAP (a.k.a libpcap), which is the > network-sniffing libary used by Ethereal, among other programs. Much > more portable than COM, and there are Python wrappers for it, IIRC. > > You could also implement an HTTP proxy server in Python; Google should > turn up numerous existing implementations. > > Graham > Thanks for the tip, I'll check that out. -- Matthew From sigzero at gmail.com Mon Nov 28 17:27:25 2005 From: sigzero at gmail.com (Robert Hicks) Date: 28 Nov 2005 14:27:25 -0800 Subject: PYTHONDOCS on OSX In-Reply-To: References: <1133144504.909363.219530@g49g2000cwa.googlegroups.com> Message-ID: <1133216845.187161.268770@g14g2000cwa.googlegroups.com> Dave Opstad wrote: > In article <1133144504.909363.219530 at g49g2000cwa.googlegroups.com>, > "Robert Hicks" wrote: > > > How do I set this variable in my .bash_profile? I have the html docs in > > /usr/local/PythonDocs. > > I have a line in my .profile like this: > > export PYTHONDOCS='/Users/opstad/Documents/Developer > Docs/Python-Docs-2.4.1' > > So by analogy, you could try adding this to your profile: > > export PYTHONDOCS='/usr/local/PythonDocs' > I have that...and it isn't working with the OSX version of IDLE in the MacPython folder. If I start Python from the Terminal it works. Any idea why it doesn't work that way? Robert From dwahler at gmail.com Thu Nov 3 13:56:26 2005 From: dwahler at gmail.com (David Wahler) Date: 3 Nov 2005 10:56:26 -0800 Subject: Can Anyone Help me on this In-Reply-To: <1131039234.706772.69660@g47g2000cwa.googlegroups.com> References: <1131039234.706772.69660@g47g2000cwa.googlegroups.com> Message-ID: <1131044186.810833.84200@g49g2000cwa.googlegroups.com> jmdeschamps at gmail.com wrote: > If what you want is a reversed copy, you could just append list1 > elements to list2, and use the reverse function such as > >>> ... > >>> for i in list1: > ... list2.append(i) > ... > >>> list2.reverse() > >>> list1 > ['1', '2', '3', '4', '5', '6', '7', '8', '9'] > >>> list2 > ['9', '8', '7', '6', '5', '4', '3', '2', '1'] It's much clearer and simpler to just do: >>> list2 = list1[:] >>> list2.reverse() This saves all the messing around with append, and has the advantage that it runs faster (by a factor of 30, on my computer). -- David From jack at performancedrivers.com Wed Nov 16 10:34:19 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 16 Nov 2005 10:34:19 -0500 Subject: best way to discover this process's current memory usage, cross-platform? In-Reply-To: <1132121442.019702.66620@g47g2000cwa.googlegroups.com> References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132080864.280909.51540@g44g2000cwa.googlegroups.com> <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> <1132121442.019702.66620@g47g2000cwa.googlegroups.com> Message-ID: <20051116153419.GH6637@performancedrivers.com> On Tue, Nov 15, 2005 at 10:10:42PM -0800, Neal Norwitz wrote: > Alex Martelli wrote: > > matt wrote: > > > > > Perhaps you could extend Valgrind (http://www.valgrind.org) so it works > > > with python C extensions? (x86 only) > > > > Alas, if it's x86 only I won't even look into the task (which does sound > > quite daunting as the way to solve the apparently-elementary question > > "how much virtual memory is this process using right now?"...!), since I > > definitely cannot drop support for all PPC-based Macs (nor would I WANT > > to, since they're my favourite platform anyway). > > Valgrind actually runs on PPC (32 only?) and amd64, but I don't think > that's the way to go for this problem. > > Here's a really screwy thought that I think should be portable to all > Unixes which have dynamic linking. LD_PRELOAD. > > You can create your own version of malloc (and friends) and free. You > intercept each call to malloc and free (by making use of LD_PRELOAD), > keep track of the info (pointers and size) and pass the call along to > the real malloc/free. You then have all information you should need. > It increases the scope of the problem, but I think it makes it soluble > and somewhat cross-platform. Using LD_PRELOAD, requires the app be > dynamically linked which shouldn't be too big of a deal. If you are > using C++, you can hook into new/delete directly. > Electric Fence[1] uses the LD_PRELOAD method. I've successfully used it to track down leaks in a python C extension. If you look at the setup.py in probstat[2] you'll see #libraries = ["efence"] # uncomment to use ElectricFence which is a holdover from developing. -Jack [1] http://perens.com/FreeSoftware/ElectricFence/ [2] http://probstat.sourceforge.net/ From steve at REMOVEMEcyber.com.au Mon Nov 14 03:04:09 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 14 Nov 2005 19:04:09 +1100 Subject: modifying small chunks from long string References: <1131951470.660501.68710@g44g2000cwa.googlegroups.com> Message-ID: <437844F9.20109@REMOVEMEcyber.com.au> MackS wrote: > This program is meant to process relatively long strings (10-20 MB) by > selectively modifying small chunks one at a time. ... > Can I get over this performance problem without reimplementing the > whole thing using a barebones list object? Is that a problem? Are you using string methods? Some possibilities are: array.array('c') UserString.MutableString cStringIO depending on exactly what you are trying to do, but if it is just straight forward replacement, (i.e. you never actually change the length of the string) I'd guess the list idiom would be simplest. If you have enough memory, just keep two copies of the string, the original and the modified: size = 1024*1024*20 # 20 MB original = "A" * size copy = [None] * size for i in range(size): copy[i] = original[i].lower() copy = ''.join(copy) This takes 530 seconds (8 minutes) on my not-especially-powerful system. Ouch. How does that compare to your code? If you can operate on moderately sized chunks of text at a time rather than one character at a time, you'll see some performance increase. Also the above code not only has a 20MB string, plus a 20MB list, it also carries around a list of 20+ million int objects. If I was paying more attention before I hit the enter key, I would have used xrange instead of range and saved a lot of memory. It also has to assemble the new 20MB string before garbage-collecting the character list. It is possible that the above test code has well in excess of 100MB of data at its peak. With those problems in mind, I try this: from __future__ import division size = 1024*1024*20 # 20 MB original = "A" * size copy = [] blocksize = 1024 for i in xrange(size//blocksize): copy.append( \ original[i*blocksize:(i+1)*blocksize].lower() ) copy = ''.join(copy) This makes a BIG difference: from 8 minutes down to 0.5 seconds. That's a speed-up by a factor of about one thousand. I was so amazed at the speed increase I re-wrote the code with a couple of simple tests, then ran it again. Same result. Unless I've made some stupid mistake, I think this is the way to go. -- Steven. From fairwinds at eastlink.ca Tue Nov 8 15:27:25 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Tue, 08 Nov 2005 16:27:25 -0400 Subject: sqlite3 decode error Message-ID: <1324293C-5096-11DA-A8B2-000A27B3B070@eastlink.ca> Recently I have run into an issue with sqlite where I encode strings going into sqlite3 as utf-8. I guess by default sqlite3 is converting this to unicode since when I try to decode I get an attribute error like this: AttributeError: 'unicode' object has no attribute 'decode' The code and data I am preparing is to work on postgres as well a sqlite so there are a couple of things I could do. I could always store any data as unicode to any db, or test the data to determine whether it is a string or unicode type when it comes out of the database so I can deal with this possibility without errors. I will likely take the first option but I looking for a simple test to determine my object type. if I do: >>>type('maybe string or maybe unicode') I get this: >>> I am looking for something that I can use in a comparison. How do I get the type as a string for comparison so I can do something like if type(some_data) == 'unicode': do some stuff else: do something else Regards, David From christian.convey at gmail.com Sat Nov 19 23:16:08 2005 From: christian.convey at gmail.com (Christian Convey) Date: Sat, 19 Nov 2005 23:16:08 -0500 Subject: Delays getting data on sys.stdin.readline() ? Message-ID: <6addebae0511192016u7e2c75bl713ad5fcc1553b82@mail.gmail.com> Hello, I've got a program that (ideally) perpetually monitors sys.stdin for lines of text. As soon as a line comes in, my program takes some action. The problem is, it seems like a very large amount of data must accumulate on sys.stdin before even my first invocation of readline() returns. This delay prevents my program from being responsive in the way it must be. Has anyone else seen this effect? If so, is there a reasonable workaround? Thanks very much, Christian From pmartin at snakecard.com Tue Nov 8 13:43:59 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Tue, 08 Nov 2005 18:43:59 +0000 Subject: user account logon from python References: Message-ID: getting there, this sequence creates a file with the correct uid and gid test_user_ids = 504 print os.setreuid(test_user_ids,0) print os.setregid(test_user_ids,0) print os.setuid(test_user_ids) print os.setgid(test_user_ids) print os.getuid() f = open("/tmp/toto","w") f.write("titi") f.close() Philippe C. Martin wrote: > Jeff, > > 1- I cannot find getpwent in the documentation > 2- crypt will not work if the system does not have shadow pw > 3- Even as root I get "Operation not permitted" using setuid and setgid > ... but I assume it is because I cannot get 1 and/or 2 to work. > > Can you direct me to some link that would explain the actual procedure ? > > Thanks, > > Regards, > > Philippe > > > > jepler at unpythonic.net wrote: > >> "login APIs" vary widely from system to system. >> >> Classic Unix systems use calls like getpwent and crypt to check >> passwords, and then call setuid, setgid and setgroups to set the identity >> of the user who is >> logging in. These are all available in stock Python, check the library >> reference for more details. Other login-time activities, like writing >> utmp entries, may not be directly available in stock Python modules. >> >> Many modern Linux systems use something called 'pam' for login-related >> activities, and there seems to be something called 'python-pam' out >> there, but I've never used it. >> >> Graphical login managers have their own additional requirements, such as >> starting and stopping the X server, managing the X authentication >> information, etc. >> >> Jeff From steven.bethard at gmail.com Wed Nov 23 01:17:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 Nov 2005 23:17:31 -0700 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: rhettinger at gmail.com wrote: >> > ii. The other problem is easier to explain by example. >> > Let it=iter([1,2,3,4]). >> > What is the result of zip(*[it]*2)? >> > The current answer is: [(1,2),(3,4)], >> > but it is impossible to determine this from the docs, >> > which would allow [(1,3),(2,4)] instead (or indeed >> > other possibilities). >> > """ >> > IMO left->right is useful enough to warrant making it defined >> > behaviour >> >>And in fact, it is defined behavior for itertools.izip() [1]. >> >>I don't see why it's such a big deal to make it defined behavior for >>zip() too. > > > IIRC, this was discussednd rejected in an SF bug report. It should not > be a defined behavior for severals reasons: [snip arguments about how confusing zip(it, it) is] > Overall, I think anyone using zip(it,it) is living in a state of sin, > drawn to the tempations of one-liners and premature optimization. They > are forsaking obvious code in favor of screwy special cases. The > behavior has been left undefined for a reason. Then why document itertools.izip() as it is? The documentation there is explicit enough to know that izip(it, it) will work as intended. Should we make the documentation there less explicit to discourage people from using the izip(it, it) idiom? STeVe From timr at probo.com Mon Nov 21 02:13:51 2005 From: timr at probo.com (Tim Roberts) Date: Mon, 21 Nov 2005 07:13:51 GMT Subject: check if com api is still available References: <3u67k3Fvep32U1@news.dfncis.de> <9Erff.20624$Hj2.1070@news-server.bigpond.net.au> Message-ID: Neil Hodgson wrote: > > All running COM servers should be in the "Running Object Table" >(ROT). If you search the net for this term you will find code that can >show what is in the ROT, so there must be an API. If only. The Microsoft Office applications seem to be the only ones in the world that use the ROT. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From samrobertsmith at gmail.com Tue Nov 8 03:18:47 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Tue, 8 Nov 2005 00:18:47 -0800 Subject: image Message-ID: <1d987df30511080018h1111aaa0t79e885438f8e2956@mail.gmail.com> why the following code report the error: Traceback (most recent call last): File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Python23\Examples\AppB\text.py", line 24, in ? text.image_create(END, image=photo) File "C:\Python23\lib\lib-tk\Tkinter.py", line 2882, in image_create return self.tk.call( TclError: image "pyimage4" doesn't exist from Tkinter import * root = Tk() root.option_readfile('optionDB') root.title('Text') text = Text(root, height=26, width=50) scroll = Scrollbar(root, command=text.yview) text.configure(yscrollcommand=scroll.set) text.tag_configure('bold_italics', font=('Verdana', 12, 'bold', 'italic')) text.tag_configure('big', font=('Verdana', 24, 'bold')) text.tag_configure('color', foreground='blue', font=('Tempus Sans ITC', 14)) text.tag_configure('groove', relief=GROOVE, borderwidth=2) text.tag_bind('bite', '<1>', lambda e, t=text: t.insert(END, "I'll bite your legs off!")) text.insert(END, 'Something up with my banter, chaps?\n') text.insert(END, 'Four hours to bury a cat?\n', 'bold_italics') text.insert(END, 'Can I call you "Frank"?\n', 'big') text.insert(END, "What's happening Thursday then?\n", 'color') text.insert(END, 'Did you write this symphony in the shed?\n', 'groove') button = Button(text, text='I do live at 46 Horton terrace') text.window_create(END, window=button) photo=PhotoImage(file='img52.gif') text.image_create(END, image=photo) text.insert(END, 'I dare you to click on this\n', 'bite') text.pack(side=LEFT) scroll.pack(side=RIGHT, fill=Y) root.mainloop() From mwm at mired.org Thu Nov 10 23:06:17 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 23:06:17 -0500 Subject: Change directory not successfully done References: Message-ID: <8664qz6d6u.fsf@bhuda.mired.org> Samuel Yin writes: > Hi, guys, > > This should be a simple problem, but I just can not resolve it. I just > want to use a python script to change my working directory. see my > following code: > > # mycd.py > 1) destdir = "xxxxxxxx" > 2) command = "cd "+ destdir > 3) os.system(command) > 4) os.chdir(destdir) > > But neither 3) nor 4) is used, I just can not change the directory after > execute mycd.py. This remind me of bash script. If you change directory > in your bash script file, it will only impact the sub process of that > script, except that you invoke that bash script by ./script_file_name. > But what should I do in the case of python script? Actually, one solution is a level of indirection worse than the bash script. Doing a cd changes the current directory of the process that executes the cd system call. In a bash script, it's the shell executing the script. In your python script, os.system launches another process to run the command, and it's *that* process that has it's directory changed. The os.chdir changes the shell of the python interpreter, which still doesn't do you any good. One solution is to switch to a shell that understands Python, and have that execfile your script. There is a Python environment that can be configured to be used as a shell, but I can't remeber it's name. If you want to stay with bash, your solutions are the same as they are for setting an environment variable in the parent shell. You can google for that for a long discussion of the issues. The solution I liked from that thread was an alias: In your bash do: alias mycd="eval $(python mycd.py)" mycd.py looks like: destdir = 'xxxxxx' command = 'os ' + destdir print command At the bash prompt you enter the command "mycd", your python script builds a command for the shell to execute and prints it, the eval reads that output and executes it in your shell. If you want to pass arguments to the python script, you'll need to use a shell function instead of an alias. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bonono at gmail.com Wed Nov 30 03:37:43 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 30 Nov 2005 00:37:43 -0800 Subject: Nested loop In-Reply-To: References: Message-ID: <1133339863.718152.140770@g43g2000cwa.googlegroups.com> viewcharts wrote: > I am reading two text files comparing the values in one to the other, > this requires two loops. The problem is that when the inner loop is > finished, it never goes back into the loop. Any suggestions? > > > for refSymbol in symbols.readlines(): > for lookupSymbol in myfile.readlines(): > showme = lookupSymbol.split('\t') > if showme[3] == refSymbol.strip(): > priceNew.write(refSymbol.strip()+" "+showme[10]) As another poster said, you have "used up" the inner iterable in the first round, it is an iterable, just not like a list where you can use multiple times. Either turn it into a list(so you can reuse it) or better yet, turn it into a dict which would speed up the matching process. Either way, it better be done outside of the outer loop. From http Fri Nov 4 20:13:26 2005 From: http (Paul Rubin) Date: 04 Nov 2005 17:13:26 -0800 Subject: C extension + libm oddity [fmod(2.0, 2.0) == nan ?!] References: <1131152542.351552.255140@g44g2000cwa.googlegroups.com> Message-ID: <7x4q6roq15.fsf@ruckus.brouhaha.com> "Lonnie Princehouse" writes: > Now, fmod(2.0, 2.0) should be 0.0. The problem? ans is getting > assigned nan! I have stepped through it in the debugger now dozens of > times. Either fmod is putting the wrong return value on the stack, or > the stack is getting corrupted by something else and "ans" is getting > assigned the wrong value. Have you compiled the C extension with all optimization turned off? Especially with optimizations on, you can't really tell what is going to get assigned in a variable because the code isn't computing the intermediate values you might expect it to. I suggest disassembling it and stepping through it instruction by instruction if you haven't done that. From tim.vets at skynet.be Tue Nov 22 18:48:37 2005 From: tim.vets at skynet.be (tim) Date: Wed, 23 Nov 2005 00:48:37 +0100 Subject: [Fwd: Re: hex string to hex value] Message-ID: <4383AE55.2050905@skynet.be> ok, but if i do >>> n=66 >>> m=hex(n) >>> m '0x42' >>> h=int(m,16) >>> h 66 >>> I end up with 66 again, back where I started, a decimal, right? I want to end up with 0x42 as being a hex value, not a string, so i can pas it as an argument to a function that needs a hex value. (i am trying to replace the 0x42 in the line midi.note_off(channel=0, note=0x42) with a variable) mensanator at aol.com wrote: > avnit wrote: > > >> If you just want to convert a string to an integer, it would be: >> >> >> >>>>> int(n) >>>>> >>>> > > That's what the OP tried and it didn't work. > > BECAUSE you have to tell the int function what base the string is in > (even though it has "0x" at the start). > > > >>>> int(n,16) >>>> >>> > 66 > > > >> in your case it would be: >> >> >> >>>>> m=66 >>>>> n=int(hex(m)) >>>>> >>>> > > Wrong again, you still have to tell it what base. > > > >>>> h=int(hex(m),16) >>>> h >>>> >>> > 66 > > > From aum at spam.me.please Mon Nov 7 01:51:39 2005 From: aum at spam.me.please (aum) Date: Mon, 07 Nov 2005 19:51:39 +1300 Subject: PyFLTK - an underrated gem for GUI projects References: Message-ID: On Sun, 06 Nov 2005 21:23:03 -0800, Roger Binns wrote: >> To me, wxPython is like a 12-cylinder Hummer, with fuzzy dice hanging >> from the mirror, fridge and microwave in the back, and DVD consoles on >> every seat, towing a campervan - absolute power and luxury, giving 8mpg >> if you're lucky. > > A word of support for wxPython: Most right you are, Roger. wx is a 5-star GUI library. When advanced GUI features are needed, wx, gtk2 or qt are definitely the way to go. What I'm saying is that there are many basic projects being written for these toolkits, whose functionality could be completely supported by PyFLTK. When only a smaller set of widgets is needed, there's a stronger case for using lighter widget libraries - especially FLTK, because you'll get way more functionality per line of code, and finish your project faster, than if using the bigger toolkits with their application-level red tape - the extra lines of code you have to write to get things done. If travelling off-road for a few weeks and driving over minefields in enemy territory, take the Hummer. But for ordinary use, like commuting to work, visiting friends, shopping etc, using anything more than the Honda 4-cylinder sedan is IMHO a waste of resources. Similarly, coding something in wx when FLTK will suffice is a waste of time, effort, disk space, CPU cycles and memory. -- Cheers aum From casevh at comcast.net Fri Nov 11 12:15:42 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 11 Nov 2005 09:15:42 -0800 Subject: LARGE numbers In-Reply-To: <7xmzkbkw0j.fsf@ruckus.brouhaha.com> References: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> <1131691903.961955.19950@o13g2000cwo.googlegroups.com> <1h5uqy3.sdzwkkuvu86mN%aleax@mail.comcast.net> <7xmzkbkw0j.fsf@ruckus.brouhaha.com> Message-ID: <1131729342.754040.316620@o13g2000cwo.googlegroups.com> Paul Rubin wrote: > aleax at mail.comcast.net (Alex Martelli) writes: > > As the author of gmpy, I'd like to point out that the speed difference > > isn't all that large, if all you're doing is ordinary arithmetic -- a > > few times at most (it can be better if you need some of GMP's > > functionality which gmpy exposes, such as primality testing). > > For numbers of this size, won't gmpy use FFT-based multiplication? > That's potentially orders of magnitude faster than ordinary n**2 > multiplication. Python's native longs use Karatsuba multiplication with is O(n^1.585). My early version of DecInt (BigDecimal) uses 4-way Toom-Cook multiplication which is O(n^1.4). My development version uses Nussbaumer convolution with is O(n ln(n)). For multiplicaiton of two 1,000,000 digits numbers and conversion to a decimal string, here are some times: GMPY multiplication: 0.96 seconds conversion to string: 712.7 seconds DecInt with GMPY multiplication: 1.33 seconds conversion to string: 0.83 seconds DecInt without GMPY multiplication: 2.84 seconds conversion to string: 0.45 seconds Python (using native long) multiplication: 8.47 seconds conversion to string: a really long time Case From see at reply.to.field Fri Nov 4 00:50:44 2005 From: see at reply.to.field (Chris) Date: Fri, 4 Nov 2005 05:50:44 -0000 Subject: /usr/lib/python2.4/posixfile.py error Message-ID: Hi, Wonder if anyone can help me? I am trying to run a perl script but I keep getting this error: /usr/lib/python2.4/posixfile.py:59: DeprecationWarning: The posixfile module is obsolete and will disappear in the future DeprecationWarning) I am running Ubuntu Hoary 5.10. I'll try the same script on my gentoo box at work tommorrow, but really would like to run this script asap. Any ideas on why it's failing on that python module? Any ideas greatfully received, Chris From cito at online.de Fri Nov 25 05:00:33 2005 From: cito at online.de (Christoph Zwerschke) Date: Fri, 25 Nov 2005 11:00:33 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132906685.036452.180860@f14g2000cwb.googlegroups.com> References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> <1132828514.489889.7110@g44g2000cwa.googlegroups.com> <1132844756.190248.141870@g47g2000cwa.googlegroups.com> <1132906685.036452.180860@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: > That means making keys, values, and items custom objects. > Creating a new instance would have the overhead of creating 4 new > objects instead of just 1. Is the added convenience worth it ? (Plus > the extra layers of method calls for each access). I'm not sure about that either. But since you are using odict for convenience reasons anyway, and not for performance reasons, it would be consequential. Performance testing should be made anyway, so this could be tested as well. I think that creating these 3 additional objects will not matter much if the dict has more than a handful of items. And the extra layers will be only called if you really access these keys, values or items attributes which will not happen very frequently. Normally, you just loop over an ordered directory and acess keyed values. > I'm not sure. It's a nice idea in terms of using it (we could just > leave the sequence attribute as an alias for the new keys attribute - > for backwards compatibility). Yes, you could make it a deprecated feature. -- Christoph From titus at caltech.edu Tue Nov 29 03:54:50 2005 From: titus at caltech.edu (C. Titus Brown) Date: Tue, 29 Nov 2005 00:54:50 -0800 Subject: ANNOUNCE: twill v0.8 Message-ID: ANNOUNCING twill v0.8. twill is a simple language for testing Web applications. It's designed for automated testing of Web sites, but it can be used to interact with Web sites in a variety of ways. twill has an interactive shell, 'twill-sh', and can also run scripts. twill is a reimplementation of Cory Dodt's PBP. It is built on top of Python and John J. Lee's mechanize. A twill script looks like this: # go to the /. login page go http://slashdot.org/login.pl # fill in the form fv 1 unickname test fv 1 upasswd test submit # ok, there's no such account ;). show error HTML. show --- This is the sixth public release of twill, version 0.8. (Tagline: "85% unit tested.") You can install twill with easy_install via PyPi, or download the latest .tar.gz at: http://darcs.idyll.org/~t/projects/twill-0.8.tar.gz Documentation is included in the .tar.gz and is also online at http://www.idyll.org/~t/www-tools/twill.html --- Miscellaneous details: twill is implemented in Python and uses pyparsing and mechanize. In addition to the existing simple command language, twill can easily be extended with Python. twill also provides a fairly simple and well-documented wrapper around mechanize. twill scripts can be recorded with maxq, although scripts may require some hand tweaking at the moment. See the twill documentation for more information. twill does not understand JavaScript, I'm sorry to say. --- New features: * test WSGI Python applications in-process; * Updated to latest versions of mechanize, ClientCookie, ClientForm, and pullparser; * Significant increase in number of unit tests & their code coverage; * Automatic 'tidy' preprocessing when available; * easy_install/eggs now supported; * http-equiv redirect now works; * new commands: - 'formaction' changes form URLs; - 'tidy_ok' checks for 'tidy' correctness; - 'showhistory' command; Special thanks to sureshvv and Simon Buenzli... From fredrik at pythonware.com Tue Nov 22 16:15:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 22:15:02 +0100 Subject: matching a string to extract substrings for which somefunctionreturns true References: <1360b7230511220418q6ede018bhcd80655f8a4f1530@mail.gmail.com> Message-ID: I wrote: > if you cannot cache session data on the server side, I'd > recommend inventing a custom record format, and doing your > own parsing. turning your data into e.g. > > "foo:1:foobar:3:0+foo1:2:foobar1:3:1+foo2:2:foobar2:3:2" > > is trivial, and the resulting string can be trivially parsed by a couple > of string splits and int() calls. on the other hand, the "myeval" function I posted here http://article.gmane.org/gmane.comp.python.general/433160 should be able to deal with your data, as well as handle data from malevolent sources without bringing down your computer. just add if token[1] == "(": out = [] token = src.next() while token[1] != ")": out.append(_parse(src, token)) token = src.next() if token[1] == ",": token = src.next() return tuple(out) after the corresponding "[" part, and call it like: data = myeval("[" + input + "]") From bonono at gmail.com Tue Nov 22 06:18:01 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 03:18:01 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132585276.357388.214630@f14g2000cwb.googlegroups.com> Message-ID: <1132658281.918440.112290@f14g2000cwb.googlegroups.com> Christoph Zwerschke wrote: > Fredrik Lundh wrote: > > I'll repeat this one last time: for the use cases presented by Zwerschke > > and "bonono", using a list as the master data structure, and creating the > > dictionary on demand, is a lot faster than using a ready-made ordered > > dict implementation. if you will access things via the dictionary a lot, > > you can cache the dictionary somewhere. if not, you can recreate it > > several times and still get a net win. > > You're right in pointing out that the advantage of ordered dictionaries > (unless you use an omptimized C implementation) is not a performance gain. > > But please see my other reply: If the dictionary has more than 3 items > (say 10 or 20), and an effective ordered dict is used, it's not really > "a lot" slower. At least if we are talking about a situation were "on > demand" is "always". So, on the other side there isn't such a big > performance loss when using ordered dictionaries as well. > > The advantage of using an ordered dictionary is that you can set up your > ordered dictionary (say, describing your database columns) once, and > then can access it in any way you like in the following: Iterate over it > in a guaranteed order or access item, always refering to the same > object, without needing to care about building and caching auxiliary > objects with different names depending on what you are doing. > Well, I don't think performance is the concern(at least not for me), but how best to blend with the rest of the code which I have no interest to explain as I am not here to convincing anyone for such a thing. I just present a use case, if they see it, fine. If not, that is fine too. But I did learn something that creating a dict on a list cost me nothing, I would be less worry about the performance hit in the future. From dcrespo at gmail.com Tue Nov 8 14:31:13 2005 From: dcrespo at gmail.com (dcrespo) Date: 8 Nov 2005 11:31:13 -0800 Subject: Get the pid of a os.startfile(filename) Message-ID: <1131478273.792041.282670@g44g2000cwa.googlegroups.com> Hi to all, How can I get the Process ID (PID) of an application started because of os.startfile(filename)? Or, better, How can I get the PID of a running program, suposing I know the name of the running application? Many thanks. Daniel From mwm at mired.org Wed Nov 23 15:41:17 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 15:41:17 -0500 Subject: What a curious assignment. References: <1132721032.455988.259600@o13g2000cwo.googlegroups.com> <438422E5.6090003@REMOVEMEcyber.com.au> <1132733852.855271.282020@f14g2000cwb.googlegroups.com> Message-ID: <86wtizdrma.fsf@bhuda.mired.org> "bonono at gmail.com" writes: > I believe he knows about inheritance, but not about the behaviour of > the assignment. In many other OO languages, I believe you cannot have > the same name for both instance variable and class variable. javascript > has similar behaviour. I think more important is that in many languages you can't dynamically add attributes to an object. So an attempt to bind a.i will either fail, or be an assignment to A.i. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jepler at unpythonic.net Tue Nov 22 17:52:10 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 22 Nov 2005 16:52:10 -0600 Subject: user-defined operators: a very modest proposal In-Reply-To: References: Message-ID: <20051122225210.GE9567@unpythonic.net> If your proposal is implemented, what does this code mean? if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation' Since it contains ']+[' I assume it must now be parsed as a user-defined operator, but this code currently has a meaning in Python. (This code is the first example I found, Python 2.3's test/test_types.py, so it is actual code) I don't believe that Python needs user-defined operators, but let me share my terrible proposal anyway: Each unicode character in the class 'Sm' (Symbol, Math) whose value is greater than 127 may be used as a user-defined operator. The special method called depends on the ord() of the unicode character, so that __u2044__ is called when the source code contains u'\N{FRACTION SLASH}'. Whatever alternate syntax is adopted to allow unicode identifier characters to be typed in pure ASCII will also apply to typing user-defined operators. "r" and "i" versions of the operators will of course exist, as in __ru2044__ and __iu2044__. Also, to accomodate operators such as u'\N{DOUBLE INTEGRAL}', which are not simple unary or binary operators, the character u'\N{NO BREAK SPACE}' will be used to separate arguments. When necessary, parentheses will be added to remove ambiguity. This leads naturally to expressions like \N{DOUBLE INTEGRAL} (y * x**2) \N{NO BREAK SPACE} dx \N{NO BREAK SPACE} dy (corresponding to the call (y*x**2).__u222c__(dx, dy)) which are clearly easy to love, except for the small issue that many inferior editors will not clearly display the \N{NO BREAK SPACE} characters. Some items on which I think I'd like to hear the community's ideas are: * Do we give special meaning to comparison characters like \N{NEITHER LESS-THAN NOR GREATER-THAN}, or let users define them in new ways? We could just provide, on object, def __u2279__(self, other): return not self.__gt__(other) and other.__gt__(self) which would in effect satisfy all users. * Do we immediately implement the combination of operators with nonspacing marks, or defer it? If we implement it, do we allow the combination with pure ASCII operators, as in u'\N{COMBINING LEFT RIGHT ARROW ABOVE}+' or treat it as a syntax error? (BTW the method name for this would be __u20e1u002b__, even though it might be tempting to support __u20e1x2b__, __u2oe1add__ and similar method names) How and when do we normalize operators combined with more than one nonspacing mark? * Which unicode operator methods should be supported by built-in types? Implementing __u222a__ and __iu222a__ for sets is a no-brainer, obviously, but what about __iu2206__ for integers and long? * Should some of the unicode mathematical symbols be reserved for literals? It would be greatly preferable to write \u2205 instead of the other proposed empty-set literal notation, {-}. Perhaps nullary operators could be defined, so that writing \u2205 alone is the same as __u2205__() i.e., calling the nullary function, whether it is defined at the local, lexical, module, or built-in scope. * Do we support characters from the category 'So' (symbol, other)? Not doing so means preventing programmers from using operators like \u"n{HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW}". Who are we to make those kinds of choices for our users? Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jschamba at physics.utexas.edu Mon Nov 14 16:14:37 2005 From: jschamba at physics.utexas.edu (Jo Schambach) Date: Mon, 14 Nov 2005 15:14:37 -0600 Subject: how do i use "tkinter.createfilehandler" with a regular c program? In-Reply-To: References: Message-ID: <4378FE3D.4020801@physics.utexas.edu> Thanks, that seems to work. maybe one more question on this subject: how can i use the callback function to the "createfilehandler" call from within a class? in other words, what would be the signature of the callback function, if I made it a member of a class? The documentation says that the callback is called with the arguments: callback(filehandle, stateMask) but a class member function always has the "self" argument as is first argument. So would the syntax be: class GUI: def __init__: ..... def filehandlerCallback(self, filehandle, stateMask): .... Jo jepler at unpythonic.net wrote: > Compared to your program, I > * Made sure that the slave program actually flushed its stdout buffers > * didn't call read(), which will by default continue reading until > it reaches EOF, not merely read the available data > > #!/usr/bin/env python > import sys, time, Tkinter, itertools, _tkinter, os > > if '-slave' in sys.argv: > for i in itertools.count(): > time.sleep(1) > print "This is a line of output:", i > sys.stdout.flush() > raise SystemExit > > root = Tkinter.Tk() > root.wm_withdraw() > > fh = os.popen('%s -slave' % sys.argv[0]) > > def reader(*args): > line = fh.readline() > if not line: > print "EOF from slave" > raise SystemExit > print "from slave: %r" % line > > _tkinter.createfilehandler(fh, Tkinter.READABLE, reader) > root.mainloop() -- Dr Joachim Schambach The University of Texas at Austin Department of Physics 1 University Station C1600 Austin, Texas 78712-0264, USA Phone: (512) 471-1303; FAX: (814) 295-5111 e-mail: jschamba at physics.utexas.edu From Serge.Orlov at gmail.com Thu Nov 17 03:44:39 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Nov 2005 00:44:39 -0800 Subject: best way to discover this process's current memory usage, cross-platform? In-Reply-To: References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132080864.280909.51540@g44g2000cwa.googlegroups.com> <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> <1132121442.019702.66620@g47g2000cwa.googlegroups.com> Message-ID: <1132217079.367516.200740@z14g2000cwz.googlegroups.com> Jack Diederich wrote: > Electric Fence[1] uses the LD_PRELOAD method. I've successfully used it to > track down leaks in a python C extension. If you look at the setup.py in > probstat[2] you'll see > #libraries = ["efence"] # uncomment to use ElectricFence > which is a holdover from developing. I've also successfully used Electric Fence many years ago to track down leaks in a C/Linux program. Since that time Electric Fence has been forked into DUMA project http://duma.sourceforge.net/ and was ported to windows, perhaps it has become cross-platform? I've never tried it on anything besides Linux. From yuxi at ece.gatech.edu Wed Nov 9 15:08:15 2005 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Wed, 09 Nov 2005 15:08:15 -0500 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Before adding complex protection mechanisms to your code you first need > some code worth protecting, which is to say it should have some novel > features or represent a lot of work that offers useful integrated > functionality for a task or a skill area. > > Most inquiries of this nature appear to fall at that first hurdle. > > There are things you can do, but I'm always keenly aware that very few > users of a program have both the skills and the inclination to rip off > the code even when the source is distributed as part of the product. > Personally I've never bothered with obfuscation, and prefer to rely on > copyright when I deliver code to customers. As you said, if you have some novel features, you will need obfuscation. Copyright doesn't protect the process and patents may take a while. In the meanwhile, good obfuscation is reasonable protection, imho. But I think you failed to note that it may not be a novel feature or useful functionality. In fact, it might be the opposite: a function the users want removed. A typical example would be a shareware registration or nag screen. When the users have to start paying, they might then feel inclied to "rip off the code", or in this case, rip out the code. From mwm at mired.org Thu Nov 10 16:00:41 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 16:00:41 -0500 Subject: append to non-existing list References: <4371fb5a$0$18086$626a14ce@news.free.fr> <437251f4$0$25824$626a14ce@news.free.fr> Message-ID: <86vez05ibq.fsf@bhuda.mired.org> Yves Glodt writes: > Which raises another question... :-) > > Is there a possibility to bring together apache and python in a way > that I can embed python into html? Lots of ways. Most of them aren't really Python, but look a lot like it. PSP is most like PHP/ASP/etc., and I believe current mod_python's come with a PSP processor. Be warned that there's more than one thing floating around by the name Python Server Pages, and they aren't completely compatible. Personally, I prefer Cheetah for this, for three reasons: 1) Cheetah doesn't use X/HTML-like syntax for it's tags, so they don't interfere with my intelligent X/HTML tools. 2) Cheetah can be used for things other than X/HTML, so you get a twofer on tools. For my last project, I created the Makefile from a Cheetah template. 3) Cheetah templates are Classes, so you inherit from them. The same last project created a top-level template that did the site-wide banner/nav/etc things, and defined abstracd methods for the title/content. Pages inherited from that (or in some cases from a subclass of that) and defined concrete versions of the abstrat methods. Cheetah templates can inherit from Python classes (which I've found useful), and Python classes can inherit from Cheetah templates (which sounds useful, but I haven't used it yet). > Or even, write a smallish webserver in python (using twisted maybe) > whose only purpose is to serve pages and execute the embedded code...? Well, you could always use the CGIHttpServer module that's in the standard library for this. Cheetah templates can be tested outside the sever environment, so you don't need a server to execute the embedded code. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From aleax at mail.comcast.net Thu Nov 3 10:39:33 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 07:39:33 -0800 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> <1131023021.643251.113330@f14g2000cwb.googlegroups.com> Message-ID: <1h5fwpi.1wjmgm417fbm8dN%aleax@mail.comcast.net> bonono at gmail.com wrote: > How about, Google use python extensively ? This I believe is a very > strong argument for any concern about python. I must admit to feeling very good when I read this kind of comment (it IS nice to see one's employer held up as a good example -- and, I WAS hired at Google in good part based on my Python skills, and authorship of the "Python in a Nutshell" book, which is among our standards books for new hires). However, let me play devil's advocate: the mix of software that Google develops, considering what we offer to the public and some reasonable speculation about the infrastructure that must be behind those offers, is clearly heavily slanted towards _networking_. So, our use cannot necessarily be "concern-allaying" for a firm which (say) doesn't care about networking, but rather wants to program games, or traditional business applications, or personal/group productivity apps, or ... But fortunately there are plenty of "success stories" in each and every one of these fields. For example, for games, Civilization IV is being developed mostly in Python (with C++ for some low levels, and BoostPython as "glue"); other Python success stories show it used in payroll applications (the hugely successful PayThyme), productivity ones (OSAF's Chandler), etc, etc. Look around the web for "Python success stories" and you may find many other examples in as huge a variety of fields as one might wish. Alex From belliott4488 at comcast.net Sat Nov 5 12:46:31 2005 From: belliott4488 at comcast.net (BLElliott) Date: Sat, 05 Nov 2005 12:46:31 -0500 Subject: how to call basic browser functions? In-Reply-To: References: Message-ID: <_umdnfXkRZJqcvHenZ2dnUVZ_sydnZ2d@comcast.com> Great! I've never looked in to the urllibs before, but it sounds like they're just what I need. And no, I'm not thinking of anything so sophisticated as executing applets or anything -- just those "Save * as ..." functions, where * might be "page", "image", "link target" etc. I also hadn't known about wget, so that's good to know, too. thanks! - bruce Peter Hansen wrote: > BLElliott wrote: > >> I think this is a very basic question, so feel free to direct me to a >> FAQ or other resource to go and get myself educated, if that's the >> best answer. >> >> Can I perform web browser functions from a script, for example, doing >> file downloads, if I can construct the file URL within my script? As >> an example, suppose there's a file I download periodically, but its >> URL changes with the current date. If I can write a script that will >> automatically generate the URL, can it then go and fetch the file for me? > > > Yes, you can definitely do that. Look for examples of using "urllib" or > "urllib2". There should be many that are close to the sort of thing you > want. Or you could simply use a command line utility such as "wget" to > accomplish much the same thing and avoid almost any programming. > > (Note that if in addition to downloading the actual contents of the > page, you will require more sophisticated features of a real browser, > such as Javascript or Java execution, you'll need capabilities far > beyond what urllib2 can provide. And you probably don't want to go > there right now.) > > -Peter From bokr at oz.net Sun Nov 20 01:43:31 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 20 Nov 2005 06:43:31 GMT Subject: Can a function access its own name? References: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> <1132430103.737707.82090@g47g2000cwa.googlegroups.com> <868xvkhrfb.fsf@bhuda.mired.org> Message-ID: <43801703.263383585@news.oz.net> On Sat, 19 Nov 2005 23:30:32 -0500, Mike Meyer wrote: >bobueland at yahoo.com writes: >> Thanks Diez and Peter, >> Just what I was looking for. In "Library Reference" heading >> 3.11.1 Types and members >> Running this yields the result >> >> cap(s, n) > >You've now got three solutions. They'll work fine most of the time, >but can't be trusted in general. Binding a name to a function doesn't >change the name that these solutions return, and the name they return >may no longer be bound to said function. Just a warning. > But the one buried in co_name seems to persist (barring byte code munging in the decorator ;-) >>> def fren(newname='newname'): ... def fren(f): ... f.__name__ = newname ... return f ... return fren ... >>> @fren('bar') ... def foo():pass ... Could have done that manually, but just playing. Ok, rebind foo and remove the old name, for grins >>> baz = foo >>> del foo See what we've got >>> dir() ['__builtins__', '__doc__', '__name__', 'baz', 'fren'] Check name(s) ;-) Local binding to the function object first: >>> baz Its outer name: >>> baz.func_name 'bar' Its def name: >>> baz.func_code.co_name 'foo' Regards, Bengt Richter From peter at engcorp.com Wed Nov 23 22:35:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Nov 2005 22:35:52 -0500 Subject: wxPython Licence vs GPL In-Reply-To: References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Really? So when I take my GPLed software, and legally install it on > 100 PCs without paying one single cent for licence fees, it isn't free of > cost? > > You a living in a strange and mysterious world, where things that cost > nothing aren't free. Many definitions of "cost" include things that go beyond mere *monetary* value. Watching a given program on TV might be called "free" by some, but if I have to suffer through commercials I don't consider it free. Heck, I despise MSN Messenger and avoided the "free" Opera** because they aren't "free" for me, loaded with advertisements that flash in my face and distract me all the time. I'm just highlighting how discussions of this nature which spend a lot of time revolving around narrow and non-shared definitions of words can really waste a lot of time... -Peter ** Apparently I'm not alone as I understand the latest Opera is entirely "free" of advertisements as well. From casevh at comcast.net Wed Nov 9 23:24:05 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 9 Nov 2005 20:24:05 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> In-Reply-To: <1h5rxho.nxmo0z15zne5jN%aleax@mail.comcast.net> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> <1131517112.247477.35030@g14g2000cwa.googlegroups.com> <1h5rxho.nxmo0z15zne5jN%aleax@mail.comcast.net> Message-ID: <1131596645.329227.185290@g43g2000cwa.googlegroups.com> > > Will you be updating the information in setup.py file? > > Done, in the current CVS version. I will grab the CVS version and create installers. > > Which versions of Python do you want to support? > > I have tested gmpy with 2.3 and 2.4 on Mac, and those two and also 2.2 > on Linux. I think supporting 2.2 with a Windows download is probably > unneeded, but 2.4 is a must and I suspect 2.3 would be nice... I will definately build for 2.3 and 2.4. > > > Do you want versions that include GMP tailored for specific processors? > > My gut reaction here is that people with special processors, Windows, > and demanding performance needs should probably get their own > development environments and build GMP and gmpy accordingly. > > Any opinions from the public on this one...? Unless there is a demand for compatibilty with older processors (Pentium, Pentium Pro, Pentium II), I will build for Pentium 3. > > > With GMP 4.1.4 compiled for pentium3, and running on a 1.8Ghz Pentium > > M, I'm able to calculate the decimal form of 2^25964951 (the 43rd > > Mersenne prime) in 10 seconds. The prior gmpy release takes just over > > 14 seconds. Without gmpy, Python takes 25.4 seconds. On an Athlon > > MP2800+ (2.133Ghz) with GMP compiled for that processor, I can do it in > > 6.6 seconds using gmpy and 22.4 seconds without gmpy. I'm working with > > blocks of 1000 digits and using a combination of Toom-Cook and > > Nussbaumer convolution to perform the multiplies and squares. > > Sounds quite decent -- about a 2.5 to 3+ times speedup wrt Python, and > some speedup wrt gmpy 1.0 (all GMP's merit -- I didn't address > performance aspects at all in this delta). Just out of curiosity: what > performance do you get on the Athlon with a pentium3-compiled GMP? > I'll try to find out. Unfortunately, my Athlon box won't run Windows. ;-) > Thanks, > > Alex You're welcome, Case From lcatalin at siadv.com Wed Nov 23 03:15:00 2005 From: lcatalin at siadv.com (Catalin Lungu) Date: Wed, 23 Nov 2005 09:15:00 +0100 Subject: SelfExtract with zipfile Message-ID: Hi, I need to compress files in self-extract archive. I use the zipfile module. Is there an option or parameter to do that? Thanks in advance, Catalin From enas_khalil at yahoo.com Tue Nov 29 09:52:54 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Tue, 29 Nov 2005 06:52:54 -0800 (PST) Subject: TypeError: unsubscriptable object Message-ID: <20051129145254.79045.qmail@web30510.mail.mud.yahoo.com> when i run this script to make a training of some text and so can use condfreqdistributions to guess text in test , my code isas follows: from nltk.probability import ConditionalFreqDist from nltk.tokenizer import WhitespaceTokenizer from nltk.tagger import * token1 = [] train_tokens = [] cfdist=ConditionalFreqDist() # open the file containning the training tagged data dd= open("fataha.txt").readlines() # generate a string # open the file containning the training tagged data data2= (open("besm.txt").read())# generate a string corpus=Token(TEXT=data2)# convert string to token to tokenize it WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(corpus) #print unicode('\xc8\xd3\xe3','cp1256') for xx in corpus['WORDS'] : token1.append(xx['TEXT']) for item in dd: train_tokens.append(item) l=len(item) i=int(item.find("=")) aa=Token(TEXT=item) aa['WORDS']=item[0:i] aa['TAG']=item[i+1:l+1] j=int(item.find('-')) print j pos=item[j+1:i] word=item[:j] train_tokens.append(aa) for xx in token1: if word==xx: print 'hi' cond=cfdist.conditions() for cond in word :cfdist[cond].inc[aa['TAG']] i got this error : Traceback (most recent call last): File "F:\MSC first Chapters\28-11\firstprog1.py", line 53, in -toplevel- for cond in word :cfdist[cond].inc[aa['TAG']] TypeError: unsubscriptable object what does unsubscriptable object this means , and how can ihandle it also if you please suggest me a good refrence in how to handle different types of objects in python as token ,and how i can generate different token attributes thanks --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at python.net Wed Nov 23 15:14:16 2005 From: theller at python.net (Thomas Heller) Date: Wed, 23 Nov 2005 21:14:16 +0100 Subject: Reading binary data References: <1132769538.319905.272190@z14g2000cwz.googlegroups.com> <1132773947.735958.240450@g49g2000cwa.googlegroups.com> Message-ID: <1x17jf53.fsf@python.net> "David M" writes: > Thanks but the C Struct describing the data doesn't match up with the > list on the module-struct page. > > this is the acct.h file [...] Tooting my ctypes horn (sorry for that): thomas at linux:~/ctypes> locate acct.h /usr/include/linux/acct.h /usr/include/sys/acct.h thomas at linux:~/ctypes> python ctypes/wrap/h2xml.py sys/acct.h -o acct.xml creating xml output file ... running: gccxml /tmp/tmpSWogJs.cpp -fxml=acct.xml thomas at linux:~/ctypes> python ctypes/wrap/xml2py.py acct.xml -o acct.py thomas at linux:~/ctypes> python Python 2.4.1a0 (#1, Oct 23 2004, 15:48:15) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import acct >>> acct.acct >>> acct.AFORK 1 >>> acct.ASU 2 >>> acct.acct.ac_comm >>> acct.acct.ac_utime >>> from ctypes import sizeof >>> sizeof(acct.acct) 64 >>> acct.acct.ac_flag >>> thomas at linux:~/ctypes> But it won't help you to decode/encode the comp_t fields into floats. Note that the h2xml.py script requires gccxml. Thomas From alan.meadows at gmail.com Thu Nov 10 18:30:33 2005 From: alan.meadows at gmail.com (Luxore) Date: 10 Nov 2005 15:30:33 -0800 Subject: thread variable scope with start_new_thread Message-ID: <1131665433.616558.105670@f14g2000cwb.googlegroups.com> Hello, I am trying to create threaded python project and I'm running into some weird Python variable scoping. I am using the "thread" module (I know, it's old and I should be using threading)... but for example: import thread def extract_archive(session, user, archive, dest=None): job_id = sunlib.job.new(...) def thread_extract_archive(): if not os.path.exists(archive): <...do stuff...> if not os.path.isfile(archive): <...do stuff...> if dest == None: dest = os.path.dirname(archive) <...do more stuff...> thread.start_new_thread(thread_extract_archive, ()) return job_id It appears that thread_extract_archive() inherits many of the variables that are passed or defined in extract_archive(). I find this scary, although very convenient because my thread process needs to reference a number of items. The problem popped up when I added the "if dest == None" bit. Python barks that "dest" is an uninitialized variable. That would make sense to me, but what I find odd is that thread_extract_archive() does not have any trouble accessing the session, user, or archive variables. The only difference is that I pass these variables to other functions (e.g. os.path.isfile), and I am doing a simple pythonic test on "dest." What scares me is that my thread has access to extract_archive() variables, but only if I access them in a certain way. Any thoughts? Is there a way to use the more improved "threading" module and pass my thread the entire variable scope of the parent process like I am able to do above? Thanks, Luxore. From bokr at oz.net Tue Nov 15 12:23:08 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 15 Nov 2005 17:23:08 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <7x64qv1tr3.fsf@ruckus.brouhaha.com> <4378a8d6.473364191@news.oz.net> Message-ID: <437a1458.566422091@news.oz.net> On 15 Nov 2005 08:51:59 GMT, Antoon Pardon wrote: >Op 2005-11-14, Bengt Richter schreef : [...] >> You may be interested in reviewing >> >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3 >> >> before continuing this topic ;-) > >It is a rather long thread. You want to avoid this one becomes of >comparable length? Not necessarily. I just thought it might help in making new discussions of previously discussed ideas clearer faster ;-) Sometimes rehashing old topics seems just tedious, but sometimes someone has a hunch that they are struggling to express, and they haven't yet succeeded in communicating its essence. Then old discussions can sometimes serve like first drafts of a speech, and revisions can prevent repeat of misunderstandings that in the archived discussions one can see were inevitable. If the nascent idea comes out viable, we all benefit, and the tedium will have been worth it. If not, well, then at least some ideas will have clearer form, and the whole process will have been a social event that some will have enjoyed anyway ;-) Regards, Bengt Richter From mwm at mired.org Fri Nov 25 16:34:14 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 25 Nov 2005 16:34:14 -0500 Subject: Which license should I use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> <863blkijjv.fsf@bhuda.mired.org> <87sltklawy.fsf_-_@lucien.dreaming> Message-ID: <86y83ch0o9.fsf@bhuda.mired.org> bkhl at stp.lingfil.uu.se (Bj??rn Lindstr??m) writes: > Mike Meyer writes: >> IANAL, but I don't believe the GPL helps in this situation. It places >> conditions on redistributing the code; it doesn't force you to >> redistribute modifieed code. Your employers could refuse to let you >> take the code with you because they own partial copyright on it. They >> couldn't sell it later because of the GPL on it, but that's not your >> issue here. > If they have the rights to the code, they can sell it, under the GPL or > any license of their choosing. In addition, if you GPL it, your employer > will be able to sell it, just like anyone else. You're right - the GPL doesn't prevent them from selling it; it just requires that they make source available to anyone they sell it to, and prevents them from preventing people who buy it from giving it away to anyone they want. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From OurLab at gmail.com Tue Nov 1 21:59:03 2005 From: OurLab at gmail.com (Alex) Date: 1 Nov 2005 18:59:03 -0800 Subject: Pickling and unpickling inherited attributes In-Reply-To: References: <1130713951.953157.270130@g14g2000cwa.googlegroups.com> <1130851315.487444.205760@g47g2000cwa.googlegroups.com> Message-ID: <1130900343.033334.321830@o13g2000cwo.googlegroups.com> > > > OK, but do be aware that slots was intended solely as a > memory-conservation measure where large numbers of objects are being > created. You are therefore subverting its true intent by using it to > limit the assignment of extra attributes (and there has been much recent > discussion on this list, though not in this thread, about what to do > instead. > > regards > Steve > -- Oh, that too... We have tens of thousands of these objects in the memory at the same moment, so memory conservation is another reason for slots. From james at colannino.org Fri Nov 11 18:33:43 2005 From: james at colannino.org (James Colannino) Date: Fri, 11 Nov 2005 15:33:43 -0800 Subject: os.chown() In-Reply-To: <86zmoa3gyp.fsf@bhuda.mired.org> References: <86zmoa3gyp.fsf@bhuda.mired.org> Message-ID: <43752A57.4040900@colannino.org> Mike Meyer wrote: >You want pwd.getpwnam and grp.getgrnam. > > Thanks. Hope my newbie questions haven't gotten on anybody's nerves yet ;) James -- My blog: http://www.crazydrclaw.com/ My homepage: http://james.colannino.org/ "A well regulated militia being necessary to the security of a free state, THE RIGHT of the people to keep and bear arms SHALL NOT BE INFRINGED." --United States Constitution, Second Ammendment From pythonnew at gmail.com Tue Nov 15 00:20:00 2005 From: pythonnew at gmail.com (Ben Bush) Date: Mon, 14 Nov 2005 21:20:00 -0800 Subject: compare list In-Reply-To: <437936F6.1010503@cc.umanitoba.ca> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> Message-ID: <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> what does the following code mean? if item in list2: if item + 1 in list1 and item + 1 in list2: On 11/14/05, Brian van den Broek wrote: > > Ben Bush said unto the world upon 2005-11-14 05:51: > > I have four lists: > > lisA=[1,2,3,4,5,6,9] > > lisB=[1,6,5] > > lisC=[5,6,3] > > lisD=[11,14,12,15] > > how can I write a function to compare lisB, lisC and lisD with lisA, if > they > > share two continuous elements (the order does not matter), then return > 1, > > otherwise return 0. For example, lisA, lisB and lisC have 5,6 or 6,5 so > > these comparison will return 1 but the comparison between lisD and lisA > > return 0. > > -- > > Thanks! > > Ben Bush > > Hi Ben, > > the code below is tested no further than shown. And, I'm no expert -- > I imagine there are better ways. With luck, I'll learn them in a > follow-up from someone more skilled :-) > > >>> def list_common_continuity_comp(list1, list2): > for item in list1: > if item in list2: > if item + 1 in list1 and item + 1 in list2: > return True > return False > > >>> lisA=[1,2,3,4,5,6,9] > >>> lisB=[1,6,5] > >>> lisC=[5,6,3] > >>> lisD=[11,14,12,15] > >>> list_common_continuity_comp(lisA, lisB) > True > >>> list_common_continuity_comp(lisA, lisC) > True > >>> list_common_continuity_comp(lisA, lisD) > False > >>> list_common_continuity_comp(lisD, lisA) > False > >>> list_common_continuity_comp(lisA, lisA) > True > >>> list_common_continuity_comp(lisB, lisA) > True > > > That gets you a binary comparison. To make it a polyadic: > > > >>> def multi_list_continuity_comp(list_of_lists): > list1 = list_of_lists[0] > for other_list in list_of_lists[1:]: > if not list_common_continuity_comp(list1, other_list): > return False > return True > > >>> meta_list1 = [lisA, lisB, lisC, lisD] > >>> meta_list2 = meta_list1[:-1] > >>> multi_list_continuity_comp(meta_list1) > False > >>> multi_list_continuity_comp(meta_list2) > True > >>> > > > Some edge cases haven't been handled: > > >>> multi_list_continuity_comp([]) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > multi_list_continuity_comp([]) > File "", line 2, in multi_list_continuity_comp > list1 = list_of_lists[0] > IndexError: list index out of range > >>> > > but this should get you started. > > Best, > > Brian vdB > > -- Thanks! Ben Bush -------------- next part -------------- An HTML attachment was scrubbed... URL: From xray_alpha_charlie at yahoo.com Sun Nov 13 21:54:28 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Sun, 13 Nov 2005 18:54:28 -0800 (PST) Subject: HOW do you stop a print??? Message-ID: <20051114025428.17945.qmail@web35911.mail.mud.yahoo.com> ok...I am running the following program: def printMultiples (n): i = 1 while i <= 6: print n*i, ' \t ', i = i + 1 i = 1 while i <= 6: printMultiples(i) i = i + 1 this is supposed to return a simple multiplication table, but for some reason it does not want to stop printing after 6 columns...instead it prints from left to right for a total of 10 columns...I need some sort of a "stop print" after the first 6 columns and then continue to fill in those columns...Can anybody solve this problem?... -thanks- --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan-news at grisby.org Fri Nov 18 10:47:53 2005 From: duncan-news at grisby.org (Duncan Grisby) Date: Fri, 18 Nov 2005 16:47:53 +0100 Subject: Regular expressions and the global interpreter lock Message-ID: Hi, I have encountered a problem with the re module. I have a multi-threaded program that does lots of regular expression searching, with some relatively complex regular expressions. Occasionally, events can conspire to mean that the re search takes minutes. That's bad enough in and of itself, but the real problem is that the re engine does not release the interpreter lock while it is running. All the other threads are therefore blocked for the entire time it takes to do the regular expression search. Is there any fundamental reason why the re module cannot release the interpreter lock, for at least some of the time it is running? The ideal situation for me would be if it could do most of its work with the lock released, since the software is running on a multi processor machine that could productively do other work while the re is being processed. Failing that, could it at least periodically release the lock to give other threads a chance to run? A quick look at the code in _sre.c suggests that for most of the time, no Python objects are being manipulated, so the interpreter lock could be released. Has anyone tried to do that? Thanks, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From gdamjan at gmail.com Wed Nov 16 18:00:29 2005 From: gdamjan at gmail.com (Damjan) Date: Thu, 17 Nov 2005 00:00:29 +0100 Subject: HTML generation vs PSP vs Templating Engines References: <1132158690.299954.90920@g14g2000cwa.googlegroups.com> Message-ID: > After some thought I decided to leave the various frameworks > aside for the time being and use mod_python.publisher along with some > means of generating HTML on the fly. I kind of like KID templates the most, you can easyly work with them in any HTML authoring software, they are easy to use (prety much pythonic). -- damjan From sdouche at gmail.com Mon Nov 28 06:34:53 2005 From: sdouche at gmail.com (Sebastien Douche) Date: Mon, 28 Nov 2005 12:34:53 +0100 Subject: General question about Python design goals In-Reply-To: References: Message-ID: <5e1183fa0511280334m2cf0e309w682c313923b9bf85@mail.gmail.com> On 11/28/05, Christoph Zwerschke wrote: > Sometimes I find myself stumbling over Python issues which have to do > with what I perceive as a lack of orthogonality. I use this thread to asking on python conception : why python have so many builtins ? I cannot understand why we use a builtins for open a file. Is it a old decision ? If anyone have a pointer of this or can explain me. Regards. -- S?bastien Douche From paul at boddie.org.uk Wed Nov 30 11:07:37 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 30 Nov 2005 08:07:37 -0800 Subject: python speed In-Reply-To: <_eqdnYiZUra9XxDenZ2dnUVZ_sadnZ2d@comcast.com> 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: <1133366857.743448.146480@g14g2000cwa.googlegroups.com> Steven Bethard wrote: > David Rasmussen wrote: > > Faster than assembly? LOL... :) Faster than physics? ;-) > I think the claim goes something along the lines of "assembly is so hard > to get right that if you can automatically generate it from a HLL, not > only will it be more likely to be correct, it will be more likely to be > fast because the code generator can provide the appropriate optimizations". I think this is just a restatement of existing motivations for using high-level languages and compilers. My impression is that PyPy takes inspiration from work which showed that run-time knowledge can sometimes produce code that is better optimised than that produced by a compiler. That said, when everyone starts showing off their favourite benchmarks, it might be more interesting not to parade some festival of arithmetic yet again. Where more recent versions of the Java virtual machines have improved is in their handling of object memory allocation, amongst other things, and merely scoffing that Java is slow (by pulling specific/specialised extension packages out of the hat) fails to acknowledge the potential for similar improvements (and others) in Python, especially where programs involving plain objects - as opposed to numbers, and where no conveniently available and wrapped C/C++ package exists for the task - are concerned. Paul From uval at rz.uni-karlsruhe.de Mon Nov 21 06:59:35 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Mon, 21 Nov 2005 12:59:35 +0100 Subject: sort the list In-Reply-To: References: Message-ID: Shi Mu wrote: > I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list > based on the second value in the item? > That is, > I want the list to be: > [[3,2],[1,4],[2,5],[3,9]] >>> lst = [[1,4],[3,9],[2,5],[3,2]] >>> lst [[1, 4], [3, 9], [2, 5], [3, 2]] >>> >>> >>> lst.sort(cmp = lambda x,y: cmp(x[1], y[1])) >>> lst [[3, 2], [1, 4], [2, 5], [3, 9]] >>> works for Python 2.4 in earlier Pythons just let cmp = .. away Regards, Daniel From grante at visi.com Thu Nov 17 20:35:38 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 18 Nov 2005 01:35:38 -0000 Subject: running functions References: <1132179612.759373.130900@g43g2000cwa.googlegroups.com> <437d2a78@nntp0.pdx.net> Message-ID: <11nqbvagv5s8251@corp.supernews.com> On 2005-11-18, Scott David Daniels wrote: > Gorlon the Impossible wrote: > >> I have to agree with you there. Threading is working out great for me >> so far. The multiprocess thing has just baffled me, but then again I'm >> learning. Any tips or suggestions offered are appreciated... > > The reason multiprocess is easier is that you have enforced > separation. Multiple processes / threads / whatever that share > reads and writes into shared memory are rife with > irreproducible bugs and untestable code. There can be problems, but you make it sound way worse than it really is. I've been doing threaded SW for a lot of years (yikes! almost 25), and it's just not that hard to deal with shared objects/variables -- especially in Python with its GIL. I think it's easier and more intuitive than forking. I've written a lot of (admittedly not huge) Python programs using threading (some with 30-40 thread), and I don't remember ever tripping over anything significant. I think dealing with shared objects is easier than figuring out how to do inter-process communications using sockets or Posix shared memory or whatnot. It's not difficult if you don't have to do any communication between processes, but in that case, shared objects aren't a problem either. [...] > That is why threads that don't do trivial things are so scary. Maybe I've just been using threads too long, but I don't think they're any more scary than software in general is scary. -- Grant Edwards grante Yow! I LIKE Aisle 7a. at visi.com From mclaugb at nospm.yahoo.com Wed Nov 9 10:26:51 2005 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Wed, 9 Nov 2005 15:26:51 -0000 Subject: Winpdb question Message-ID: Is there any way to either restrict the number of variables displayed in the Globals or Locals section. It is a pain having to search through this list all of the time just to look at the values of variables in my program. Bryan From riek at zem.uni-bonn.de Fri Nov 4 14:38:10 2005 From: riek at zem.uni-bonn.de (riek at zem.uni-bonn.de) Date: 4 Nov 2005 11:38:10 -0800 Subject: python, mssql and unicode In-Reply-To: <3svh9oFqfulaU1@uni-berlin.de> References: <1131034411.281189.17770@g43g2000cwa.googlegroups.com> <3svh9oFqfulaU1@uni-berlin.de> Message-ID: <1131133090.948194.122620@o13g2000cwo.googlegroups.com> Hi Diez :) I tried converting the query string to utf-16 but only got weird results. The problem might lie with the _mssql module (which pymssql is using, it's just a wrap around _mssql) that I am using... I'll post what I get from converting to utf-16 later, maybe you have an idea... From tnoell at gmail.com Wed Nov 16 15:04:11 2005 From: tnoell at gmail.com (tnoell at gmail.com) Date: 16 Nov 2005 12:04:11 -0800 Subject: readline vi mode in python interactive shell Message-ID: <1132171451.328876.177210@z14g2000cwz.googlegroups.com> Hi comp.lang.python: New to the group and new to python, so don't tear me up too much ... I installed the GNU readline support in python2.4, and it is working, but there is one annoying behaviour that I am hoping to squash ... Namely, when I hit to go to edit mode, then hit 'k' to go up in the command history, the prompt is put at the start of the line. Other places I use vi mode command line editing (e.g., zsh), the cursor is at the end of the previous command. More often than not, I am wanting to edit the latter part of the previous command, not the start. Is there any way to tell readline to put the cursor at the end of the command line when browsing them? Thx for any light you can shinte, Tim From mwm at mired.org Mon Nov 28 20:43:40 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 28 Nov 2005 20:43:40 -0500 Subject: New docs for set elements/dictionary keys References: <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> <863bljf1o8.fsf@bhuda.mired.org> <4388f6ce$0$22897$9b622d9e@news.freenet.de> <86mzjqew8l.fsf_-_@bhuda.mired.org> <43896474$0$22007$9b622d9e@news.freenet.de> <86k6etd8p2.fsf@bhuda.mired.org> <438A3896.7020501@v.loewis.de> <86wtitbiom.fsf@bhuda.mired.org> <863blhwcnc.fsf@bhuda.mired.org> Message-ID: <864q5wteib.fsf@bhuda.mired.org> Christoph Zwerschke writes: > Mike Meyer wrote: >> Christoph Zwerschke wrote: >>>I think that is not so bad. How about this simplification: >>> >>>Any hashable object(1) can be used as a dictionary key/set >>>element. Lists, sets and dicts are not hashable, and can not be >>>used. Tuples can be used if all the things they contain are >>>hashable. Instances of all other built-in types and most user-defined >>>classes are hashable. >>> >>>(1) Objects for which the hash() function returns an appropriate >>>(proper?) value. See the __hash__ documentation for details. >> I think that will do quite nicely, as the information about __hash__, >> __cmp__ and __eq__ are all in the __hash__ documentation. You wrote it >> - why don't you submit a PR with it? > Actually you wrote it ;-) Do suggestions like this one go to the > normal Python sf bug tracker? Yup. I went ahead and did it. ID #1368768. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bokr at oz.net Tue Nov 29 09:31:46 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 29 Nov 2005 14:31:46 GMT Subject: Precision for equality of two floats? References: <1h6q8gv.16lvyv91k5bodeN%aleax@mail.comcast.net> Message-ID: <438c634e.224486674@news.oz.net> On Mon, 28 Nov 2005 07:58:37 -0800, aleax at mail.comcast.net (Alex Martelli) wrote: >Anton81 wrote: > >> Hi! >> >> When I do simple calculation with float values, they are rarely exactly >> equal even if they should be. What is the threshold and how can I change >> it? > >Python's builtin floats compare for exact bit-by-bit equality -- no >"threshold". You may want to look at the allclose function in the Does "exact bit-by-bit" mean that a = a == is 100% guaranteed? I.e., are there implementations where an expression value might remain in 80-bit representation in the fpu and be rounded to 64 bits for assignment to a and then not compare equal because the second a is a rounded 64-bit value compared to the regenerated 80-bit value? Since cpython bytecodes store expression values on the cpu stack, not the fpu stack, I assume it's ok there, but is it a potential problem for optimizers generating machine code? Or is it spec-ed for mandatory as-if-storing-both-arguments-as-double-before-comparing behaviour? Just wondering ;-) Regards, Bengt Richter From zolaris at gmail.com Thu Nov 10 20:44:33 2005 From: zolaris at gmail.com (zolaris at gmail.com) Date: 10 Nov 2005 17:44:33 -0800 Subject: Printing current time to a file Message-ID: <1131673473.043969.226000@f14g2000cwb.googlegroups.com> I am trying to print the current system time to a file. I know only a little bit about Python. I have gotten the very simple: Print time.time() to work properly. From what I gather the line to print it to a file should look like: self.log.write(time.ctime(time.time())) But that prints nothing in the file assigned to log. Is there something I should be doing extra? Thanks. From tuvas21 at gmail.com Fri Nov 4 12:11:30 2005 From: tuvas21 at gmail.com (Tuvas) Date: 4 Nov 2005 09:11:30 -0800 Subject: Tkinter- checkbutton In-Reply-To: <1131123953.135003.86390@g14g2000cwa.googlegroups.com> References: <1131123953.135003.86390@g14g2000cwa.googlegroups.com> Message-ID: <1131124290.860885.105430@g14g2000cwa.googlegroups.com> Ere, ignore the mis-capped Checkbutton and the missed master call in it... From aleax at mail.comcast.net Tue Nov 22 22:56:59 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 22 Nov 2005 19:56:59 -0800 Subject: about sort and dictionary References: <1132493880.591426.224140@g49g2000cwa.googlegroups.com> <1132651818.348370.117450@g49g2000cwa.googlegroups.com> <1132653873.855348.265740@g47g2000cwa.googlegroups.com> <1132700747.794586.73170@g44g2000cwa.googlegroups.com> Message-ID: <1h6g1t6.qxc6tnag2skbN%aleax@mail.comcast.net> bonono at gmail.com wrote: ... > intuitive seems to be a very subjective matter, depends on once > background etc :-) That's a strong point of Ruby, actually -- allowing an exclamation mark at the end of a method name, which conventionally is always used to indicate that the method is a mutator. So, you can have a.reverse [NOT mutating a since no !] _and_ a.reverse! [mutating a]. Probably too much of a change even for Python 3000, alas... but, it DOES make it obvious when an object's getting mutated, and when not... Alex From cochrane at shake56.esscc.uq.edu.au Wed Nov 2 01:08:22 2005 From: cochrane at shake56.esscc.uq.edu.au (Paul Cochrane) Date: Wed, 2 Nov 2005 06:08:22 +0000 (UTC) Subject: Running autogenerated code in another python instance Message-ID: Hi all, I've got an application that I'm writing that autogenerates python code which I then execute with exec(). I know that this is not the best way to run things, and I'm not 100% sure as to what I really should do. I've had a look through Programming Python and the Python Cookbook, which have given me ideas, but nothing has gelled yet, so I thought I'd put the question to the community. But first, let me be a little more detailed in what I want to do: I have a python module (called pyvisi, but you don't need to know that) which attempts to simplify the writing of scripts for high performance computing visualisation applications. What it does is provides a layer between the user and the actual renderer backend that is actually going to process the code. Effectively all my app does is to autogenerate the code the user would have to write were they savvy with the python interface to vtk (the visualisation toolkit). This reduces the effort on the part of the user quite a lot. What I have currently is my python module generating the equivalent vtk-python code and then executing this in an exec(). This is not nice (and potentially very slow), especially if one has to share around data, so what I want to do is have a separate python process or thread which just sits there accepting the autogenerated text strings as if the user were writing them directly at the python prompt (or equivalent), and returning any error messages generated. Also, I want to be able to share data between the two processes/threads so that one doesn't have to turn numerical data into a string which is then turned back into numerical data inside the exec() call (ugly, I know, but it works). Maybe a picture will help as well (time going down the page): Main Proc(1) | |------------> Renderer(2) | | | <-- Data(3) --> | | | | more commands | | ---------------> | | | | even more cmds | | ---------------> | | | | render finished | | shut down Rndrr | | <--------------- | | | main proc continues or finishes (1) the main process where the python code destined for the backend is generated (2) the secondary process which accepts and runs the code it receives (3) data to visualised; shared between the two processes Ok, hopefully you get what I want to do now... So, what is the best way to do this? Threads share memory, so this is handy to share the data around, however, how does one send arbitrary commands to be processed by a thread? One way to do this would be to use pipes, but this means that I can't share the data around as easily. I've also seen the Pyro project as a possibility, but I would like to keep this as "core python" as possible. Any help or advice would be really (really!) appreciated. TIA Paul -- Paul Cochrane Earth Systems Science Computational Centre University of Queensland, Brisbane, Queensland 4072, Australia E: cochrane at esscc dot uq dot edu dot au From gh at ghaering.de Mon Nov 7 09:36:20 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 07 Nov 2005 15:36:20 +0100 Subject: Python and PL/SQL In-Reply-To: <1131371902.061620.295920@g49g2000cwa.googlegroups.com> References: <1131369305.252487.30220@o13g2000cwo.googlegroups.com> <1131371902.061620.295920@g49g2000cwa.googlegroups.com> Message-ID: <436F6664.2040906@ghaering.de> infidel wrote: > vb_bv wrote: > >>Does Pyton PL/SQL programming language of Oracle support? >> > PL/SQL is only supported *inside* Oracle databases. Python can be used > to call PL/SQL procedures (I recommend the cx_Oracle module), but you > can't run Python inside the database like PL/SQL. If one is really really really insisting on running Python code inside an Oracle database, I think it could be done: you can write Oracle stored procedures in C libraries, Java libraries and even .NET libraries (10g on win32). And there are Python implementations for C, Java and .NET. So much for the theory. In my not so humble opinion, instead of all this fancy stuff, you will be better off writing your stored procedures in PL/SQL, which is a very good language for manipulating data, and writing portable, efficient and maintainable server-side database code. -- Gerhard From gsakkis at rutgers.edu Mon Nov 21 13:01:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 21 Nov 2005 10:01:50 -0800 Subject: about sort and dictionary References: Message-ID: <1132596110.312103.179750@g43g2000cwa.googlegroups.com> "Shi Mu" wrote: > Got confused by the following code: > >>> a [6, 3, 1] > >>> b [4, 3, 1] > >>> c > {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]} > >>> c[2].append(b.sort()) > >>> c > {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]} > #why c can not append the sorted b?? In python 2.4, you can use the sorted() builtin instead: c[2].append(sorted(b)) George From mwm at mired.org Sun Nov 13 17:07:03 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 13 Nov 2005 17:07:03 -0500 Subject: Copyright References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <1131859100.890118.317030@g14g2000cwa.googlegroups.com> <868xvt147q.fsf@bhuda.mired.org> <1131915269.961526.93330@g49g2000cwa.googlegroups.com> Message-ID: <86wtjcyzg8.fsf@bhuda.mired.org> "The Eternal Squire" writes: >>Further, recent evidence is that this is no longer true in that >>country, assuming it ever was. > Wow, how Machiaviellian. Just an observation on the state of the US. It's been a long while since the people running the country did so for the people. >>Copyright by itself does not pay >>the rent, put food on the table or put people through college. It's >>strong enough to be do that *if* the public values what you create >>enough and *if* you work hard enough at marketing it and *if* you >>produce enough. Those are some mighty big ifs. > Yes, profitable innovation is 1 percent inspiration plus 99 percent > persperation. The critical thing is that copyright isn't a vital part of the formula. Lots of people make a good living creating intellectual property without needing copyright on said property to provide the income. The whole claim that copyright benefits the creator is a misdirection. Look at the number of creators who make a living off of sale of copyrighted materials vs the number of people between the creator and the consumer making a living off their work. Tell me who owns the big, fancy offices - the creators, or the middlemen. Tell me who's lobbying congress to create laws that protect and extend copyright. Finally, notice the difference between what you pay for a mass-market work - dollars - and what the creator gets - pennies, and tell me who gets the difference. Yes, copyright benefits the creator, but the primary beneficiaries are the people who arrange to put hard media in the hands of the public - the publishers. During the bulk of the twentieth century, this arrangement was reasonable - the middlemen were putting up the money, and taking all the financial risks. In some cases, they even took on the risk for the creator themselves, paying the creator an advance against royalties, so that if the product failed in the market, the creator got paid, and they took the hit for it. Given all that, the *real* question isn't "How will the creator get paid?", it's "How will the creator get published?" The last few decades have given us a *lot* of answers to that: put it on their web site, which can be had for free; put it in a podcat; blog it; put it in a torrent; and so on. How they make money off of it after that is still being explored, but people are doing it. Yes, the creator doesn't sell as many copies this way. On the other hand, they get a much larger percentage of the price of the product. Publishers are in danger of becoming irrelevant. That's why they're making all the noise, and doing everything they can to limit the publics rights. They're distracting people from the real issue - their bottom line - by claiming it's "for the good of the creator", while they try and make sure their business model - the one where they get the bulk of the profits - stays in place. *These* are the people whose side you are arguing, not the creator. >>Maybe "the people" you're talking about above are "the rich corporations >>with the congresscritters in their pockets." But that's hardly "the >>majority". > It sometimes works that way, unfortunately. But at least we can vote > the > bastards out when we hear of such things. It's been working that way regulary since the 1920s, and the same bastards are still running the country. >>You apparently think that taking the opportunity for the creator to be >>rewarded for their efforts is ok if you deride other people who do >>that very thing. > And in what way is piracy a form of creation? That's a complete non-sequitor. >>So what's the difference between the RIAA and a >>pirate who publicly points out that what the RIAA is up to? > The difference is that the RIAA does not copy software without the > copyright holder's consent. Actually, they do. More accurately, the companies that form the RIAA do. That's the point. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From matthewharrison at gmail.com Wed Nov 2 13:30:10 2005 From: matthewharrison at gmail.com (matt) Date: 2 Nov 2005 10:30:10 -0800 Subject: pyzeroconf on linux... Message-ID: <1130956210.722448.178960@g44g2000cwa.googlegroups.com> Hey, has anyone out there tried pyzeroconf on Linux? I'm using Andrew's code from http://www.amk.ca/python/zeroconf to publish and discover services. The code works under Mac. But it doesn't under linux (FC4). I should clarify that, it appears that the publish code doesn't work under linux. The discovery code will discover stuff (on linux) that I publish on the Mac. I've fired up ethereal and it doesn't appear that much is happening in the way of UDP on port 5353 (on linux). Does anyone have any hints or suggestions? thanks matt From steve at holdenweb.com Wed Nov 2 17:19:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Nov 2005 22:19:03 +0000 Subject: Python and MySQL In-Reply-To: References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: Thomas Bartkus wrote: > "Aquarius" wrote in message > news:1130948507.082484.199730 at f14g2000cwb.googlegroups.com... > >>I appologize in advance for this strange (and possibly stupid) >>question. >> >>I want to know if there is a way to interface a MySQL database without >>Python-MySQL or without installing anything that has C files that need >>to be compiled. The reason for this, is that I want to develop a >>certain web application, but my hosting provider (!#@$!@#%) isn't very >>eager to supply Python-MySQL (or any modules to python). Is there an >>alternative approach I could use to pass around this ridiculos lack of >>functionality? > > > Well, I'm looking at the source for the ever popular MySQLdb library. It > appears to be nothing but straight up Python source code. I see no reason > why you couldn't just take these modules and put them in your own private > directory. There is nothing secret here. > > But > > As others have already pointed out, after you go to this trouble, your > hosting provider will still suck! I'm sure you can you can get lot's of > suggestions for a suitable replacement. > I have a _mysql.c as a part of my distrbution of MySQLdb. Don't you? 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 lycka at carmen.se Tue Nov 8 11:11:20 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 08 Nov 2005 17:11:20 +0100 Subject: Using python for writing models: How to run models in restricted python mode? In-Reply-To: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> Message-ID: vinjvinj wrote: > I have an application which allows multiple users to write models. > These models get distributed on a grid of compute engines. users submit > their models through a web interface. I want to > > 1. restrict the user from doing any file io, exec, import, eval, etc. I > was thinking of writing a plugin for pylint to do all the checks? Is > this is a good way given that there is no restricted python. What are > the things I should serach for in python code I'm not sure why you want to prevent e.g. all file io. Let the jobs run as users with very limited permissions. > 2. restrict the amount of memory a module uses as well. For instance > how can I restrict a user from doing a = range(10000000000) or similar > tasks so that my whole compute farm does not come down. Use Sun Grid Engine. http://gridengine.sunsource.net/documentation.html From mwm at mired.org Tue Nov 8 20:14:38 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 20:14:38 -0500 Subject: Invoking Python from Python References: <1131466225.744361.7010@z14g2000cwz.googlegroups.com> Message-ID: <86acgeaagx.fsf@bhuda.mired.org> claird at lairds.us (Cameron Laird) writes: > In article , > Thomas Guettler wrote: >>creating source code with a script, is no good solution. >>Once I had to maintain lisp code which stored its data in lisp code, too >>(incl. conditions and loops). It was a nightmare. > Yes and no. There are times when it's justified. I ENTIRELY > agree, though, that many people who *think* that's what they > want to do simply don't understand how dynamic base Python is, > and therefore don't realize how much easier it can be to write > a single, unified application. Yup. Python can do a lot of things directly that other languages might solve with code that writes code. However, that's a *very* powerful technic, and not everything it does can be done with lesser tools. On the other hand, it's a *very* powerful technic, and abusing it can easilyi create unmaintainable code. > At this point, 'twould be appropriate to describe an instance > or two in which code generation is a good idea. While I have > some, they're tedious to make clear. Maybe I'll do so in a > follow-up ... Since Cameron didn't provide examples, let me grab a simple one. The cheetah templating system works by creating Python programs from the template. The programs, when run, output the "filled in" template. The templates are generally more maintainable than the raw python - even if you cleaned up all the things Cheetah does to make writing templates easier. This model makes it possible for Cheetah templates use inheritance - they can inherit from each other, from python classes, and python classes can inherit from them. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From server.prime at gmail.com Wed Nov 2 10:20:17 2005 From: server.prime at gmail.com (server.prime at gmail.com) Date: 2 Nov 2005 07:20:17 -0800 Subject: computer programming Message-ID: <1130944817.168134.124690@g14g2000cwa.googlegroups.com> hello all! if u dont mind, please visit and register in my site www.javaholics.tk for java programming discussions all other programming languages and discussions are welcome! its a gr8 site and a growing community the only advantage is that its got more features as its based on SMF(Simple Machines Forum) with a advanced professional interface enjoy! remember u cant see hidden sections until you register... and thank you! -Prado. From aleax at mail.comcast.net Mon Nov 7 22:12:11 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 7 Nov 2005 19:12:11 -0800 Subject: PYTHON LOOSING FOR JAVA??????? References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> Message-ID: <1h5o6j6.ikzaeu11af7rpN%aleax@mail.comcast.net> Fcamattti wrote: > So I have a doubt. I'd like to know what do you think about the joint > of efforts of Sun Microsystems and the Google to create a office web > based. I sincerely enjoy the idea althoug I'd like to know what will be > the future of this wonderful language called Python?????? Since Sun's existing StarOffice supports Python, _and_ Google is well known as an enthusiastic endorser of Python (http://www.python.org/Quotes.html etc etc), why would any possible cooperation between Sun's Office apps, and Google, cause anybody to _worry_ about "the future of ... Python"?! Alex From elbertlev at hotmail.com Wed Nov 16 11:32:59 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 16 Nov 2005 08:32:59 -0800 Subject: python and VisualFox dbf In-Reply-To: <1132080408.157794.129920@g14g2000cwa.googlegroups.com> References: <1132080408.157794.129920@g14g2000cwa.googlegroups.com> Message-ID: <1132158779.662070.190010@g43g2000cwa.googlegroups.com> A hint :) Is ADO supported? From cjw at sympatico.ca Wed Nov 2 08:53:32 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 02 Nov 2005 08:53:32 -0500 Subject: 'super' to only be used for diamond inheritance problems? In-Reply-To: References: Message-ID: Giovanni Bajo wrote: > Alex Hunsley wrote: > > >>I've seen a few discussion about the use of 'super' in Python, >>including the opinion that 'super' should only be used to solve >>inheritance diamond problem. (And that a constructor that wants to >>call the superclass methods should just call them by name and forget >>about super.) What is people's opinion on this? Does it make any >>sense? > > > > I personally consider super a half-failure in Python. Some of my reasons are > cited here: > http://fuhm.org/super-harmful/ > It would help to have some clearer guidelines on class (type) usage. I like James Knight's (fuhm) suggestion with respect to consistent signatures. Colin W. From mde at micah.elliott.name Fri Nov 18 16:24:53 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Fri, 18 Nov 2005 13:24:53 -0800 Subject: Choose meaningful subjects for posts [was: Re: newb ?] In-Reply-To: <17278.14762.150392.942325@montanaro.dyndns.org> References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> <86u0eaj5ed.fsf@bhuda.mired.org> <11nsbh2r64kb9ae@corp.supernews.com> <17278.14762.150392.942325@montanaro.dyndns.org> Message-ID: <20051118212452.GB9941@kitchen.client.attbi.com> On Nov 18, skip at pobox.com wrote: > Grant> Obligatory aside: I'm completely baffled why anybody would choose > Grant> the mailing list format over Usenet. I don't even read mailing > Grant> lists via mailing lists. I recommend gmane.org's NNTP server for > Grant> all your mailing list needs. > > For the same reason I don't like web forums as a means of > communication. I would much rather operate in an interrupt-driven > mode than have to remember to poll some external service to get my > daily helping of information. Agreed! I notice that a lot of people post here from google. I did it too before I discovered the mailing list, which I now use because I haven't found a news reader that I like nearly as much as mutt. It's quite nice to combine email and news into one. If you have any suggestions for console-based newsreaders, I'm all ears. I have tried to setup "tin" in the past but the voluminosity of its documentation made me give up. -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From eric.moritz at gmail.com Mon Nov 28 23:15:15 2005 From: eric.moritz at gmail.com (eric.moritz at gmail.com) Date: 28 Nov 2005 20:15:15 -0800 Subject: New Position at Naples Daily News using Django/Python Message-ID: <1133237715.097228.149760@f14g2000cwb.googlegroups.com> One of the most respected and award-winning newspaper Web teams in the world has moved to Florida and is looking for an experienced server-side Web developer. NDN Productions -- the online and new media publishing division of the Naples Daily News -- is looking for a full-time Python programmer to develop Internet-based applications that cross from computers to mobile phones to iPods to Sony PSPs. We strive for innovation and nimble development for sites that embrace relational databases in ways they've rarely been used on the local level coupled with broadband-centric multimedia content that all works together in a platform-independent manner. In other words, we strive to build the kinds of Web sites and related offshoots that you wish were in your hometown. We're big believers and contributors to the open-source community. Our primary development platform is Python (mod_python) and PostgreSQL, with a particular emphasis on using the Django infrastructure. That being said, we believe a solid background in Web application design is more important than knowledge of a particular language or platform. If you're a smart cookie and it shows, we know that you'll have no problems picking up the tools we use. We embrace a highly creative, non-traditional work environment. We love to work fast and have fun, with the time between having a great idea and that idea being added to one of our sites being measured in days, if not hours. Our salary is competitive, though not crazy huge, and our benefits package is sweet. And because our agile and autonomous online team works under the umbrella of one of the largest and most stabile diversified media companies in the nation, you don't have to worry about your checks ever bouncing. If you work with us, your mom and dad will be proud, and your friends will be envious. So, if you learn things quickly, want to hang out with cool people and build amazing Web content, than this is the place for you. We're an equal-opportunity employer. In fact, we even hire folks from Missouri. So, contact Rob Curley at NDN Productions right now before one of your buddies beats you to this great gig. Rob Curley Director of New Media NDN Productions/The Naples Daily News E >> nerds at bonitanews.com P >> 239.435.3473 From larry.bates at websafe.com Wed Nov 9 19:40:05 2005 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 09 Nov 2005 18:40:05 -0600 Subject: parse data In-Reply-To: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> References: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> Message-ID: <437296E5.3050109@websafe.com> py wrote: > I have some data (in a string) such as.... > > person number 1 > > Name: bob > Age: 50 > > > person number 2 > > Name: jim > Age: 39 > > ...all that is stored in a string. I need to pull out the names of the > different people and put them in a list or something. Any > suggestions...besides doing data.index("name")...over and over? > > thanks! > Something like this works if line spacing can be depended on. Also a good way to hide the actual format of the string from your main program. Larry Bates class personClass: def __init__(self, nameline, ageline): self.name=nameline.split(':')[1].strip() self.age=int(ageline.split(':')[1].strip()) return class peopleClass: def __init__(self, initialstring): # # Define a list where I can store people # self.peoplelist=[] self.next_index=0 # # Split the initial string on newlines # lines=initialstring.split('\n') # # Loop over the lines separating the people out # while 1: lines.pop(0) # Throw away the person number line bl1=lines.pop(0) # Throw away the blank line nameline=lines.pop(0) # Get name line ageline=lines.pop(0) # Get age line # # Create person instance and append to peoplelist # self.peoplelist.append(personClass(nameline, ageline)) try: bl2=lines.pop(0) # Throw away trailing blank line 1 except: break # All done if there is none try: bl3=lines.pop(0) # Throw away trailing blank line 2 except: break # All done if there is none return def __len__(self): return len(self.peoplelist) def __iter__(self): return self def next(self): # # Try to get the next person # try: PERSON=self.peoplelist[self.next_index] except: self.next_index=0 raise StopIteration # # Increment the index pointer for the next call # self.next_index+=1 return PERSON if __name__== "__main__": initialstring='person number 1\n\nName: bob\nAge: 50\n\n\n' \ 'person number 2\n\nName: jim\nAge: 39' people=peopleClass(initialstring) for person in people: print "Name:", person.name print "Age:", person.age From roy at panix.com Thu Nov 17 13:50:50 2005 From: roy at panix.com (Roy Smith) Date: Thu, 17 Nov 2005 18:50:50 +0000 (UTC) Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <437C36EA.8010600@REMOVEMEcyber.com.au> Message-ID: Micah Elliott wrote: > I recently gave up on trying to support (backport to) pre-2.2 in my > projects. It's been ~3 years since 2.2 released and that seem like a > pretty reasonable support window. It depends on what you're doing. If you're developing for in-house use, you have control over what you run and can upgrade whenever you feel you can justify devoting the resources to the upgrade effort. If you're a one-man band, upgrading to a new version may be an hour's work to download and install the latest and greatest. If you're a cog in a large organization, it may be quite a bit more hassle. If you're developing for outside customers, it's a whole different story. Lots of people are running operating systems which are several years old (heck, I'm typing this on a Windows-2000 box), and those operating systems may have shipped with versions of langauges which were several years old at the time they shipped. Consider the following conversation with a prospective customer: Prospect: "I really love your product, the price is OK, and I've got budget approval for the purchase. Now, what do we need to run it?" You: "All you need is a box running Python 2.2". Prospect: "Oh, bummer, we run 2.1 [or 2.0, or 1.5.2] in-house on all our machines". You: "No problem, it's easy to upgrade to 2.2" Prospect: "Unfortunately, not around here it isn't. I.T. owns the servers, and they won't do the upgrade. Looks like we won't be able to use your product after all. Sorry." I'm not saying you shouldn't use new stuff, but don't fool yourself about how long a lifetime old versions have in the field. And, the old adage that "The customer is always right" is a good one. From tuvas21 at gmail.com Mon Nov 7 15:00:07 2005 From: tuvas21 at gmail.com (Tuvas) Date: 7 Nov 2005 12:00:07 -0800 Subject: Tkinter- Building a message box In-Reply-To: <1131390077.610545.316450@g44g2000cwa.googlegroups.com> References: <1131387846.676519.184420@g44g2000cwa.googlegroups.com> <1131389256.633959.267940@g44g2000cwa.googlegroups.com> <1131390077.610545.316450@g44g2000cwa.googlegroups.com> Message-ID: <1131393607.496512.193680@f14g2000cwb.googlegroups.com> Thanks alot, that helped TONS! Just had to modify it slightly, but, well, it works great now. Thanks! From aleax at mail.comcast.net Thu Nov 3 10:39:33 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 07:39:33 -0800 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> Message-ID: <1h5fx6z.10aqr6wdobju6N%aleax@mail.comcast.net> Roy Smith wrote: > > because they do not come with the full range of libraries e.g GDI > > libraries. > > No language has libraries for everything you might ever possibly want to > do. Python has a wide range of libraries for many common tasks, but my no > means all. Still, if it comes down to "language X has a good library for > what we need and language Y doesn't", that will often be (and rightly so) > the decision maker as to which language to use. ...except that -- with ctypes, SWIG, Jython and IronPython implementations, pyrex, BoostPython, and a zillion other tools, it's just about impossible to give examples of libraries which Python cannot use pretty easily and successfully. Library availability (through any or all of these tools) is one of the strong practical argument FOR Python!-) Alex From duncan.booth at invalid.invalid Tue Nov 22 04:05:50 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Nov 2005 09:05:50 GMT Subject: about sort and dictionary References: <1132493880.591426.224140@g49g2000cwa.googlegroups.com> Message-ID: Magnus Lycka wrote: > Actually, I guess it's possible that sorted() is done so > that it works like below, but I don't think pre-sorted() > versions of Python support keyword arguments to list.sort() > anyway... > > def sorted(l, *p, **kw): s=l[:];s.sort(*p, **kw);return s One part you missed, sorted is actually closer to: def sorted(iterable, cmp=None, key=None, reverse=False): "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" s=list(iterable) s.sort(cmp, key, reverse) return s The point being that while in general only a list will have a sort method, the sorted builtin may be called on any iterable and will return a sorted list. Also note that it only accepts specific named arguments, and has a docstring. From bytecolor at yahoo.com Tue Nov 15 10:10:05 2005 From: bytecolor at yahoo.com (bytecolor) Date: 15 Nov 2005 07:10:05 -0800 Subject: Is Python worth it?? In-Reply-To: References: <20051114225249.89689.qmail@web35901.mail.mud.yahoo.com> Message-ID: <1132067405.045760.275080@g14g2000cwa.googlegroups.com> http://www.norvig.com/21-days.html -- bytecolor From darkpaladin79 at gmail.com Sun Nov 6 11:07:02 2005 From: darkpaladin79 at gmail.com (Ivan Shevanski) Date: Sun, 6 Nov 2005 11:07:02 -0500 Subject: Clearing output screen Message-ID: <17d4ae400511060807j518eac01n9250dbc35d974ef2@mail.gmail.com> I know there is a way to do this, but google doesn't seem to want to find it =) There is a command to clear the output screen right? Thanks in advance, -Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Wed Nov 23 20:45:50 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 23 Nov 2005 20:45:50 -0500 Subject: Using Cron to run a python program References: <1132791791.548850.186420@o13g2000cwo.googlegroups.com> Message-ID: <20051124014517.M83381@uniqsys.com> On 23 Nov 2005 16:23:11 -0800, vagrantbrad wrote > I'm using python 2.4 running on Fedora Core 4. I have written a python > program called ipscan.py that checks the external ip address of my > cable internet connection, and on change, will update the dns records > at my dns provider, zoneedit. So basically, I've setup dynamic dns > using python. Once the ip compare and/or update is complete, I log the > results to a text file called update.log. When I run the program in > a bash shell with the command "python ipscan.py", the program runs fine > and the results are appended to update.log. When I run this program > as a cron job under the root user with the previously mentioned > command, the program runs without errors but does not append an > entry to the log. The permissions on the update.log file should not > be an issue since I'm running the cron job as root, but I've given > root write permissions just to be safe. What would cause the > logging to work at a command prompt but fail in cron? I'm not > getting any errors in the cron logs or /var/spool/mail/root. You're not giving us much detail about your script, so we can only guess. My guess is that your python script is either not invoked at all or it dies (raises an exception) before appending to the update.log. You should keep in mind that cron jobs don't run in a normal login shell, don't have the normal environment variables, and are not attached to a tty. Any of those factors can conceivably cause a script to fail under cron when it works fine from a shell. HTH, Carsten. From bkhl at stp.lingfil.uu.se Fri Nov 11 17:38:42 2005 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Fri, 11 Nov 2005 23:38:42 +0100 Subject: What do you use as symbols for Python? References: <4372f88a$0$31833$636a15ce@news.free.fr> Message-ID: <87acga24jx.fsf_-_@lucien.dreaming> Gary Herron writes: > Another similar approach that keeps those values together in a single > namespace is this (my favorite): > > class State: > OPENED, CLOSED, ERROR = range(3) > > Then you can refer to the values as > State.OPENED > State.CLOSED > State.ERROR Of course, with this solution you still get this problem: class State: OPENED, CLOSED, ERROR = range(3) class Spam: EGGS, HAM, TOAST = range(3) State.ERROR == Spam.TOAST => True Thus, the solutions using unique objects for each value seems cleaner, and closer to actual symbols, to me. I don't see why Python doesn't go all the way and add a real symbol type, though. I've seen way too many ugly string or integer based solutions. -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From rupole at hotmail.com Sat Nov 5 01:56:38 2005 From: rupole at hotmail.com (Roger Upole) Date: Sat, 5 Nov 2005 01:56:38 -0500 Subject: NTFS reparse points References: Message-ID: <1131174048_3253@spool6-east.superfeed.net> You should be able to use win32file.DeviceIoControl with winioctlcon.FSCTL_SET_REPARSE_POINT to do this. (winioctlcon was added in build 205) The hard part is going to be constructing the REPARSE_GUID_DATA_BUFFER struct to pass in as the buffer. hth Roger "Stanislaw Findeisen" wrote in message news:dkct0v$68j$1 at achot.icm.edu.pl... >I want to create a reparse point on NTFS (any). > > Here (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/reparse_points.asp) I read: "reparse points > are used to implement NTFS file system links". Here > (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/hard_links_and_junctions.asp) I read: "Soft links > are implemented through reparse points". > > However I can't see FILE_ATTRIBUTE_REPARSE_POINT turned on in any file / directory shortcuts I create. In fact the only > attribute set in shortcuts created using Windows Explorer is FILE_ATTRIBUTE_ARCHIVE. (I am using GetFileAttributes() to > examine this.) > > The questions are: > > (1) Why is that so? > (2) Does anybody have any idea (sample code?) on how to create a reparse point (the simpler, the better) using Python? > > I am using Windows 2000 Professional, Python 2.4 and Mark Hammond's Python for Windows Extensions build 204. > > Thank you. > > +-------------------------------------------------------+ > | When replying, please replace "my_initials" in the | > | From: address field with my initials - that is, "SF". | > +-------------------------------------------------------+ > > -- > http://www.nglogic.com > Enter through the narrow gate! (Mt 7:13-14) ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-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 saint.infidel at gmail.com Tue Nov 8 16:53:19 2005 From: saint.infidel at gmail.com (infidel) Date: 8 Nov 2005 13:53:19 -0800 Subject: cx_Oracle callproc output parameters Message-ID: <1131486799.092340.72120@g43g2000cwa.googlegroups.com> I have a stored procedure that has a single output parameter. Why do I have to pass it a string big enough to hold the value it is to receive? Why can't I pass an empty string or None? >>> import cx_Oracle as oracle >>> connection = oracle.connect('usr/pwd at tns') >>> cursor = connection.cursor() >>> network_name, = cursor.callproc('my_pkg.get_network_name_sp', ('',)) Traceback (most recent call last): File "", line 1, in ? DatabaseError: ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at "USR.MY_PKG", line 35 ORA-06512: at line 1 The following works fine, but I don't like having to do it: >>> network_name, = cursor.callproc('my_pkg.get_network_name_sp', (' ' * 32,)) Am I missing something obvious here? From steven.bethard at gmail.com Wed Nov 23 12:18:16 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 Nov 2005 10:18:16 -0700 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: <1132727299.252266.315990@o13g2000cwo.googlegroups.com> References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> <1132727299.252266.315990@o13g2000cwo.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Steven Bethard wrote: > >>rhettinger at gmail.com wrote: >> >>>>>ii. The other problem is easier to explain by example. >>>>>Let it=iter([1,2,3,4]). >>>>>What is the result of zip(*[it]*2)? >>>>>The current answer is: [(1,2),(3,4)], >>>>>but it is impossible to determine this from the docs, >>>>>which would allow [(1,3),(2,4)] instead (or indeed >>>>>other possibilities). >>>>>""" >>>>>IMO left->right is useful enough to warrant making it defined >>>>>behaviour >>>> >>>>And in fact, it is defined behavior for itertools.izip() [1]. >>>> >>>>I don't see why it's such a big deal to make it defined behavior for >>>>zip() too. >>> >>> >>>IIRC, this was discussednd rejected in an SF bug report. It should not >>>be a defined behavior for severals reasons: >> >>[snip arguments about how confusing zip(it, it) is] >> >>>Overall, I think anyone using zip(it,it) is living in a state of sin, >>>drawn to the tempations of one-liners and premature optimization. They >>>are forsaking obvious code in favor of screwy special cases. The >>>behavior has been left undefined for a reason. >> >>Then why document itertools.izip() as it is? The documentation there is >>explicit enough to know that izip(it, it) will work as intended. Should >>we make the documentation there less explicit to discourage people from >>using the izip(it, it) idiom? > [snip] > > But technically speaking, you are still referring to the implementation > detail of izip(), not the functionality of izip(). > > I do now agree with another poster that the documentation of both zip > and izip should state clear that the order of picking from which > iterable is undefined or can be changed from implementation to > implementation, to avoid this kind of temptation. > Actually, it's part of the specificiation. Read the itertools documentation[1]: """ izip(*iterables) Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. Equivalent to: def izip(*iterables): iterables = map(iter, iterables) while iterables: result = [i.next() for i in iterables] yield tuple(result) """ So technically, since itertools.izip() is "equivalent to" the Python code above, it is part of the specification, not the implementation. But I certainly understand Raymond's point -- the code in the itertools documentation there serves a number of purposes other than just documenting the behavior. [1]http://docs.python.org/lib/itertools-functions.html#l2h-1392 STeVe From uval at rz.uni-karlsruhe.de Mon Nov 14 13:43:14 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Mon, 14 Nov 2005 19:43:14 +0100 Subject: mp3 wav editing in python In-Reply-To: <1131987258.719059.15890@g47g2000cwa.googlegroups.com> References: <1131987258.719059.15890@g47g2000cwa.googlegroups.com> Message-ID: yb wrote: > Hi, > > Is there a python based tool to cut mp3 and wav file at a start and end > time? I'm looking for a python script that can output a new wav or mp3 > file based on star and endpoint. > > Thank you > there is a wave module >>> import wave >>> dir(wave) ['Chunk', 'Error', 'WAVE_FORMAT_PCM', 'Wave_read', 'Wave_write', '__all__', '__builtin__', '__builtins__', '__doc__', '__file__', '__name__', '_array_fmts', 'big_endian', 'open', 'openfp', 'struct'] >>> wav= wave.open("/musik/musik/wav/Co - 1.wav") >>> wav >>> dir(wav) ['__del__', '__doc__', '__init__', '__module__', '_compname', '_comptype', '_convert', '_data_chunk', '_data_seek_needed', '_file', '_fmt_chunk_read', '_framerate', '_framesize', '_i_opened_the_file', '_nchannels', '_nframes', '_read_fmt_chunk', '_sampwidth', '_soundpos', 'close', 'getcompname', 'getcomptype', 'getfp', 'getframerate', 'getmark', 'getmarkers', 'getnchannels', 'getnframes', 'getparams', 'getsampwidth', 'initfp', 'readframes', 'rewind', 'setpos', 'tell'] >>> wav.getnchannels() 2 >>> and so on, this is what google gave me http://scipy.mit.edu/tutorials/wave.pdf I did some wave ploting with matplotlib module, so I think it's feasible to cut and write wave files too as for mp3, I don't know of any modules I think mainly because of license issue you could decode mp3 to wav and process whatever you want to process but to encode them back into mp3 is a problem maybe you could use lame or bladeenc as a command line tool or use ogg instead http://www.andrewchatham.com/pyogg/ there are de/encoders freely available this may also be interessting to you http://pymedia.org/ hth, Daniel From kasperd at daimi.au.dk Wed Nov 9 06:24:55 2005 From: kasperd at daimi.au.dk (Kasper Dupont) Date: Wed, 09 Nov 2005 12:24:55 +0100 Subject: page faults when spawning subprocesses References: <1131526746.894342.182260@z14g2000cwz.googlegroups.com> Message-ID: <4371DC87.2C4B79E9@daimi.au.dk> Dave Kirby wrote: > > 5) WTF can I do about it? Maybe using vfork rather than fork would help. But I'm not sure that will work as intended when there are multiple threads, in fact I'm not sure fork will work either. You could have fork racing against another thread being in a critical region thus duplicating the memory map at some point where some data structures are in an inconsistent state and apparently locked by some thread existing in the parent. A possible solution would be to use fork to create two processes before creating any threads. Have the communicate over pipes or sockets when new processes are to be created. Then one process can create all the threads you need, and the other can fork off children. Even in that case vfork may come in handy. If you dislike the semantics of vfork, but still want the parent to block until the child has called execve, then you can do so manually using a pipe. Create the pipe before calling fork, in parent process you close write end and try to read from the pipe, in child process you close read end and mark write end close on exec. When exec succeeds, the pipe is closed and parent gets EOF. (I have tried some of this in C, but I must admit, I don't know if it can be done in Python as well.) -- Kasper Dupont Note to self: Don't try to allocate 256000 pages with GFP_KERNEL on x86. From peter at engcorp.com Sat Nov 26 19:10:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Nov 2005 19:10:47 -0500 Subject: Comparison problem In-Reply-To: References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: Tom Anderson wrote: > On Sat, 26 Nov 2005, Chris wrote: > >> if item[0:1]=="-": > > item[0:1] seems a rather baroque way of writing item[0]! I'd actually > suggest writing this line like this: Actually, it's not so much baroque as it is safe... item[0] will fail if the string is empty, while item[0:1] will return '' in that case. Of course, as you point out, .startswith() is the better approach anyway. -Peter From howardrh at westerncom.net Tue Nov 29 19:43:51 2005 From: howardrh at westerncom.net (hrh1818) Date: 29 Nov 2005 16:43:51 -0800 Subject: wxPython : getting started References: <438c8dc4$1@epflnews.epfl.ch> Message-ID: <1133311431.147087.242380@z14g2000cwz.googlegroups.com> One possible source of help is the book "Python Programming on Win 32". It has a 20 page introducrtion on using wxPython. Howard David Sulc wrote: > Hi ! > > I've looked all over (internet, books, etc.) and I haven't found a very > good ressource to get started with wxPython (yes, I've been through > their tutorial). > > What I would basically like to do for starters is to be able to define > the main panel being displayed. For example : > 1. wxFrame contains a wxPanel (call it mainPanel). > 2. mainPanel contains another panel (childPanelA) > 3. another panel has been defined (childPanelB) but is not displayed > (the user can only see childPanelA inside mainPanel) > 4. by clicking on a menu entry (for example), the displayed panel is now > childPanelA (which is inside mainPanel) > > So how do I do this ? I realize it's a very basic question, but it's > been driving me mad... > > Also, is there any good open source wxPython program that I could study ? > > Thanks for any help... From uval at rz.uni-karlsruhe.de Mon Nov 14 17:36:45 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Mon, 14 Nov 2005 23:36:45 +0100 Subject: Searching date and and time from a text file In-Reply-To: <1132005880.158423.45690@g43g2000cwa.googlegroups.com> References: <1132005880.158423.45690@g43g2000cwa.googlegroups.com> Message-ID: masudtarek at gmail.com wrote: > Hi, I am new in Python programming. Can anybody give me any idea about > how to detect more than one date and time (like 11/11/2005 , > 10-12-2006, 12:30 etc) from a text file and keep them in a list. well first we read the file src = file("/your/file").read() then we need some regular expressions to find the date and time import re pattern = { "time" : re.compile(r"\b\d\d:\d\d\b"), "date1" : re.compile(r"\b\d\d-\d\d-\d\d\d\d\b"), "date2" : re.compile(r"\b\d\d/\d\d/\d\d\d\d\b") } times = pattern["time"].findall(src) dates1 = pattern["date1"].findall(src) dates2 = pattern["date2"].findall(src) note this is not very good solution though one should check all the items to be sure hours are between 0 and 23 and minutes in range 0 .. 59 for time in times: t = time.split(":") assert 0 <= int(t[0]) <= 23 assert 0 <= int(t[1]) <= 59 hth, Daniel ps: all code untested From svenn.are at bjerkem.de Tue Nov 1 14:32:08 2005 From: svenn.are at bjerkem.de (svenn.are at bjerkem.de) Date: 1 Nov 2005 11:32:08 -0800 Subject: Python's website does a great disservice to the language In-Reply-To: References: Message-ID: <1130873528.812783.75600@g43g2000cwa.googlegroups.com> So the first thing you do when you go to a web page is to google if they are going to redesign it? -- Svenn From http Sat Nov 5 21:14:03 2005 From: http (Paul Rubin) Date: 05 Nov 2005 18:14:03 -0800 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <436c0527.146082265@news.oz.net> <864q6rkfie.fsf@bhuda.mired.org> <436d0b61.213212052@news.oz.net> <7xirv639kb.fsf@ruckus.brouhaha.com> Message-ID: <7x7jbmfrpw.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > It never occurred to me that immutable objects could implement __iadd__. > > If they can, I'm puzzled as to why. > I'm surprised that it never occurred to you that people might > want to do something like x = 1; x += 1 in Python, But I wouldn't expect that to mean that ints implement __iadd__. I'd expect the x+=1 to just use __add__. I haven't checked the spec though. > I can respect the position of somebody who says that only methods > should be inherited -- somebody, I think it was you, suggested that there > is at least one existing OO language that doesn't allow inheritance for > attributes, but never responded to my asking what language it was. I was thinking of Flavors. You use a special function (send) to do method calls. But people generally felt that was kludgy and CLOS eliminated it. I'm not sure what happens in Smalltalk. > instance.attribute sometimes reading from the class attribute is a feature > of inheritance; instance.attribute always writing to the instance is a > feature of OOP; instance.attribute sometimes writing to the instance and > sometimes writing to the class would be, in my opinion, not just a wart > but a full-blown misfeature. But that is what you're advocating: x.y+=1 writes to the instance or the class depending on whether x.y is mutable or not. Say you have an immutable class with a mutable subclass or vice versa. You'd like to be able to replace a class instance with a subclass instance and not have the behavior change (Liskov substitution principle), etc. From fredrik at pythonware.com Fri Nov 25 02:36:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Nov 2005 08:36:42 +0100 Subject: The imp module and cyclic imports References: <1132864414.261663.306290@g43g2000cwa.googlegroups.com> Message-ID: Matthias Kramm wrote: > I'm having a little bit of trouble using the "imp" module to > dynamically import modules. It seems that somehow cyclic > references of modules don't work. the problem you're seeing appears also if you use "import web.one" or "from web import one" or "__import__('web.one')". > I'm unable to get the following to work: > > I've got the following files: > > web/__init__.py > web/one.py > web/two.py > testimport.py > > >From which web/one.py contains the line: > > from web import two > > and web/two.py contains the line: > > from web import one I think, but I'm not 100% sure, that the problem you're seeing is that Python hasn't finished importing the "web.one" module when you're trying to import it again. - testimport wants to import web.one - python imports the web module - python finishes importing the web module - python imports the web.one module - web.one wants to import web.two - python imports the web.two module - web.two wants to import web.one - python notices that web.one is already being imported, and leaves it to the original import to finish the task if you replace the "from web import" statements with plain imports, everything will work as expected. just change from web import one to import one and do the same for the other module. hope this helps! From nir1408 at gmail.com Sun Nov 13 02:26:47 2005 From: nir1408 at gmail.com (nir1408 at gmail.com) Date: 12 Nov 2005 23:26:47 -0800 Subject: Winpdb question In-Reply-To: References: Message-ID: <1131866807.760599.302240@g49g2000cwa.googlegroups.com> Hello Bryan, You can restrict the number of variables displayed in the globals name-space viewer with the filter button located second from the right on the tool bar. This will filter out modules, classes, and function names from the list. Nir From steve at REMOVETHIScyber.com.au Sat Nov 5 19:11:48 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 06 Nov 2005 11:11:48 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <436c0527.146082265@news.oz.net> <864q6rkfie.fsf@bhuda.mired.org> <436d0b61.213212052@news.oz.net> Message-ID: On Sat, 05 Nov 2005 21:26:22 +0000, Bengt Richter wrote: > BTW, semantically does/should not __iadd__ really implement a _statement_ and therefore > have no business returning any expression value to bind anywhere? We get to practicality versus purity here. Consider x += y for some object type x. If x is a mutable object, then __iadd__ could be a statement, because it can/should/must modify x in place. That is the pure solution. But do you want x += y to work for immutable objects as well? Then __iadd__ cannot be a statement, because x can't be modified in place. Our pure "add in place" solution fails in practice, unless we needlessly restrict what can use it, or have the same syntactical expression (x += y) bind to two different methods (__iadd__ statement, and __riadd__ function, r for return). Either pure solution is yucky. (That's a technical term for "it sucks".) So for practical reasons, __iadd__ can't be a statement, it needs to return an object which gets bound to x. Fortunately, that behaviour works for mutables as well, because __iadd__ simply returns self, which gets re-bound to x. While I am enjoying the hoops people are jumping through to modify the language so that b.a += 2 assigns b.a in the same scope as it was accessed, I'm still rather perplexed as to why you would want that behaviour. It seems to me like spending many hours building a wonderfully polished, ornate, exquisite device for building hiking boots for mountain goats. -- Steven. From utabintarbo at gmail.com Thu Nov 3 12:40:05 2005 From: utabintarbo at gmail.com (utabintarbo) Date: 3 Nov 2005 09:40:05 -0800 Subject: How can I package a python script and modules into a single script? In-Reply-To: <3bmd220k.fsf@python.net> References: <1131030933.425241.142800@o13g2000cwo.googlegroups.com> <3bmd220k.fsf@python.net> Message-ID: <1131039605.019088.31540@o13g2000cwo.googlegroups.com> I believe you are thinking of "freeze", which is part of the normal python distro. There is also cx_Freeze ( http://starship.python.net/crew/atuining/cx_Freeze/ ).... Bob From grante at visi.com Thu Nov 3 10:51:30 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 03 Nov 2005 15:51:30 -0000 Subject: reading internet data to generate random numbers. References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> <11mj21gr6rjgc65@corp.supernews.com> <86ll06jr79.fsf@bhuda.mired.org> <4369B2CF.70201@REMOVEMEcyber.com.au> Message-ID: <11mkcg2l9d89qff@corp.supernews.com> On 2005-11-03, Steven D'Aprano wrote: >>>I think that the timing of certain network events is one of the >>>Linux kernel's entropy sources. >> >> BSD as well. The key word is "one". While network events don't make a >> good source of random data, proplery combining such sources can create >> good random data. > > > > Depends on what you mean by "random". In particular, > the randomness of network events does not follow a > uniform distribution, but then not many things do. One presumes there is a way to "uniformize" the events, but I'm just guessings. [...] > I have no idea what distribution data from the Internet would > have, I would imagine it is *extremely* non-uniform and *very* > biased towards certain values (lots of "<" and ">" I bet, and > relatively few "\x03"). I've never heard of anybody using the data as source of entropy. All the entropy gathering I've read about used the timing of network events, not the user-data associated with those events. -- Grant Edwards grante Yow! ... this must be what at it's like to be a COLLEGE visi.com GRADUATE!! From bokr at oz.net Wed Nov 9 00:22:35 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 09 Nov 2005 05:22:35 GMT Subject: How to convert a number to hex number? References: <1131442115.025438.326670@g49g2000cwa.googlegroups.com> <1131464101.546746.107110@g47g2000cwa.googlegroups.com> <7xmzkfrum1.fsf@ruckus.brouhaha.com> <43712759.482516031@news.oz.net> <9Cbcf.186716$xl6.130920@tornado.tampabay.rr.com> Message-ID: <43718108.4422919@news.oz.net> On Wed, 09 Nov 2005 00:42:45 GMT, Ron Adam wrote: > > >Bengt Richter wrote: >> On 08 Nov 2005 08:07:34 -0800, Paul Rubin wrote: >> >> >>>"dcrespo" writes: >>> >>>>>>>hex(255)[2:] >>>> >>>>'ff' >>> >>>'%x'%255 is preferable since the format of hex() output can vary. Try hex(33**33). >> >> >> Not to mention (#@%*!-pletive deleted ;-) >> >> >>> hex(-255)[2:] >> 'xff' >> >>> hex(-255) >> '-0xff' >> >>> hex(-255&0xff) >> '0x1' >> >> Regards, >> Bengt Richter > >I just happen to have been playing around with converting bases the last >couple of days. (idonowhy) ;-) > It seems to be one of those inevitable things, enjoy it ;-) But you still use '-' + yourconversion(abs(x)) to deal with a negative number. That's what I was #@%*!-ing about. You can't see the 'bits' in the way one was used to with the old int values. My answer was a base-complement representation, of which base-16 is a particular case. See http://groups.google.com/group/comp.lang.python/msg/d8324946fcdff8f8 and the code in the second reference from there: http://groups.google.co.uk/group/comp.lang.python/msg/359927a23eb15b3e I only put in characters for up to base 36, but it's a function parameter you can pass, so your digits ought to work if passed. The idea of base-complement is that the first digit is the zero digit for positive numbers and the digit for base-1 for negative numbers. This can be arbitrarily repeated to the left as fill without changing the numeric value. so for base 10 one is 01 and -1 is 99, and for hex that is 01 and FF. For base 2, 01 and 11. Etc. To make a general literal you need a prefix to the data that tells you the base value to use in interpreting the data part. A la 0x01, I proposed 0b. So +1 -1 is 0b2.01 and 0b2.11 or octal 0b8.01 and 0b8.77 or decimal 0b10.01 and 0b10.99 and hex 0b16.01 and 0b16.ff Algorithmically, minus 1 can be represented with a single data digit, but that's a style issue. >Oh yeah, I was thinking of using base62 to generate non-repeating id >strings and wanted to try it out. Hm, what were you going to use those for? [...too tired to revisit the problem, just wanted to comment on the sign/magnitude representation, hope I didn't typo too badly above ;-) ...] Regards, Bengt Richter From peter.maas at somewhere.com Thu Nov 17 17:50:49 2005 From: peter.maas at somewhere.com (Peter Maas) Date: Thu, 17 Nov 2005 23:50:49 +0100 Subject: Zope vs Php In-Reply-To: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> Message-ID: Steve schrieb: >>From what I can tell you can't just do > <% > #python code > %> > some title > > this is what we would like to do with session support and things that > php provides? Google for "python web frame works". Most have session support, and some offer Python Code embedded in HTML (e.g. Webware, mod_python and Spyce). I never realized what's so great about this because <% #python code %> some title and print output(python-code) + " some title". are equivalent. Another approach is using Templates. Most web frameworks have Templates. My favorite is Cheetah. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------ From bonono at gmail.com Tue Nov 22 21:06:24 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 18:06:24 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: <1132711584.209266.102530@g47g2000cwa.googlegroups.com> rhettinger at gmail.com wrote: > IIRC, this was discussednd rejected in an SF bug report. It should not > be a defined behavior for severals reasons: > > * It is not communicative to anyone reading the code that zip(it, it) > is creating a sequence of the form (it0, it1), (it2, it3), . . . IOW, > it conflicts with Python's style of plain-speaking. > * It is too clever by far -- much more of a trick than a technique. > * It is bug-prone -- zip(x,x) behaves differently when x is a sequence > and when x is an iterator (because of restartability). Don't leave > landmines for your code maintainers. > * The design spirit of zip() and related functions is from the world of > functional programming where a key virtue is avoidance of side-effects. > Writing zip(it, it) is exploiting a side-effect of the implementation > and its interaction with iterator inputs. The real spirit of zip() is > having multiple sequences translated to grouped sequences out -- the > order of application (and order of retrieving inputs) should be > irrelevant. > * Currently, a full understanding of zip() can be had by remembering > that it maps zip(a, b) to (a0, b0), (a1, b1), . . . . That is simple > to learn and easily remembered. In contrast, it introduces unnecessary > complexity to tighten the definition to also include the order of > application to cover the special case of zip being used for windowing. > IOW, making this a defined behavior results in making the language > harder to learn and remember. > > Overall, I think anyone using zip(it,it) is living in a state of sin, > drawn to the tempations of one-liners and premature optimization. They > are forsaking obvious code in favor of screwy special cases. The > behavior has been left undefined for a reason. > While I agree that zip() should be left as it is(the definition as it is only supposed to do a lock step of N iterables), I don't think zip(it,it) is purely for the sake of one liner. It does convey the intend clearer to me than for loop(well that IMO is the reasons of many one liner). It tells me exactly what I want: make a "window/mask" of N slots and put it on top of a list and fold. The result are strips of the list each with element N. zip(it,it,it,it) is a mask of 4 slot zip(it,it,it,it,it) is a mask of 5 slot Though in this case it is still not 100% correct as if my list has odd number of elements, zip(it,it) would drop the last one, but that was not defined in the original question. From alanmk at hotmail.com Mon Nov 14 16:54:19 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 14 Nov 2005 21:54:19 +0000 Subject: Making a persistent HTTP connection In-Reply-To: <3tsdvaFugk4lU2@uni-berlin.de> References: <4378e5bb$0$2103$edfadb0f@dtext02.news.tele.dk> <3tsdvaFugk4lU2@uni-berlin.de> Message-ID: [David Rasmussen] >> I use urllib2 to do some simple HTTP communication with a web server. >> In one "session", I do maybe 10-15 requests. It seems that urllib2 >> opens op a connection every time I do a request. Can I somehow make it >> use _one_ persistent connection where I can do multiple GET->"receive >> data" passes before the connection is closed? [Diez B. Roggisch] > Are you sure HTTP supports that? Yes, HTTP 1.1 definitely supports multiple requests on the same connection. http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.1 Some HTTP 1.0 clients supported persistent connections through the use of the non-standard "keep-alive" header. > And even if it works - what is the problem with connections being created? The URL above describes the benefits of persistent connections. The primary problem of the old style of one-request-per-connection is the creation of more sockets than are necessary. To the OP: neither urllib nor urllib2 implements persistent connections, but httplib does. See the httplib documentation page for an example. http://www.python.org/doc/2.4.2/lib/httplib-examples.html However, even httplib is "synchronous", in that it cannot pipeline requests: the response to the first request must be competely read before a second request can be issued. HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From Serge.Orlov at gmail.com Sun Nov 13 15:58:04 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 Nov 2005 12:58:04 -0800 Subject: Confusion about __call__ and attribute lookup References: <43734796$1_1@newspeer2.tds.net> <43736a63$1_1@newspeer2.tds.net> Message-ID: <1131915483.987505.105400@g49g2000cwa.googlegroups.com> Kent Johnson wrote: > Leif K-Brooks wrote: > > New-style classes look up special methods on the class, not on the instance: > > For my future reference, is this documented somewhere in the standard docs? > Looks like it's the most detailed explanation on the net: http://mail.python.org/pipermail/python-dev/2003-May/035732.html From vinjvinj at gmail.com Tue Nov 8 10:31:34 2005 From: vinjvinj at gmail.com (vinjvinj) Date: 8 Nov 2005 07:31:34 -0800 Subject: Using Which Version of Linux In-Reply-To: References: Message-ID: <1131463894.214456.96070@g44g2000cwa.googlegroups.com> I would strongly recomend ubuntu server 5.1. I installed it on about 15 servers. Its secure out of the box. no ports are open. It comes with python 2.4.1 and a ton of python modules. The install requires only 1 cd and uses only 400 mb. From deets at nospam.web.de Sat Nov 5 13:01:42 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 05 Nov 2005 19:01:42 +0100 Subject: Python gui In-Reply-To: References: Message-ID: <3t4ac7Fr8nn7U1@uni-berlin.de> Philippe C. Martin wrote: > Hi, > > Is wxWidget now part of python ? or will it be ? 1) No. 2) I guess no. Because it has pretty heavy dependencies (wx, GTK/other toolkit) Tkinter is what comes ou of the box - and thats it. Regards, Diez From samrobertsmith at gmail.com Fri Nov 11 18:47:28 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 11 Nov 2005 15:47:28 -0800 Subject: x, y coordinates in Tkinter canvas Message-ID: <1d987df30511111547v3f32646by49ad408ad0f45b4c@mail.gmail.com> got confused by x, y coordinates in Tkinter canvas. from left to right, does X increase? from top to bottom, does y increase? From p at ulmcnett.com Wed Nov 30 12:51:42 2005 From: p at ulmcnett.com (Paul McNett) Date: Wed, 30 Nov 2005 09:51:42 -0800 Subject: an intriguing wifi http server mystery...please help In-Reply-To: <1133372232.737182.98410@g43g2000cwa.googlegroups.com> References: <1133324893.968023.79050@z14g2000cwz.googlegroups.com> <438D3186.2070800@ulmcnett.com> <1133372232.737182.98410@g43g2000cwa.googlegroups.com> Message-ID: <438DE6AE.3090405@ulmcnett.com> jojoba at gmail.com wrote: > Please excuse any ignorance here. > I would love to show you what you are asking for, but I am not sure > what you are asking for (newbie here). > > All these connections (i.e. client-server connections) are within my > local area network. > > I have a simple linksys 802.11b router. > My server is set to say, "192.168.1.100", port 9999, > and my client is set to say, "192.168.1.101" > > I load up the server, then go to the client computer webbrowser and > enter "http://192.168.1.100:9999" If you are on Windows, please open a command window (Start|Run and then type 'cmd') and type: route print On Linux or Mac, the command would simply be: route Do this on both computers, and post the output here. If you are using ip addresses only in your URL's the problem isn't with DNS or name lookup so let's eliminate a routing problem next. -- Paul McNett http://paulmcnett.com http://dabodev.com From nomail at nomail.com Tue Nov 29 21:29:30 2005 From: nomail at nomail.com (Nx) Date: Wed, 30 Nov 2005 10:29:30 +0800 Subject: run runs away In-Reply-To: References: <438c57fe@127.0.0.1> Message-ID: Thanks for your reply ! I now realize , that the run() used in this code stems from a def , which actually wraps os.spawnv(os.P_WAIT, ...) in a way that eliminates waiting.... I like this newsgroup as there are always people who are less stumped than oneself. Nx From bobueland at yahoo.com Thu Nov 17 05:03:08 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 17 Nov 2005 02:03:08 -0800 Subject: IDLE question References: <1132217965.434209.122200@f14g2000cwb.googlegroups.com> <3u3186FvbckvU1@individual.net> Message-ID: <1132221788.888868.8370@f14g2000cwb.googlegroups.com> Okey I tried what you recommended My C:\Python24\sitecustomize.py looks like this: # sitecustomize.py import os from btools import * When I enter C:\Python24>C:\Python24\pythonw.exe C:\Python24\Lib\idlelib\idle.py -r C:\Python24\sitecustomize.py in commad propmt IDLE starts up and automatically imports 'os' and all names from my btools folder. So far so good. But when I hit Ctrl+F6 and restart Python Shell both 'os' and names from btools are gone! When I work with IDLE I typically start a new file (File/New Window) and when I have written the code I hit (Ctrl+S) to Save and F5 to run. This restarts Python Shell and my names from btools are gone. It's no solution if I'm forced to go back to command prompt and enter the long sequance again. Bob From callum at gmail.com Wed Nov 23 22:05:52 2005 From: callum at gmail.com (Callum Prentice) Date: 23 Nov 2005 19:05:52 -0800 Subject: Simple photo collage using Python and PIL In-Reply-To: References: <1132704610.945593.16100@g47g2000cwa.googlegroups.com> Message-ID: <1132801552.684895.104980@g44g2000cwa.googlegroups.com> Thanks very much Fredrik - just what I was looking for - that gives me a good place to start from. Much appreciated. Cal. From fuzzyman at gmail.com Thu Nov 24 05:35:14 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Nov 2005 02:35:14 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> Message-ID: <1132828514.489889.7110@g44g2000cwa.googlegroups.com> Carsten Haese wrote: > On Wed, 23 Nov 2005 23:39:22 +0100, Christoph Zwerschke wrote > > Carsten Haese schrieb: > > > > > Thus quoth the Zen of Python: > > > "Explicit is better than implicit." > > > "In the face of ambiguity, refuse the temptation to guess." > > > > > > With those in mind, since an odict behaves mostly like a dictionary, [] > > > should always refer to keys. An odict implementation that wants to allow > > > access by numeric index should provide explicitly named methods for that > > > purpose. > > > > Exactly. But I don't think in this case such methods would be > > needed. You easily get the i-th value in the ordered dict as > > d.values()[i]. > > > > -- Chris > > True enough, but unless the odict has its list of values on hand, you're > asking the odict to build a list of all its values just so that you can get > the i'th element. Having a method that does the equivalent of d[d.sequence[i]] > would be cleaner and more efficient. > I'm going to add some of the sequence methods. I'm *not* going to allow indexing, but I will allow slicing. You can also do d[d.keys()[i]] This provides two ways of fetching values by index, so I don't want to add another. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -Carsten From fuzzyman at gmail.com Wed Nov 23 03:32:33 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Nov 2005 00:32:33 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <11o6hr7s4886720@corp.supernews.com> References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> <1132652504.327803.154790@g49g2000cwa.googlegroups.com> <9smdnVdh0oNCkh7eRVn-uw@speakeasy.net> <11o6hr7s4886720@corp.supernews.com> Message-ID: <1132734753.411477.7340@f14g2000cwb.googlegroups.com> While we're on the subject, it would be useful to be able to paste in a changelog as well as a description. Currently when updating versions you have to include the changelog in the description - or not at all... All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From arkanes at gmail.com Fri Nov 18 19:23:11 2005 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Nov 2005 18:23:11 -0600 Subject: Confused about namespaces In-Reply-To: <1132358984.915609.306380@g44g2000cwa.googlegroups.com> References: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> <1132356583.703129.241070@g47g2000cwa.googlegroups.com> <1132358984.915609.306380@g44g2000cwa.googlegroups.com> Message-ID: <4866bea60511181623u7ab0970am7a8ab8574315c491@mail.gmail.com> On 18 Nov 2005 16:09:44 -0800, KvS wrote: > Hmm. But actually I was doing this import from GUIclasses with exactly > this in mind, namely that it would make wx also available at top level. There's no reason not to just "import wx" if you want that. > I (in my naive understanding) see this as "natural" and actually > desirable, how could this cause confusing bugs? Do you mean multiple > "from ... import *"'s 'on top of each other' would cause foo1.foo2.attr > and foo1.attr both would become just attr and therefore ambiguous at > top level? the second import will overwrite the first, making the first inaccessible > > If you import foo in two different modules, does the interpreter then > create one instance of foo and create a reference in both modules to > the same foo rather than creating two different instances of foo? > No. It creates the foos within each module, but which foo you have access to in the importing module is determined by the order of import. > -- > http://mail.python.org/mailman/listinfo/python-list > From kent37 at tds.net Sun Nov 13 19:13:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Nov 2005 19:13:27 -0500 Subject: Python Book In-Reply-To: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> References: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> Message-ID: <4377D6A7.4040807@tds.net> David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? I like Learning Python. Python in a Nutshell is good if you want something brief. Kent From kbk at shore.net Sat Nov 19 01:34:23 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 19 Nov 2005 01:34:23 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200511190634.jAJ6YNMh017166@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 379 open (+14) / 2968 closed ( +7) / 3347 total (+21) Bugs : 910 open ( +6) / 5384 closed (+17) / 6294 total (+23) RFE : 200 open ( +0) / 191 closed ( +2) / 391 total ( +2) New / Reopened Patches ______________________ PythonD DJGPP-specific patch set for porting to DOS. (2005-11-08) http://python.org/sf/1351020 opened by Ben Decker PythonD new file: python2.4/plat-ms-dos5/djstat.py (2005-11-08) http://python.org/sf/1351036 opened by Ben Decker askyesnocancel helper for tkMessageBox (2005-11-08) http://python.org/sf/1351744 opened by Fredrik Lundh fix for resource leak in _subprocess (2005-11-09) CLOSED http://python.org/sf/1351997 opened by Fredrik Lundh [PATCH] Bug #1351707 (2005-11-10) http://python.org/sf/1352711 opened by Thomas Lee Small upgrades to platform.platform() (2005-11-10) http://python.org/sf/1352731 opened by daishi harada a faster Modulefinder (2005-11-11) http://python.org/sf/1353872 opened by Thomas Heller support whence argument for GzipFile.seek (bug #1316069) (2005-11-12) http://python.org/sf/1355023 opened by Fredrik Lundh PEP 341 - Unification of try/except and try/finally (2005-11-14) http://python.org/sf/1355913 opened by Thomas Lee Delete Python-ast.[ch] during "make depclean" (#1355883) (2005-11-14) CLOSED http://python.org/sf/1355940 opened by Thomas Lee Python-ast.h & Python-ast.c generated twice (#1355883) (2005-11-14) http://python.org/sf/1355971 opened by Thomas Lee Sort nodes when writing to file (2005-11-14) CLOSED http://python.org/sf/1356571 opened by Johan Str?m potential crash and free memory read (2005-11-15) http://python.org/sf/1357836 opened by Neal Norwitz ftplib dir() problem with certain servers (2005-11-17) http://python.org/sf/1359217 opened by Stuart D. Gathman Iterating closed StringIO.StringIO (2005-11-18) http://python.org/sf/1359365 opened by Walter D?rwald Speed charmap encoder (2005-11-18) http://python.org/sf/1359618 opened by Martin v. L?wis Patch for (Doc) #1357604 (2005-11-18) http://python.org/sf/1359879 opened by Peter van Kampen Add XML-RPC Fault Interoperability to XMLRPC libraries (2005-11-18) http://python.org/sf/1360243 opened by Joshua Ginsberg correct display of pathnames in SimpleHTTPServer (2005-11-18) http://python.org/sf/1360443 opened by Ori Avtalion Auto Complete module for IDLE (2005-11-19) http://python.org/sf/1361016 opened by Jerry Patches Closed ______________ Redundant connect() call in logging.handlers.SysLogHandler (2005-11-07) http://python.org/sf/1350658 closed by vsajip incomplete support for AF_PACKET in socketmodule.c (2004-11-19) http://python.org/sf/1069624 closed by gustavo fix for resource leak in _subprocess (2005-11-09) http://python.org/sf/1351997 closed by effbot Info Associated with Merge to AST (2005-01-07) http://python.org/sf/1097671 closed by kbk Delete Python-ast.[ch] during "make depclean" (#1355883) (2005-11-13) http://python.org/sf/1355940 closed by montanaro Sort nodes when writing to file (2005-11-14) http://python.org/sf/1356571 closed by effbot CodeContext - an extension to show you where you are (2004-04-16) http://python.org/sf/936169 closed by kbk New / Reopened Bugs ___________________ win32serviceutil bug (2005-11-08) CLOSED http://python.org/sf/1351545 opened by Tim Graber Switch to make pprint.pprint display ints and longs in hex (2005-11-08) http://python.org/sf/1351692 opened by Mark Hirota zipimport produces incomplete IOError instances (2005-11-08) http://python.org/sf/1351707 opened by Fred L. Drake, Jr. CVS webbrowser.py (1.40) bugs (2005-10-26) CLOSED http://python.org/sf/1338995 reopened by montanaro SVN webbrowser.py fix 41419 didn't (2005-11-09) http://python.org/sf/1352621 opened by Greg Couch poplib.POP3_SSL() class incompatible with socket.timeout (2005-11-10) http://python.org/sf/1353269 opened by Charles Http redirection error in urllib2.py (2005-11-10) http://python.org/sf/1353433 opened by Thomas Dehn Python drops core when stdin is bogus (2005-11-10) http://python.org/sf/1353504 opened by Skip Montanaro Error in documentation for os.walk (2005-11-11) CLOSED http://python.org/sf/1353793 opened by Martin Geisler logging: Default handlers broken (2005-11-11) CLOSED http://python.org/sf/1354052 opened by Jonathan S. Joseph Interactive help fails with Windows Installer (2005-11-11) CLOSED http://python.org/sf/1354265 opened by Colin J. Williams shutil.move() does not preserve ownership (2005-11-13) http://python.org/sf/1355826 opened by lightweight Incorrect Decimal-float behavior for + (2005-11-13) http://python.org/sf/1355842 opened by Connelly make depend/clean issues w/ ast (2005-11-13) http://python.org/sf/1355883 opened by Skip Montanaro Division Error (2005-11-13) CLOSED http://python.org/sf/1355903 opened by Azimuth Ctrl+C for copy does not work when caps-lock is on (2005-11-14) http://python.org/sf/1356720 opened by Lenny Domnitser Tix.py class HList missing info_bbox (2005-11-14) http://python.org/sf/1356969 opened by Ron Provost urllib/urllib2 cannot ftp files which are not listable. (2005-11-15) http://python.org/sf/1357260 opened by Bugs Fly os.path.makedirs DOES handle UNC paths (2005-11-15) http://python.org/sf/1357604 opened by j vickroy suprocess cannot handle shell arguments (2005-11-16) http://python.org/sf/1357915 opened by Pierre Ossman Incorrect handling of unicode "strings" in asynchat.py (2005-11-16) CLOSED http://python.org/sf/1358186 opened by Holger Lehmann subprocess.py fails on Windows when there is no console (2005-11-16) http://python.org/sf/1358527 opened by Martin Blais Incorrect documentation of raw unidaq string literals (2005-11-17) http://python.org/sf/1359053 opened by Michael Haggerty Prefer configured browser over Mozilla and friends (2005-11-17) http://python.org/sf/1359150 opened by Ville Skytt? bdist_rpm still can't handle dashes in versions (2005-11-18) http://python.org/sf/1360200 opened by jared jennings telnetlib expect() and read_until() do not time out properly (2005-11-18) http://python.org/sf/1360221 opened by Duncan Grisby Bugs Closed ___________ "setdlopenflags" leads to crash upon "import" (2005-11-07) http://python.org/sf/1350188 closed by nnorwitz pydoc seems to run some scripts! (2005-11-04) http://python.org/sf/1348477 closed by nnorwitz cgitb.py report wrong line number (2005-04-06) http://python.org/sf/1178148 closed by ping win32serviceutil bug (2005-11-08) http://python.org/sf/1351545 closed by nnorwitz CVS webbrowser.py (1.40) bugs (2005-10-27) http://python.org/sf/1338995 closed by birkenfeld __getslice__ taking priority over __getitem__ (2005-10-17) http://python.org/sf/1328278 closed by birkenfeld _subprocess.c calls PyInt_AsLong without error checking (2005-11-03) http://python.org/sf/1346547 closed by effbot Syntax error on large file with MBCS encoding (2005-03-15) http://python.org/sf/1163244 closed by mhammond setgroups rejects long integer arguments (2004-01-02) http://python.org/sf/869197 closed by loewis Error in documentation for os.walk (2005-11-11) http://python.org/sf/1353793 closed by tim_one logging: Default handlers broken (2005-11-11) http://python.org/sf/1354052 closed by vsajip Significant memory leak with PyImport_ReloadModule (2005-08-11) http://python.org/sf/1256669 closed by birkenfeld Interactive help fails with Windows Installer (2005-11-11) http://python.org/sf/1354265 closed by loewis os.remove fails on win32 with read-only file (2004-12-29) http://python.org/sf/1092701 closed by effbot Division Error (2005-11-13) http://python.org/sf/1355903 closed by effbot IDLE, F5 – wrong external file content. (on error!) (2005-10-25) http://python.org/sf/1337987 closed by kbk Random core dumps (2004-11-10) http://python.org/sf/1063937 closed by nnorwitz Incorrect handling of unicode "strings" in asynchat.py (2005-11-16) http://python.org/sf/1358186 closed by effbot New / Reopened RFE __________________ python.desktop (2005-11-10) http://python.org/sf/1353344 opened by Bj?rn Lindqvist RFE Closed __________ please support the free visual studio sdk compiler (2005-11-05) http://python.org/sf/1348719 closed by loewis fix for ms stdio tables (2005-10-11) http://python.org/sf/1324176 closed by loewis From paschalis at interia.pl Tue Nov 1 16:01:35 2005 From: paschalis at interia.pl (dale cooper) Date: 1 Nov 2005 13:01:35 -0800 Subject: Tkinter problem In-Reply-To: References: <1130761580.552145.167340@z14g2000cwz.googlegroups.com> <1130800625.796277.222980@g14g2000cwa.googlegroups.com> Message-ID: <1130878895.208976.94150@f14g2000cwb.googlegroups.com> Thanks! At this moment I can see the first python generated Tk window on my screen. It's great ;-))) From peter at engcorp.com Wed Nov 30 13:22:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 30 Nov 2005 13:22:34 -0500 Subject: python speed In-Reply-To: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> Message-ID: David Rasmussen wrote: > Frithiof Andreas Jensen wrote: >>From the speed requirement: Is that correspondance chess by any chance?? > > Regular chess at tournament time controls requires speed too. Any pure > Python chess program would lose badly to the best C/C++ programs out > there now. > > I would also like to see Half Life 2 in pure Python. True, but so what? Why did you suddenly change the discussion to require "pure" Python? And please define "pure" Python, given that the interpreter and many builtins, not to mention many widely used extension modules, are coded in C? And are you not allowed to use any of the performance-boosting techniques available for Python, like Pyrex or Psyco? Why such restrictions, when these are things Python programs use on a daily basis: these are *part* of Python, as much as the -O switch on the compiler is part of C/C++. Okay, let's compare a "pure" Python program (if you can define it in any meaningful, practical way) with a "pure" Java program, running on a non-JIT interpreter and with optimizations turned off (because, of course, those optimizations are umm... somehow.. not "pure"...?). Judging by the other posts in this thread, the gauntlet is down: Python is faster than Java. Let those who believe otherwise prove their point with facts, and without artificially handcuffing their opponents with non-real-world "purity" requirements. -Peter From roy at panix.com Sun Nov 20 15:52:29 2005 From: roy at panix.com (Roy Smith) Date: Sun, 20 Nov 2005 15:52:29 -0500 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote: > One example I can think of is a large number of float constants used > for some math routine. In that case they usually be a full 16 or 17 > digits. It'd be handy in that case to split into smaller groups to > make it easier to match with tables where these constants may come > from. Ex: > > def sinxx(x): > "computes sin x/x for 0 <= x <= pi/2 to 2e-9" > a2 = -0.16666 66664 > a4 = 0.00833 33315 > a6 = -0.00019 84090 > a8 = 0.00000 27526 > a10= -0.00000 00239 > x2 = x**2 > return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10)))) > > (or least that's what I like to write). Now, if I were going to higher > precision, I'd have more digits of course. You have described, if memory serves, a Taylor series, and those coefficients are 1/3!, 1/5!, 1/7!, etc. What I would do, rather than embedding the numeric constants in the code, is embed the formula and have the machine compute the actual values at import time. At the very least, have them machine generated and saved. You certainly don't want to be typing in long strings of digits like that. From bockman at virgilio.it Sun Nov 6 12:49:39 2005 From: bockman at virgilio.it (Francesco Bochicchio) Date: Sun, 06 Nov 2005 18:49:39 +0100 Subject: Newbie Alert: Help me store constants pythonically References: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> Message-ID: Il Sun, 06 Nov 2005 08:33:17 -0800, Brendan ha scritto: > Hi all > > I'm new to Python (and programming in general), and I can't decide what > is the most 'pythonic' way to approach a problem. Your advice would be > appreciated. > > I have a bunch of 'scans', containing the data measured from one of > several types of 'model'. Each 'model' has different values for a list > of constants I want to create 'analyses' which interpret the data from > the scans, with reference the appropriate model. So far, I have come > up with three strategies to store this information, illustrated below > (I've simplified the constant list to just two): > > 1) Store the model constants as class instances: > > class Model: > def __init__(self, numBumps, sizeOfBumps): > self.__dict__.update(locals()); del self.self > > MODEL1 = Model(1, 2) > MODEL2 = Model(3, 4) > #etc > > class Analysis: > def __init__(self, scanData, model): > #do analysis > > 2) Store the model constants as class variables: > > class MODEL1: > numBumps = 1 > sizeOfBumps = 2 > > class MODEL2: > numBumps = 3 > sizeOfBumps = 4 > > class Analysis: > #as with 1 > > 3) Store the model constants as class variables of the analysis class: > > class Model1Analysis: > numBumps = 1 > sizeOfBumps = 2 > > def __init__(self, scanData): > #do analysis > > class Model2Analysis(Model1Analysis): > numBumps = 3 > sizeOfBumps = 4 > > There may be more options, but at this point I became paralyzed with > choice. I worry about getting stuck with an unworkable structure since > I don't have the experience to decide the merits of each in advance. I > get way too frustrated about these things :) > Brendan My vote would go to the first option, but I don't understand why you use such a complicate way to set instance attributes. I would do simply class Model: def __init__(self, numBumps, sizeOfBumps): self.numBumps = numBumps self.sizeofBumps = sizeOfBumps or, if you want to generalize the arguments of the constructor: class Model: def __init__(self, **model_attributes): for attname, attvalue in model_attributes.items(): setattr(self, attname, attvalue) As for why to choose the first option... is the one that causes you to avoid useless code repetitions and to keep the Analysis code nicely generic. Ciao ----- FB From evenprimes at gmail.com Thu Nov 3 10:48:28 2005 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 3 Nov 2005 10:48:28 -0500 Subject: when and how do you use Self? In-Reply-To: <4369d4f0$0$18073$626a14ce@news.free.fr> References: <4369d4f0$0$18073$626a14ce@news.free.fr> Message-ID: As a point of style: the 'other' identifier should only be used in Zen Metaclass programming as an implicit reference to the calling object or as a list of references to all other instances of the class. Context will make it both clear and obvious which use case is desired. On 03/11/05, bruno at modulix wrote: > Tieche Bruce A MSgt USMTM/AFD wrote: > > I am new to python, > > > > > > > > Could someone explain (in English) how and when to use self? > > > Don't use self. Use other. > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" > -- > http://mail.python.org/mailman/listinfo/python-list > -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From bonono at gmail.com Wed Nov 23 01:12:14 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 22:12:14 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <1h6g7u3.s47mh51bqem74N%aleax@mail.comcast.net> References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> <1132715742.672265.259740@o13g2000cwo.googlegroups.com> <4383e912.513766727@news.oz.net> <1132719449.516504.268980@z14g2000cwz.googlegroups.com> <1h6g70e.19ub6oh1pa0proN%aleax@mail.comcast.net> <1132725466.987600.167800@g14g2000cwa.googlegroups.com> <1h6g7u3.s47mh51bqem74N%aleax@mail.comcast.net> Message-ID: <1132726334.837563.279920@g43g2000cwa.googlegroups.com> Alex Martelli wrote: > bonono at gmail.com wrote: > ... > > But I can also record these changes in a seperate table which then > > becomes a "sorted" case ? > > somedict['x']='y', per se, does no magic callback to let you record > anything when type(somedict) is dict. You can wrap or subclass to your > heart's content to record insertion/deletion/update history, but that > ever-changing "seperate [[sic]] table" is entirely coupled to > 'somedict', not therefore "separate" at all, and should properly be kept > as an instance variable of your wrapper or subclass. > > That's a pretty obvious difference from cases in which the auxiliary > table used to define the ordering is REALLY *separate* -- independent of > the insertion/etc history of the dictionaries it may be used on. > So, it depends. From desparn at wtf.com Wed Nov 16 13:27:49 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Wed, 16 Nov 2005 13:27:49 -0500 Subject: is parameter an iterable? References: Message-ID: "Fredrik Lundh" wrote in news:mailman.750.1132159667.18701.python-list at python.org: > Rick Wotnaz wrote. > >> ... which leads me to belive that 'msg' is not type(str). It >> can be coerced (str(msg).find works as expected). But what >> exactly is msg? It appears to be of , and does >> not test equal to a string. > > it's an instance of the exception type, of course. > >::: > > if you do > > raise SomeError, value > > Python will actually do > > raise SomeError(value) > > (that is, create a SomeError exception and pass the value as its > first argument). > > you can use either form in your code (I prefer the latter > myself). > >::: > > as for catching the exceptions, if you do > > try: > ... > except SomeError, v: > ... > > Python will treat this as > > try: > ... > except: > # some exception occurred > typ = sys.exc_type > exc = sys.exc_value > if issubclass(typ, SomeError): > v = exc > ... > else: > raise # propagate! > > (where typ and exc are internal variables) > Thank you (and Roy Smith) for helping to clarify this. I see that my mental image of an Exception (which, I admit, was not based on extensive R'ing of TFM) was way off. Judging by Steven D'Aprano's code sample, I'm not the only one who was mistaken about the nature of v in your example. I'd always assumed it was the human- readable string associated with the TypeError. Wrong, I see. -- rzed From antonyliu2002 at yahoo.com Sun Nov 27 19:29:23 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Sun, 27 Nov 2005 16:29:23 -0800 (PST) Subject: How to enable bash mode at the interative mode? In-Reply-To: Message-ID: <20051128002923.3834.qmail@web35801.mail.mud.yahoo.com> Hi, thanks. Look what I have: $ python Python 2.4.2 (#1, Nov 20 2005, 13:03:38) [GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-2mdk)] on linux2 Yes, I realize that I don't have readline module available. The same Mandrake system has Python 2.3 as well, and it has the readline module. I don't know how to install the readline module. I tried what was suggested from the newsgroup, but got an error at make: make: *** [Modules/readline.o] Error 1 Thanks --- Carl Friedrich Bolz wrote: > Anthony Liu wrote: > > That is, at the Python interactive mode, if I hit > the > > upper arrow key, it'll bring up the last line of > code. > > > > At > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/fb8c2fd9eed0d/736fac8c33e84d0c?lnk=st&q=python+%22upper+arrow%22&rnum=2&hl=en#736fac8c33e84d0c > > , it seems that Michael Spalinski suggests of > > reinstalling Python. > > > > Any easier way to achieve this feature? > > > > Thanks. > > You are probably missing the readline module. What > operating > system/python version are you using? > > Cheers, > > Carl Friedrich Bolz > > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ From jstroud at mbi.ucla.edu Mon Nov 7 22:39:55 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 7 Nov 2005 19:39:55 -0800 Subject: Regular expression question -- exclude substring In-Reply-To: <436ffd9b$1_1@newspeer2.tds.net> References: <1131405834.093144.206510@g43g2000cwa.googlegroups.com> <436ffd9b$1_1@newspeer2.tds.net> Message-ID: <200511071939.55974.jstroud@mbi.ucla.edu> On Monday 07 November 2005 17:31, Kent Johnson wrote: > James Stroud wrote: > > On Monday 07 November 2005 16:18, google at fatherfrost.com wrote: > >>Ya, for some reason your non-greedy "?" doesn't seem to be taking. > >>This works: > >> > >>re.sub('(.*)(00.*?01) target_mark', r'\2', your_string) > > > > The non-greedy is actually acting as expected. This is because non-greedy > > operators are "forward looking", not "backward looking". So the > > non-greedy finds the start of the first start-of-the-match it comes > > accross and then finds the first occurrence of '01' that makes the > > complete match, otherwise the greedy operator would match .* as much as > > it could, gobbling up all '01's before the last because these match '.*'. > > For example: > > > > py> rgx = re.compile(r"(00.*01) target_mark") > > py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat > > 01') ['00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01'] > > py> rgx = re.compile(r"(00.*?01) target_mark") > > py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat > > 01') ['00 noise1 01 noise2 00 target 01', '00 dowhat 01'] > > ??? not in my Python: > >>> rgx = re.compile(r"(00.*01) target_mark") > >>> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat > >>> 01') > > ['00 noise1 01 noise2 00 target 01'] > > >>> rgx = re.compile(r"(00.*?01) target_mark") > >>> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat > >>> 01') > > ['00 noise1 01 noise2 00 target 01'] > > Since target_mark only occurs once in the string the greedy and non-greedy > match is the same in this case. Somehow my cutting and pasting got messed up. It should be: py> rgx = re.compile(r"(00.*?01) target_mark") py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01 target_mark') ['00 noise1 01 noise2 00 target 01', '00 dowhat 01'] py> rgx = re.compile(r"(00.*01) target_mark") py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01 target_mark') ['00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01'] Sorry about that. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From xray_alpha_charlie at yahoo.com Mon Nov 14 11:26:07 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Mon, 14 Nov 2005 08:26:07 -0800 (PST) Subject: newbie help needed Message-ID: <20051114162607.42068.qmail@web35907.mail.mud.yahoo.com> I am running the following program: def print Multiples (n, high): i = 1 while i <= high: print n*i, ' \t' , i = i + 1 print def printMultTable (high): i = 1 while i <= high: print Multiples (i, high) i = i + 1 printMultiples(8,8) printMultTable(8) Basically this program prints the correct multiplication table but instead of having just 8 rows it has 9 with the top row consisting of multiples of 8 then below the top row is a normal multiplication table...How can I get rid of the top row? --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjdevnull at yahoo.com Thu Nov 10 12:40:35 2005 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 10 Nov 2005 09:40:35 -0800 Subject: Pythonising the vim (e.g. syntax popups) -> vimpst In-Reply-To: <1131644203.723980.185230@f14g2000cwb.googlegroups.com> References: <200511091609.09613.email@christoph-haas.de> <200511100052.01043.r.roelofsen@tuxed.de> <1131644203.723980.185230@f14g2000cwb.googlegroups.com> Message-ID: <1131644435.169281.71950@o13g2000cwo.googlegroups.com> sjdevnull at yahoo.com wrote: > 2. Failing that, look in a help dictionary; I generated mine from the > info version of the Python docs, using a simple Python script. Which is as follows (run on all the python-lib*info* files and it'll generate a file called "output"; rename that to ~/.vim/pyhelp.py) import sys docDict = {} for file in sys.argv[1:]: lines = open(file, "r").readlines() for i in range(len(lines)): line = lines[i].strip() if line.startswith("`") and "(" in line and line.endswith("'"): line = line[1:-1] kv = line[0:line.find("(")] j = i while j < len(lines) and lines[j+1].startswith(" "): j = j+1 line = line + " "+lines[j].strip() if kv and kv not in docDict: docDict[kv] = line keys = docDict.keys() keys.sort() for k in keys: print docDict[k] open("output", "w").write("docDict="+`docDict`) From larry.bates at websafe.com Thu Nov 10 13:46:03 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 10 Nov 2005 12:46:03 -0600 Subject: help make it faster please In-Reply-To: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> Message-ID: <4373956B.2060509@websafe.com> pkilambi at gmail.com wrote: > I wrote this function which does the following: > after readling lines from file.It splits and finds the word occurences > through a hash table...for some reason this is quite slow..can some one > help me make it faster... > f = open(filename) > lines = f.readlines() > def create_words(lines): > cnt = 0 > spl_set = '[",;<>{}_&?!():-[\.=+*\t\n\r]+' > for content in lines: > words=content.split() > countDict={} > wordlist = [] > for w in words: > w=string.lower(w) > if w[-1] in spl_set: w = w[:-1] > if w != '': > if countDict.has_key(w): > countDict[w]=countDict[w]+1 > else: > countDict[w]=1 > wordlist = countDict.keys() > wordlist.sort() > cnt += 1 > if countDict != {}: > for word in wordlist: print (word+' '+ > str(countDict[word])+'\n') > The way this is written you create a new countDict object for every line of the file, it's not clear that this is what you meant to do. Also you are sorting wordlist for every line, not just the entire file because it is inside the loop that is processing lines. Some extra work by testing for empty dictionary: wordlist=countDict.keys() then if countdict != {}: for word in wordlist: if countDict is empty then wordlist will be empty so testing for it is unnecessary. Incrementing cnt, but never using it. I don't think spl_set will do what you want, but I haven't modified it. To split on all those characters you are going to need to use regular expressions not split. Modified code: def create_words(lines): spl_set = '[",;<>{}_&?!():-[\.=+*\t\n\r]+' countDict={} for content in lines: words=content.split() for w in words: w=w.lower() if w[-1] in spl_set: w = w[:-1] if w: if countDict.has_key(w): countDict[w]=countDict[w]+1 else: countDict[w]=1 return countDict import time filename=r'C:\cygwin\usr\share\vim\vim63\doc\version5.txt' f = open(filename) lines = f.readlines() start_time=time.time() countDict=create_words(lines) stop_time=time.time() elapsed_time=stop_time-start_time wordlist = countDict.keys() wordlist.sort() for word in wordlist: print "word=%s count=%i" % (word, countDict[word]) print "Elapsed time in create_words function=%.2f seconds" % elapsed_time I ran this against a 551K text file and it runs in 0.11 seconds on my machine (3.0Ghz P4). Larry Bates From casevh at comcast.net Fri Nov 11 01:51:43 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 10 Nov 2005 22:51:43 -0800 Subject: LARGE numbers In-Reply-To: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> References: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> Message-ID: <1131691903.961955.19950@o13g2000cwo.googlegroups.com> For more information on how the largest prime number was found, see www.mersenne.org. Python does support large numbers, but it's not very fast for such large numbers. There is a Python module called GMPY that uses the GMP (Gnu Multiple Precision) library for faster operations on large numbers. Both Python and GMP use a binary format to store large numbers. Binary format is most efficient for computation, but it is very slow to convert huge numbers from the internal binary format to a decimal format. I have written a library designed specifically to operate with huge numbers. It stores the numbers in a decimal format so conversion to decimal format is very fast. On my not-quite-ready-to-release development version, I can calculate, and convert to a string in decimal format, the largest known prime (2^25964951 - 1) in less than 10 seconds. My best time so far is 6.6 seconds. An early alpha-quality release is available at http://home.comcast.net/~casevh/ I also have release candidate versions of GMPY for Windows on that page. I'll try to get the next release and some demos up in a few days. Case From sjhalpin at gmail.com Fri Nov 18 00:25:41 2005 From: sjhalpin at gmail.com (flippetigibbet) Date: 17 Nov 2005 21:25:41 -0800 Subject: .pth - howto? In-Reply-To: References: <1132286440.597347.186850@g47g2000cwa.googlegroups.com> Message-ID: <1132291541.007880.146330@g47g2000cwa.googlegroups.com> I inserted the 'import pdb...' suggestions and set the .pth back to the first thing I'd tried: C:\Documents and Settings\user\My Documents\my\scripts\py\mydir and lo and behold - it works!! Then I took out the "import pdb ...' and ... it still works!! What did you do to my system to get it to work? :) Seriously though: thank you very much. I guess there must have been a typo in my original attempts or something like that. My team of trigger-happy lawyers are looking at me and licking their lips. From chris.atlee at gmail.com Wed Nov 16 13:02:03 2005 From: chris.atlee at gmail.com (chris.atlee at gmail.com) Date: 16 Nov 2005 10:02:03 -0800 Subject: path module / class Message-ID: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> Hi there, I haven't seen this topic pop up in a while, so I thought I'd raise it again... What is the status of the path module/class PEP? Did somebody start writing one, or did it die? I would really like to see something like Jason Orendorff's path class make its way into the python standard library. It seems like this comes up every so often, prompts some discussion, and then fizzles :) Last I checked on python-dev, people were mostly in agreement that the path module could be added, with a few modifications. (The top of the thread is here: http://thread.gmane.org/gmane.comp.python.devel/69403) A few issues that were left unresolved by that thread were: - should joinpath() be called subpath()? I think joinpath is fine, it agrees with os.path - should listdir() be called subpaths()? I don't think so, would listpaths() be a good alternative? - drop getcwd() method? - what the class / module should actually be called, and where should it live? - unicode support - timestamp / datetime objects for mtime/ctime/atime functions Cheers, Chris From bignose+hates-spam at benfinney.id.au Mon Nov 14 22:18:30 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Nov 2005 14:18:30 +1100 (EST) Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> <87psp2ao7s.fsf@lucien.dreaming> Message-ID: Bj?rn Lindstr?m wrote: > So, I guess no one read my explanation of why this an issue about > more than implementing enums (which is fairly trivial, as we have > seen). I read it. I see that something more than enums is being asked for. What I don't see is a use case where this is a benefit over just using an object type, such as enum or a string or something else. -- \ "All my life I've had one dream: to achieve my many goals." -- | `\ Homer, _The Simpsons_ | _o__) | Ben Finney From mwm at mired.org Wed Nov 30 23:25:36 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 23:25:36 -0500 Subject: Making immutable instances References: <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> <86u0duodzl.fsf@bhuda.mired.org> <1133333467.677454.134110@g49g2000cwa.googlegroups.com> <86acfloox6.fsf@bhuda.mired.org> <1133402729.430608.21400@g43g2000cwa.googlegroups.com> <86fypdmpi5.fsf@bhuda.mired.org> <1133410318.274544.326740@g47g2000cwa.googlegroups.com> Message-ID: <86zmnll9z3.fsf@bhuda.mired.org> bonono at gmail.com writes: > Well, in this case, would it be simple for the OP that if he wants to > disallow this attaching additional things, just use __slot__. That's *documented* as an implementation-dependent behavior. Using it to get that effect is abuse of the feature, and may well quit working in the future. > What I wan to say though is, if we can live with the inability of not > able to attach to built-in types, why is it so difficult for other user > defined class ? Because not being able to do it for built-in types is an implementation detail, and a wart in the language. And again, *what's the use case*? A number of people have asked why we shouldn't allow this, but none of them been able to come up with a use case better than "I think doing that is bad style." > If the authors go to the length of not allowing it, so be it. They > are afterall define it for their use and how someone else will use > it don't matter. I take it you never distribute your code, or otherwise expect other people to reuse it? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mwm at mired.org Wed Nov 30 01:18:22 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 01:18:22 -0500 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> Message-ID: <86u0duodzl.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> When it was suggested that a facility for doing this be added to the >> language, I asked for a use case for it. Nobodies come up with a >> reason for placing such restriction on the client yet. If you've got a >> use case, I'd be interested in hearing it. > I see it the other way; almost all the time in my own code I try to > initialize all of any instance's attributes in an __init__ method. > Dynamically adding attributes is useful sometimes, but done > willy-nilly leads to spaghetti code. Pretty much anything, if abused, can lead to "spaghetti code". > In the cases where it's useful, > I'd rather see it done through a special __setattr__ method, perhaps > inherited from a mixin: > > class Frob(Whatsit, DynamicAttributeMixin): > ... > > However, that's not likely to happen. The thing is, the need for an extra attribute doesn't come from your class, it comes from the client of your class. You can't know if the client code will need that facility or not, so the only choice you know won't be wrong sometime is to always add the mixin. In which case, you should follow the Python "the less boilerplate, the better" practice, and leave it off. Which is what we have. Letting the class author declare whether or not the client can add attributes is wrong for the same reasons - and in the same places - that letting the class author declare that the client shouldn't be allowed to access specific attributes, and so on, is wrong. Of course, it's also *right* for the same reasons and in the same places as those things. I just don't think those places happen in Python programs. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From peter at engcorp.com Wed Nov 2 11:44:27 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Nov 2005 11:44:27 -0500 Subject: Flat file, Python accessible database? In-Reply-To: References: <877jbsxnrx.fsf@lucien.dreaming> Message-ID: Steve Holden wrote: > My experience on Cygwin was that I had to install sqlite before pySqlite > worked. So although the Windows install of Pysqlite bundles a .pyd that includes the statically linked sqlite library, other platforms do not? I agree that would represent a potentially annoying extra setup step. -Peter From simon.brunning at gmail.com Wed Nov 23 08:03:48 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 23 Nov 2005 13:03:48 +0000 Subject: user-defined operators: a very modest proposal In-Reply-To: References: <4383C386.5040909@kzoo.edu> <8c7f10c60511230414w7547f2d7m@mail.gmail.com> Message-ID: <8c7f10c60511230503t1c3df3f2m@mail.gmail.com> On 23/11/05, Fredrik Lundh wrote: > see also: > > http://www.brunningonline.net/simon/blog/archives/000666.html > http://www.python.org/peps/pep-0666.html PEP 666 should have been left open. There are a number of ideas that come up here that should be added to it - and i'm sure there'll be more. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From lycka at carmen.se Wed Nov 23 08:44:49 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 23 Nov 2005 14:44:49 +0100 Subject: about sort and dictionary In-Reply-To: <1132678387.884058.107900@z14g2000cwz.googlegroups.com> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > a reminder" that the change is inplace. How arrogant! While > I'm sure the designers had kindly intentions. my memory, though > bad, is not that bad, and I object to being forced to write code > that is more clunky than need be, because the designers thought > they needed to help me with my memory. Such as being arm-twisted into writing horrible things like x = sorted(l) instead of x = l.sort()? It sounds a bit as if someone locked you into a cellar and forced you to program Python, just to torture you. I guess the next step will be the comfy armchair! ;) Python has its roots in ABC, a language intended for teaching programming to beginners, and it goes to great lengths to make it easy to do things right. In my opinion, it also avoids the mistake of introducing hurdles in a vain attempts to prevent programmer mistakes. Such hurdles typically lead to ugly workarounds. There are a few cases when things don't work as some people would expect them to work, but I think there are good resons for that. I'm surprised that you don't complain about not being able to do "while x = f(): ..." while you're at it. That's also a restriction of the kind you seem to rebel against. I'm pretty sure Guido didn't think a bit about *your* memory capacity when he designed Python, but rather wanted to avoid spending his and other programmers' time on helping people with yet another set of silly bugs. > There is much about Perl's rich functionality that is very worthy. > Unfortunately, as you know, it's syntax leaves a lot to be desired. Which is mainly a consequence of TMTOWTDI... If you want something more perlish, but with somewhat more sane syntax, you might want to try Ruby. From lycka at carmen.se Tue Nov 1 03:32:49 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 01 Nov 2005 09:32:49 +0100 Subject: Using graphviz to visualize trace.py output, anybody? In-Reply-To: <1130710534.618559.40680@g43g2000cwa.googlegroups.com> References: <1130710534.618559.40680@g43g2000cwa.googlegroups.com> Message-ID: svenn.are at bjerkem.de wrote: > Hi, > > has anybody thought of / already used graphviz to convert the output of > trace.py into a graph? Thanks for the pointer to trace.py. I hadn't seen that before. Are you thinking about a call-graph or sequence diagram, based on the output from trace.py --trace? I suspect it might be easiest to do that by modifying trace.py, so that it gives clearer hints about when it performs a call, and when it returns from a call. (Could it do that? Does trace.py have a clue about that?) E.g. from running trace.py --trace trace.py in Python 2.3 I get: ... --- modulename: trace, funcname: ? ... trace.py(104): PRAGMA_NOCOVER = "#pragma NO COVER" trace.py(107): rx_blank = re.compile(r'^\s*(#.*)?$') --- modulename: sre, funcname: compile sre.py(179): return _compile(pattern, flags) --- modulename: sre, funcname: _compile sre.py(218): cachekey = (type(key[0]),) + key sre.py(219): p = _cache.get(cachekey) sre.py(220): if p is not None: sre.py(221): return p trace.py(109): class Ignore: --- modulename: trace, funcname: Ignore trace.py(109): class Ignore: ... That should cause something like: trace.GLOBAL |->sre.compile | |->sre._compile |->trace.Ignore Finding the relevant nodes in the graph seems trivial. It's the ' --- modulename:...' rows. Figuring out the origin of the edges to these nodes seems error-prone. How do you know that the above isn't really... trace.GLOBAL |->sre.compile |->sre._compile |->trace.Ignore ...for instance? Looking at the output, we can see that it's not, and we know that sre won't call trace in _compile, but I'm not sure how to write a parser that would detect all such cases. I imagine that loops, callbacks etc might turn out to be tricky. Both calls and returns can look very different in Python, the program flow can move back and forth a lot, both modules and callables might have a different name than the one that appears in the source code where it's called (e.g. re => sre above) etc. I wrote somthing like this to analyze COBOL source code about a year ago, and that was trivial, but Python is so dynamic and varied compared to COBOL where I only had to look for "CALL something" if my memory serves me right. Perhaps you should make a simple parser that does the very easy part, essentially something like: ? -> sre.compile; ? -> sre._compile; ? -> trace.Ignore; Then you can massage the resulting dot-files manually until they give you the output you want. You should really do this with non- trivial code of the kind you would like to analyze, and make sure that you are able to create meaningful graphs. For instance, you probably want to show something other than just the output of... trace.__main__ -> sre.compile; sre.compile -> sre._compile; trace.__main__ -> trace.Ignore; ...since this wouldn't give you any meaningful image of the sequence. Or perhaps you just want collaboration diagrams? Actually, even if you end up doing manual work with every dot-file, it might turn out to be less work that other ways of doing graphs, at least if you can get typical edges right in your program and just fix occational ambiguities. I'm not so sure that it's so easy to get any pretty graphs at all from this approach though. I guess it requires some experimentation. From flamesrock at gmail.com Fri Nov 25 11:56:53 2005 From: flamesrock at gmail.com (flamesrock) Date: 25 Nov 2005 08:56:53 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132937812.977891.103460@g44g2000cwa.googlegroups.com> The best, in my opinion is wxPython. I recommend getting wxGlade and just fiddling around. You should be able to produce some interesting GUI's fairly easily. From mwm at mired.org Thu Nov 24 21:47:43 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 21:47:43 -0500 Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> <871x15vcdc.fsf@lucien.dreaming> <86u0e1va6q.fsf@bhuda.mired.org> Message-ID: <86fyplv3xs.fsf@bhuda.mired.org> "Giovanni Bajo" writes: > Mike Meyer wrote: >>> Bj?rn Lindstr?m wrote: >>> Why do you think we have a frozenset, for instance? By Mike's >>> argument, we shouldn't have it. >> Not *my* arguments, certainly. Not unless you're seriously >> misinterpreting them. > Sorry then, I probably am. There must be a misunderstanding somewhere. I'm seeing posts from you attribute to "Mike Meyer" (me) and "Mike" - some of which definitely weren't me. So maybe it wasn't mine. > What is your position about frozenset? By my understanding of your arguments, > it is a hand-cuffed version of set, which just prevents bugs that could still > be caught by testing. I have exactly the same problem with frozensets as I do with sets - I can't add attributes to either one. That frozenset can't be changed doesn't bother me particularly. > The same applies for the arbitrary restriction of not allowing sets > to be key dictionaries (with their hash value being their id). I can't parse that. What do you mean by "key dictionaries"? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From samrobertsmith at gmail.com Sun Nov 20 10:12:08 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 07:12:08 -0800 Subject: about dictionary Message-ID: <1d987df30511200712p661a1af4y140aead6a8d21cdb@mail.gmail.com> d is a dictionary. >>> d {0: [[0, 1], [0, 2]], 1: [[0, 1], [1, 2], [1, 3]], 2: [[0, 2], [1, 2], [2, 3]], 3: [[1, 3], [2, 3]]} for the value under each key, if the possible connection is in the dictionary, for example, under key 0. 1 and 2 were found to have a pair in some other places so get [0,1,2] hence, how to design a dictionary, let dicTry= {0: [[0, 1,2], 2: [[0, 1, 2], [1, 2,3]], 2: [[0, 1,2], [1, 2,3], 3: [1,2,3]} Thanks a lot! From greg.steffensen at gmail.com Sun Nov 6 15:08:23 2005 From: greg.steffensen at gmail.com (gsteff) Date: 6 Nov 2005 12:08:23 -0800 Subject: Python gui In-Reply-To: References: <436e3916$0$22284$4fafbaef@reader1.news.tin.it> Message-ID: <1131307703.160659.267170@g44g2000cwa.googlegroups.com> PyGTK is just easier to code with. The api is much nicer. However, yeah, the windows/mac appearance probably does make it a non-starter, unfortunately. As near as I can tell, the solution that currently has the most momentum is to just integrate the cheeseshop more tightly into python, so that whatever gui toolkit you choose can be installed easily. Its probably the only politically feasible solution anyway. Greg From oliver.andrich at gmail.com Tue Nov 1 16:35:10 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Tue, 1 Nov 2005 22:35:10 +0100 Subject: Object-Relational Mapping API for Python In-Reply-To: <1130872943.306455.129550@g47g2000cwa.googlegroups.com> References: <1130872943.306455.129550@g47g2000cwa.googlegroups.com> Message-ID: <6f7b52d0511011335w1e81d77dm@mail.gmail.com> Hi, if you enjoyed Hibernate or got intrigued by it, go and look into SQLOject ( http://www.sqlobject.org/). And you will be less intrigued by Hibernate, but will start to really like SQLObject. :) Best regards, Oliver -- Oliver Andrich --- http://roughbook.de/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy.d.brewer at gmail.com Wed Nov 30 23:52:01 2005 From: jeremy.d.brewer at gmail.com (jbrewer) Date: 30 Nov 2005 20:52:01 -0800 Subject: Python CGI Message-ID: <1133412721.816114.64490@g43g2000cwa.googlegroups.com> I need to update a CGI script I have been working on to perform validation of input files. The basic idea is this: 1.) HTML page is served 2.) User posts file and some other info 3.) Check file for necessary data * If data is missing, then post a 2nd page requesting needed data * If data is present, continue to 4 4.) Process input file and display results (processing path depends on whether data from 3 was present in file or had to be input by user) I'm unsure of the best way to implement step 3. Is it even possible to put all of this into one script? Or should I have one script check the file for the data, then pass the info on to a 2nd script? The cgi.FieldStorage() function should only be called once, so it seems like it's not possible to read a form and then repost another one and read it. If this is true and I need 2 scripts, how do I pass on the information in step 3 automatically if the file has the proper data and no user input is needed? Sorry if this is a dumb question (or unclear), but this is my (ever-growing) first CGI script. Thanks. Jeremy From ralmeida at gmail.com Wed Nov 30 10:48:29 2005 From: ralmeida at gmail.com (Roberto De Almeida) Date: 30 Nov 2005 07:48:29 -0800 Subject: XML and namespaces References: <1133364176.932411.113600@g47g2000cwa.googlegroups.com> Message-ID: <1133365709.569314.150120@g43g2000cwa.googlegroups.com> I've found the same bug. This is what I've been doing: from xml.dom.minidom import Document try: from xml.dom.ext import PrettyPrint except ImportError: PrettyPrint = None doc = Document() ... if PrettyPrint is not None: PrettyPrint(doc, stream=output, indent=' ') else: top_parent.setAttribute("xmlns", xmlns) output.write(doc.toprettyxml(indent=' ')) From bignose+hates-spam at benfinney.id.au Fri Nov 18 07:43:10 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 Nov 2005 23:43:10 +1100 (EST) Subject: Behaviour of enumerated types (was: Re: Immutable instances, constant values) References: <437d6711.87269326@news.oz.net> Message-ID: Bengt Richter wrote: > Ben Finney wrote: > >I've recently packaged 'enum' in PyPI. > [...] > My notion of enum comes from (what I remember of) Pascal You might want to investigate the 'enum' package for my idea of how an enumerated type can work. > which is basically an ordered set of names of integers forming a > type, and ord(one_of_the_names) gets you the index value. Getting a numeric index might be useful in a language such as Pascal, with no built-in dict or sequence types. In Python, where any immutable object can be a dict key, and any sequence can be iterated, it seems of no use. > But what we have is named integers, much as True and False are built > in names for integer subtypes with value 1 and 0. That's an implementation detail; surely code shouldn't be expecting any particular relationship between integers and boolean values? > So I'd say enums should also be int subtypes... Likewise, that seems best left as an implementation detail. Why expect any particular mapping to int values? Doing arithmetic or boolean logic on enumerated values seems against their purpose. -- \ "We tend to scoff at the beliefs of the ancients. But we can't | `\ scoff at them personally, to their faces, and this is what | _o__) annoys me." -- Jack Handey | Ben Finney From see at reply.to.field Sat Nov 5 12:45:31 2005 From: see at reply.to.field (Chris) Date: Sat, 5 Nov 2005 17:45:31 -0000 Subject: /usr/lib/python2.4/posixfile.py error References: <436afbc2$0$14200$9b622d9e@news.freenet.de> Message-ID: In article <436afbc2$0$14200$9b622d9e at news.freenet.de>, martin at v.loewis.de says... > Chris wrote: > > Wonder if anyone can help me? > > I very much doubt that, with as little information you gave us. > > > I am trying to run a perl script but I keep getting this error: > > > > /usr/lib/python2.4/posixfile.py:59: DeprecationWarning: The posixfile > > module is obsolete and will disappear in the future > > DeprecationWarning) > > It's very strange that you get a Python error when running a Perl > script. So I thought ;) However, it's a perl script that invokes python. http://search.cpan.org/~rprice/Nokia-File-NFB-0.01/lib/Nokia/File/NFB.pm > > Any ideas on why it's failing on that python module? > > It's not failing. It's a warning, not an error. The warning is > that the Python code you are running uses the posixfile module, > and it should be rewritten to stop doing so, as the posixfile > module will go away eventually. > Ok, many thanks. I got it working in the end, appears that the nfb.py script requires the file it is processing to be in the same directory. Which is quite annoying, but at least I know how to sort it now. Many thanks for your quick reply and apologies for my late one :( Cheers, Chris From venky at nospam.com Tue Nov 29 21:04:53 2005 From: venky at nospam.com (Venky) Date: Wed, 30 Nov 2005 02:04:53 GMT Subject: python & Tkinter - library loading failure in linux Message-ID: <9N7jf.9141$3o6.1741826@twister.southeast.rr.com> When I do 'import Tkinter', I get the ImportError: "libtk.so.0: cannot open shared object file: No such file or directory" I work around the issue by creating a softlink libtk.so.0 in the current directory to /usr/lib/libtk8.3.so and then updating env variable LD_LIBRARY_PATH to the current directory. After this, Tkinter module loads up fine. Is there a better way to do this (from within the python script) ? TIA venky From bokr at oz.net Mon Nov 7 23:08:06 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 08 Nov 2005 04:08:06 GMT Subject: Regular expression question -- exclude substring References: <1131405834.093144.206510@g43g2000cwa.googlegroups.com> <1131409094.240352.67240@g43g2000cwa.googlegroups.com> Message-ID: <43702496.416273970@news.oz.net> On Mon, 7 Nov 2005 16:38:11 -0800, James Stroud wrote: >On Monday 07 November 2005 16:18, google at fatherfrost.com wrote: >> Ya, for some reason your non-greedy "?" doesn't seem to be taking. >> This works: >> >> re.sub('(.*)(00.*?01) target_mark', r'\2', your_string) > >The non-greedy is actually acting as expected. This is because non-greedy >operators are "forward looking", not "backward looking". So the non-greedy >finds the start of the first start-of-the-match it comes accross and then >finds the first occurrence of '01' that makes the complete match, otherwise >the greedy operator would match .* as much as it could, gobbling up all '01's >before the last because these match '.*'. For example: > >py> rgx = re.compile(r"(00.*01) target_mark") >py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') >['00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01'] >py> rgx = re.compile(r"(00.*?01) target_mark") >py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') >['00 noise1 01 noise2 00 target 01', '00 dowhat 01'] > >My understanding is that backward looking operators are very resource >expensive to implement. > If the delimiting strings are fixed, we can use plain python string methods, e.g., (not tested beyond what you see ;-) >>> s = "00 noise1 01 noise2 00 target 01 target_mark" >>> def findit(s, beg='00', end='01', tmk=' target_mark'): ... start = 0 ... while True: ... t = s.find(tmk, start) ... if t<0: break ... start = s.rfind(beg, start, t) ... if start<0: break ... e = s.find(end, start, t) ... if e+len(end)==t: # _just_ after ... yield s[start:e+len(end)] ... start = t+len(tmk) ... >>> list(findit(s)) ['00 target 01'] >>> s2 = s + ' garbage noise3 00 almost 01 target_mark 00 success 01 target_mark' >>> list(findit(s2)) ['00 target 01', '00 success 01'] (I didn't enforce exact adjacency the first time, obviously it would be more efficient to search for end+tmk instead of tmk and back to beg and forward to end ;-) If there can be spurious target_marks, and tricky matching spans, additional logic may be needed. Too lazy to think about it ;-) Regards, Bengt Richter From runlevelten at gmail.com Sat Nov 26 18:51:12 2005 From: runlevelten at gmail.com (Ten) Date: Sat, 26 Nov 2005 23:51:12 +0000 Subject: Cheapest pocket device to code python on In-Reply-To: <1131076503.645113.309940@g49g2000cwa.googlegroups.com> References: <1131076503.645113.309940@g49g2000cwa.googlegroups.com> Message-ID: <200511262351.12911.runlevelten@gmail.com> On Friday 04 November 2005 03:55, theboringdays at gmail.com wrote: > What is the cheapest/affordable pocket device that I can code python > on? I think the closest I have seen is pocketpc from this page: > > http://www.murkworks.com/Research/Python/PocketPCPython/Overview Depends what you're using it for, and how cheap you mean. Having seen the PocketPC angle covered, I may as well cover a different angle give an even cheaper option. I use an old epocpython on a Psion Revo Plus for jotting down python concepts and testing out ideas, and I wouldn't be without it - especially because the Revo keyboard is usable in a way touchscreens aren't for me. It's not the most extensive python installation, and it won't stand much earthshifting (it doesn't include some modules, like tkinter) but it's a hell of a lot of portable python considering the fact you can pick one up for around 10 to 20 squids on ebay. Better keyboard than a pda, portable python for next to nothing. From franzl.mueller at gmx.de Tue Nov 29 19:18:38 2005 From: franzl.mueller at gmx.de (Franz Mueller) Date: Wed, 30 Nov 2005 01:18:38 +0100 Subject: Dive into Python PDF Message-ID: Hi there, is there a nicer looking version of the "Dive into Python" PDF? The one from diveintopython.org looks horrible, much worse than the web-version; also the images aren't where they should be. Has anybody tried to create a nice looking version? Maybe using dblatex or something similar? (I only know of the existence of docbook, never used it though) -- Franz From aleax at mail.comcast.net Sat Nov 19 22:03:29 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 19 Nov 2005 19:03:29 -0800 Subject: Confused about namespaces References: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> <1132356583.703129.241070@g47g2000cwa.googlegroups.com> <437efd39$0$16715$626a14ce@news.free.fr> <1132403581.738349.214210@g47g2000cwa.googlegroups.com> Message-ID: <1h6afhz.f3wbez1fa8ly7N%aleax@mail.comcast.net> KvS wrote: > Thanks a lot for all the answers. After rereading everything said here > today it's become more clear to me what you guys are telling me and > I'll actively try to forget about "from ... import *" ;). I commend you for your decision. It's a construct that I sometimes find quite handy in an experimentation session in the interactive interpreter, but just has no really good place in 'true' code;-0. Alex From cito at online.de Tue Nov 22 13:37:49 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 19:37:49 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1h6f39h.n2wpx91c4cc2qN%aleax@mail.comcast.net> References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> <1h6f39h.n2wpx91c4cc2qN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > Perl's _arrays_ are a bit like Python _lists_, and ordered; it's the > _hashes_ that are a bit like Python _dicts_, and unordered. PHP's use > of "array" for both concepts may indeed be a bit confusing. Perl's _hashes_ have been also called _associative arrays_ originally. >>Anyway, it would be interesting to examine this in detail and how this >>is implemented in other languages. Ok, I just did a little research an compared support for ordered dicts in some other languages: * Perl has hashes (associative arrays) which are not ordered. Here also people are asking for and implementing "ordered hashes", e.g. http://perltraining.com.au/tips/2005-06-29.html http://search.cpan.org/dist/Tie-IxHash/lib/Tie/IxHash.pm http://search.cpan.org/dist/Tie-InsertOrderHash/InsertOrderHash.pm http://www.yapc.org/America/previous-years/19100/schedule/author/pinyan.html * Ruby hashes are not ordered. Again people are asking for and implementing "ordered hashes". e.g. http://raa.ruby-lang.org/project/orderedhash/ http://groups.google.com/group/comp.lang.ruby/browse_frm/thread/8ebe8d1c5830c801/6428a870925f23f4 * Smalltalk: Innately has unordered Dictionaries. People are asking for and implementing "OrderedDictionaries" as well, e.g. http://exept.eu.org:8080/ClassDoc/classDocOf:,OrderedDictionary * Lisp has (ordered) "association lists". * PHP has ordered associative arrays. * Awk, TCL: Associative arrays are unordered. * C++ has a Map template in the STL which is ordered (a "Sorted Associative Container"). * Java: Has "LinkedHashMap" which is ordered. So ordered dictionaries don't seem to be such an exotic idea. All implementations I found were pretty unequivocally the same that I had in mind, using insertion order, appending the latest inserted keys at the end, not changing the order if an existing key is re-inserted, and deleting keys together with entries. I also found a discussion thread like the current where similar arguments were mentioned for and against ordered dictionaries: In http://mail.python.org/pipermail/python-dev/2005-March/052041.html, Nick Coghlan raises the following rhetorical question: Would the default semantics below really be that suprising? "An ordered dictionary remembers the order in which keys are first seen and, when iterated over, returns entries based on that order. This applies to direct iteration, iteration over values and (key, value) pairs, to the list-producing methods (i.e. keys(), values() and items()) and to any other operations that involve implicit iteration (e.g. converting to a string representation). Overwriting an entry replaces its value, but does not affect its position in the key order. Removing an entry (using 'del') _does_ remove it from the key order. Accordingly, if the entry is later recreated, it will then occur last in the key order. This behaviour is analagous to that of a list constructed using only list.append() to add items (indeed, the key order can be thought of as a list constructed in this fashion, with keys appended to the list when they are first encountered)." This was also the semantics I immediately had in mind when I thought about ordered dictionaries, though I hadn't read anything about ordered dictionaries before and it is the same semantics that I found others have implemented in other languages. I can't help but I still find it unambiguous and intuitive enough to consider it "the one" standard implementation for ordered dictionaries. Also, in the use cases mentioned (describing database columns, html form fields, configuration parameters etc.), the dictionary is usually only created once and then not changed, so different handling of re-insertion or deletion of keys would not even be relevant in these cases. -- Christoph From sybrenUSE at YOURthirdtower.com.imagination Tue Nov 1 12:18:06 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 1 Nov 2005 18:18:06 +0100 Subject: python.org offline References: <1130862100.694549.276860@f14g2000cwb.googlegroups.com> Message-ID: dcrespo enlightened us with: > "The server is temporarily unable to service your request due to > maintenance downtime or capacity problems." Yes, I can read. My question is: does anyone know why this happens so often lately? 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 smcg4191zz at friizz.RimoovAllZZs.com Tue Nov 22 12:42:31 2005 From: smcg4191zz at friizz.RimoovAllZZs.com (Stuart McGraw) Date: Tue, 22 Nov 2005 10:42:31 -0700 Subject: Why are there no ordered dictionaries? References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com><1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net><1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net><1132652504.327803.154790@g49g2000cwa.googlegroups.com><9smdnVdh0oNCkh7eRVn-uw@speakeasy.net><11o6hr7s4886720@corp.supernews.com> Message-ID: <11o6m49sq9vpi75@corp.supernews.com> "Fredrik Lundh" wrote in message news:mailman.1022.1132679831.18701.python-list at python.org... > Stuart McGraw wrote > > > > What would improve the Cheese Shop's interface for you? > > > > Getting rid of those damn top level links to old versions. > > Seeing a long list of old versions, when 99% of visitors are > > only interested in the current version, is just visual noise, > > and really lame. Move the old version links onto the page > > describing the software. > > hmm? the pypi package automatically hides old versions when > you post new ones, and it's been that way for ages... > > (which is bloody annoying if you're a package developers, since it > means that alphas for the next release hides the most recent stable > version) > > looking at the full index, ZODB seems to be the only package that's > available in more than just one stable and one development version... http://cheeseshop.python.org/pypi?:action=browse&asdf=405 - ClientForm-0.1.17 - ClientForm-0.2.1b ... - EmPy_3.1 - EmPy_3.1.1 - EmPy_3.2 - EmPy_3.3 ... - FauxIdent-1.1 - FauxIdent-1.2 - FauxIdent-1.2.1 ... Well, it is better than I remember it being a while (year?) ago, my recollection is that many packages had many, many old versions listed but now I usualy see only a couple versions. Hmm, so two versions means one is a development version, and the other is a stable version? I did not know that, and did not see it documented on the site. I would say documenting that would be an interface improvement. I still think it would be better to have just a package name (with current version) listed in the index page(s), and have alternate versions (old, alpha testing, etc) listed on the package's description page. From bignose+hates-spam at benfinney.id.au Sat Nov 19 04:02:11 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 19 Nov 2005 20:02:11 +1100 (EST) Subject: Reinvent no more forever References: <1132365222.708885.317350@g44g2000cwa.googlegroups.com> Message-ID: ismaelgfk at gmail.com wrote: > Ben Finney wrote: > > How do we deal with the rampant proliferation of a zillion > > implementations of some standard idiom in PyPI? > > How about some kind of "mega util" package? One big package with all > those recurring reinventions. If it gets popular enough, I'm sure it > could stop so much reinvention. No, you'd just ensure there would be several, competing, incompatible "mega util" packages. Plus, you'd have the additional problem of depending on a big, low-coherence package for one or two idioms within it. > I'm thinking that a Wiki would be quite suitable for development, to > incite more contributions (rather than only CVS). -- \ "As the most participatory form of mass speech yet developed, | `\ the Internet deserves the highest protection from governmental | _o__) intrusion." -- U.S. District Court Judge Dalzell | Ben Finney From me at privacy.net Thu Nov 3 11:15:56 2005 From: me at privacy.net (Dan Sommers) Date: Thu, 03 Nov 2005 11:15:56 -0500 Subject: when and how do you use Self? References: <4369d4f0$0$18073$626a14ce@news.free.fr> Message-ID: On Thu, 3 Nov 2005 10:48:28 -0500, Chris Cioffi wrote: > As a point of style: the 'other' identifier should only be used in > Zen Metaclass programming as an implicit reference to the calling > object or as a list of references to all other instances of the class. > Context will make it both clear and obvious which use case is desired. Can I use the 'other' identifier in, e.g., an __add__ method? Please? ;-) Regards, Dan -- Dan Sommers From peter at engcorp.com Sat Nov 19 13:08:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Nov 2005 13:08:57 -0500 Subject: Underscores in Python numbers In-Reply-To: <1132392820.882873.183570@g44g2000cwa.googlegroups.com> References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Steven D'Aprano: >>Perhaps Python should concatenate numeric literals at compile time: >>123 456 is the same as 123456. > > I think using the underscore it is more explicit: > n = 123_456 > > Alternatively the underscore syntax may be used to separate the number > from its base: > 22875 == 22875_10 == 595b_16 == 123456_7 > But probably this is less commonly useful (and not much explicit). Umm... in other words, "the underscore is under-used so let's assign some arbitrary meaning to it" (to make the language more like Perl perhaps?). Or maybe one should instead interpret this as "numeric literals need more bells and whistles, and I don't care which of these two we add, but we have to do *something*!". :-) -Peter From franck.perez at gmail.com Thu Nov 17 18:49:04 2005 From: franck.perez at gmail.com (Franck PEREZ) Date: Fri, 18 Nov 2005 00:49:04 +0100 Subject: Importing a class without knowing the module Message-ID: Hello, I'm developing a small XML marshaller and I'm facing an annoying issue. Here's some sample code: ########### My test application ############ class Foo(object): #The class I'd like to serialize pass import myMarshaller foo = Foo() s = myMarshaller.dumps(foo) #works fine, spits something like another_foo = loads(s) #fails, see below ########### My marshaller (in its own module) ############ def loads(s): #First, get class name (here "Foo") klass = eval(className) #fails because "Foo" is not in the marshaller's namespace ! How could I tell the marshaller to locate the Foo class and any other class I try to deserialize ? I've tried to pass my test application's globals() to the marshaller, it works but it's dirty IMHO... I've tried also to locate the class (here "Foo") somewhere in sys.modules in the "loads" method, but it was heavy and unsuccessful. Thanks a lot for your help ! Franck From bkhl at stp.lingfil.uu.se Sun Nov 13 10:28:31 2005 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Sun, 13 Nov 2005 16:28:31 +0100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> Message-ID: <87mzk8pnxc.fsf@lucien.dreaming> Ben Finney writes: > I've yet to see a convincing argument against simply assigning values > to names, then using those names. The problem with that is that you can't pass around the names of objects that are used for other things. Obviously they make enums unnecessary, but only people damaged by non-dynamic languages could think that's the main point. ;-) Being able to do that precludes the need for converting going back and forth between strings and method names when you need to do things like keeping a list of function names, even when you need to be able to change what those function names point to. Python doesn't really need to introduce a new type to do this. It's already there, as what we usually just call names. Probably this discussion would benefit from talking about names rather than symbols, as that seems to confuse some people. So, Python already has symbols. What we need is a way to refer to these symbols explicitly. I would suggest to do it like in Lisp: quote(spam) Of course, this would preferably be implemented so that it doesn't just work on simple names: quote(spam(eggs)) I syntactic sugar, like ' in Lisp, could be introduced later, but I don't think that would be strictly necessary. -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From cito at online.de Mon Nov 28 17:08:49 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 28 Nov 2005 23:08:49 +0100 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Fredrik Lundh schrieb: > Christoph Zwerschke wrote: >>But the problem is that the tutorials and manuals give the impression >>that the difference between lists and tuples is only mutablity versus >>immutability. > > both the tutorial and the FAQ discusses the difference in terms of use > cases and recommended usage. The tutorial does not speak about differences other than mutability. But you're right, the C structs analogy is mentioned in the FAQ. >>Maybe I am I lacking the satori of a real Python Zen master? > > I suggest you look up the phrase "bike shed effect". next, go read some > recent PEP:s to see what's really going on in the Python design universe. The bike shed effect is a good explanation and so true. About 8 years ago when I started to work at my current working place at the university I suggested that a bike shed should be provided for people like me. Since then, a lot of million euro projects have been carried out, like introducing SAP software and new projects are in progress. But my bike still is getting wet and anyway, it's still bothering me. -- Christoph From hancock at anansispaceworks.com Wed Nov 23 10:20:15 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 23 Nov 2005 09:20:15 -0600 Subject: Timeout for regular expression In-Reply-To: References: <1132681028.115173.201230@g47g2000cwa.googlegroups.com> Message-ID: <20051123092015.101a77be@samwise.anansi> On Tue, 22 Nov 2005 18:49:15 +0100 "Fredrik Lundh" wrote: > not directly. the only reliable way is to run it in a > separate process, and use the resource module to set > necessary limits. Wow. Thank you Mr. Lundh, I never noticed that module. I think I have an application for that. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From spam.csubich+block at block.subich.spam-dot-com.no-spam.invalid Tue Nov 29 16:28:53 2005 From: spam.csubich+block at block.subich.spam-dot-com.no-spam.invalid (spam.csubich+block at block.subich.spam-dot-com.no-spam.invalid) Date: 29 Nov 2005 21:28:53 GMT Subject: Unifying Attributes and Names (was: Re: Death to tuples!) References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: <438cc815$0$1526$892e7fe2@authen.yellow.readfreenews.net> Bengt Richter wrote: > If we had a way to effect an override of a specific instance's attribute accesses > to make certain attribute names act as if they were defined in type(instance), and > if we could do this with function instances, and if function local accesses would > check if names were one of the ones specified for the function instance being called, > then we could define locally named constants etc like properties. > > The general mechanism would be that instance.__classvars__ if present would make > Nah... you're not nearly going far enough with this. I'd suggest a full unification of "names" and "attributes." This would also enhance lexical scoping and allow an "outer" keyword to set values in an outer namespace without doing royally weird stuff. In general, all lexical blocks which currently have a local namespace (right now, modules and functions) would have a __namespace__ variable, containing the current namespace object. Operations to get/set/delete names would be exactly translated to getattr/setattr/delattrs. Getattrs on a namespace that does not contain the relevant name recurse up the chain of nested namespaces, to the global (module) namespace, which will raise an AttributeError if not found. This allows exact replication of current behaviour, with a couple interesting twists: 1) i = i+1 with "i" in only an outer scope acutally works now; it uses the outer scope "i" and creates a local "i" binding. 2) global variables are easily defined by a descriptor: def global_var(name): return property( lambda self: getattr(self.global,name), lambda (self, v): setattr(self.global,name,v), lambda self: delattr(self.global,name), "Global variable %s" % name) 3) "outer variables" under write access (outer x, x = 1) are also well-defined by descriptor (exercise left for reader). No more weird machinations involving a list in order to build an accumulator function, for example. Indeed, this is probably the primary benefit. 4) Generally, descriptor-based names become possible, allowing some rather interesting features[*]: i) "True" constants, which cannot be rebound (mutable objects aside) ii) Aliases, such that 'a' and 'b' actually reference the same bit, so a = 1 -> b == 1 iii) "Deep references", such that 'a' could be a reference to my_list[4]. iv) Dynamic variables, such as a "now_time" that implicitly expands to some function. 5) With redefinition of the __namespace__ object, interesting run-time manipulations become possible, such as redefining a variable used by a function to be local/global/outer. Very dangerous, of course, but potentially very flexible. One case that comes to mind is a "profiling" namespace, which tracks how often variables are accessed -- over-frequented variables might lead to better-optimized code, and unaccessed variables might indicate dead code. [*] -- I'm not saying that any of these examples are particularly good ideas; indeed, abuse of them would be incredibly ugly. It's just that these are the first things that come to mind, because they're also so related to the obvious use-cases of properties. The first reaction to this is going to be a definite "ewwwww," and I'd agree; this would make Python names be non-absolute [then again, the __classvars__ suggestion goes nearly as far anyway]. But this unification does bring all the power of "instance.attribute" down to the level of "local_name". The single biggest practical benefit is an easy definiton of an "outer" keyword: lexical closures in Python would then become truly on-par with use of global variables. The accumulator example would become: def make_accum(init): i = init def adder(j): outer i #[1] i += j return i return adder [1] -- note, this 'outer' check will have to require that 'i' be defined in an outer namespace -at the time the definition is compiled-. Otherwise, the variable might have to be created at runtime (as can be done now with 'global'), but there's no obvious choice on which namespace to create it in: global, or the immediately-outer one? This implies the following peculiar behaviour (but I think it's for the best): > # no i exists > def f(): # will error on definition > outer i print i > def g(): # won't error > print i > i = 1 > f() > g() > Definitely a Py3K proposal, though. From keesvanschaik at gmail.com Tue Nov 1 18:45:59 2005 From: keesvanschaik at gmail.com (KvS) Date: 1 Nov 2005 15:45:59 -0800 Subject: wxPython: updating style of StaticText from event generated by button References: <1130886746.328723.109570@f14g2000cwb.googlegroups.com> <4367f8fb$0$24643$4fafbaef@reader3.news.tin.it> Message-ID: <1130888759.884816.247730@o13g2000cwo.googlegroups.com> Thanks :), I'll give both of your hints a try. What I basically want to do is have something like an "old style" button in win xp that's either "up" or "down", since I couldn't find a more straightforward method I thought taking a text widget and adjusting the border at mouse click would be the best alternative no? One question then, what's the use of having a method like SetWindowStyle() if it doesn't really do anything at runtime? Is it indeed just intended for the few widgets that do support it? - Kees From eric_brunel at despammed.com Wed Nov 16 11:53:23 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 16 Nov 2005 17:53:23 +0100 Subject: How to write an API for a Python application? References: <437af434@news.bezeqint.net> <1132150685.389414.258170@z14g2000cwz.googlegroups.com> Message-ID: On 16 Nov 2005 06:18:05 -0800, Paul Boddie wrote: > Gary Kshepitzki wrote: >> I would like to create an API for a piece of Python code. The API is for use >> by non Python code. >> It should support interaction in both directions, both accessing functions >> on the API and the ability for the API to raise events on its client. >> What is the best way to do that? > > One technology that I used many years ago with Python, and which should > still do the job is CORBA - at that time ILU, but I suppose the various > other ORBs should also be as capable; certainly, ILU permitted > callbacks from the server into the client. These days, you might want > to look at omniORB, Fnorb and ORBit. > > Paul I never saw any way to create callbacks from server to client with CORBA. How would you describe such a callback in the IDL file? TIA -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From grante at visi.com Tue Nov 1 12:57:34 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Nov 2005 17:57:34 -0000 Subject: Python's website does a great disservice to the language References: Message-ID: <11mfb4el2kk5b00@corp.supernews.com> On 2005-11-01, CppNewB wrote: > I was trying to advocate using Python for an upcoming > prototype, so my boss went out to take a look at the > documentation and try and get a feel for what the language is > all about. > > First comment; "I hope the language is designed better than > the site." It sounds like you work for the prototypical PHB. > The site is readable, but is amateurish. If I had an ounce of > design skills in me, I would take a stab at it. May God save us from "professional" looking web sites. > Maybe we could round up a couple of designers to donate some > time? Maybe we could build a basic CMS on top of Django or > TurboGears (displaying Python's capability as a web > development stack)? I like the Python web site. It's simple, easy to read, and easy to use. Just like the lanuage. -- Grant Edwards grante Yow! Yow!! That's a GOOD at IDEA!! Eating a whole FIELD visi.com of COUGH MEDICINE should make you feel MUCH BETTER!! From frithiof.jensen at diespammerdie.jensen.tdcadsl.dk Thu Nov 24 07:40:12 2005 From: frithiof.jensen at diespammerdie.jensen.tdcadsl.dk (Frithiof Andreas Jensen) Date: Thu, 24 Nov 2005 13:40:12 +0100 Subject: Using Cron to run a python program References: <1132791791.548850.186420@o13g2000cwo.googlegroups.com> Message-ID: <4385b4aa$0$8780$edfadb0f@dread14.news.tele.dk> skrev i en meddelelse news:1132791791.548850.186420 at o13g2000cwo.googlegroups.com... > permissions just to be safe. What would cause the logging to work at a > command prompt but fail in cron? Because the environment is different; "man cron" might tell *how* it is different (I cannot because it varies with platform, distribution ... ) From schwehr at gmail.com Sun Nov 27 11:35:04 2005 From: schwehr at gmail.com (schwehr at gmail.com) Date: 27 Nov 2005 08:35:04 -0800 Subject: passing artibrary strings into a database Message-ID: <1133109304.575556.284190@g47g2000cwa.googlegroups.com> Hi All, I was wondering if there is a helper library out there that will nicely encode artibrary text so that I can put in into a TEXT field in a database and then retrieve it without getting into trouble with ',",new lines or other such things that would foul the sql insert call and or be a security hazard? This feels like a newbee type question, but I haven't found anything with a quick search. Thanks, -kurt From eurleif at ecritters.biz Mon Nov 14 17:21:03 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 14 Nov 2005 22:21:03 GMT Subject: Parse file into array In-Reply-To: <1132004925.481923.47520@z14g2000cwz.googlegroups.com> References: <1132004925.481923.47520@z14g2000cwz.googlegroups.com> Message-ID: amfr wrote: > I was wondering how i could parse the contents of a file into an array. > the file would look something like this: > > gif:image/gif > html:text/html > jpg:image/jpeg > ... > > As you can see, it contains the mime type and the file extension > seperated by commas, 1 per line. I was wondering if it was possible to > create and array like this: > > (Pseudocode) > mimetypearray[gif] = "image/gif" > mimetypearray[html] = "text/html" > mimetypearray[jpg] = "image/jpeg" > ... You want a dictionary, not an array. mimetypedict = {} for line in mimetypefile: line = line.rsplit('\r\n') extension, mimetype = line.split(':') mimetypedict[extension] = mimetype Note that there's already a MIME type database in the standard mimtypes module: . From paul at boddie.org.uk Wed Nov 9 13:02:03 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 9 Nov 2005 10:02:03 -0800 Subject: Web automation References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> <1131397945.832762.71070@g47g2000cwa.googlegroups.com> <86k6fk9k6v.fsf@bhuda.mired.org> <1131415131.676626.7730@g49g2000cwa.googlegroups.com> <86r79r96qh.fsf@bhuda.mired.org> <1131481509.978954.25900@g49g2000cwa.googlegroups.com> <1131549811.451297.160650@o13g2000cwo.googlegroups.com> <1131555173.464527.133760@g47g2000cwa.googlegroups.com> Message-ID: <1131556798.392662.229800@g47g2000cwa.googlegroups.com> qwwee... at yahoo.it wrote: > While I was posting the reply to Mike I saw the last > contribution of Paul Boddie. > > From what he says I infer that he is a Windows programmer Far from it! OutlookExplorer was written as an experiment when I had to use Windows in a corporate environment. I don't run Windows at all on my own hardware, and I even assembled my own Linux-compatible machine in order to (a) not pay the Windows tax and (b) get open enough hardware for which Linux drivers exist. Rant: instead of quietly grumbling and installing Linux over Windows on newly purchased hardware, and then grumbling some more about incomplete device support, I'd advise both individuals and businesses to tell vendors where they can shove their bundled Windows licences and special agreements with Microsoft. Installing Linux after the fact does little to enlighten the average vendor - to them you're still running Windows, loving it, and presumably willing to buy the whole package from them again in future. Rant over! > (OutlookExplorer). > In Windows I have no problems (a part security) to program > "dirty" automation scripts! > But I have a doubt... how my Windows theory accords > with DCOP and KDE? DCOP is mostly equivalent to COM for automation purposes. Whilst there are command line tools (dcop) and simple graphical tools (kdcop) for accessing the interfaces exposed by applications, you might want to consider PyKDE and its own DCOP support. What I've just added to qtxmldom is support for DCOP-based access to DOM documents in Konqueror, although the installation of the different components is still a bit awkward: PyKDE needs a patch, for example. Paul From fakeaddress at nowhere.org Fri Nov 4 14:08:36 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 04 Nov 2005 19:08:36 GMT Subject: Catch stderr in non-console applications Message-ID: New and improved! Love Python's stack-tracing error messages, but hate the way GUI applications throw the messages away and crash silently? Here's a module to show Python error messages that would otherwise be lost in console-less programs. Graphical applications should not require console windows, but they do need a workable destination for sys.stderr. To try it out, you can use something like: import errorwindow x = undefined_variable_name I've tried this version on Microsoft Windows 2000 and XP, and on a couple versions of Linux. I'd be happy to hear how it does on other systems. Thanks to George (g... at ll.mit.edu) for testing a previous version. Thanks to Robert Kern for pointing me to a bug solution. --Bryan ---------------- cut ------------------- #!/usr/bin/env python # Python module "errorwindow.py", by Bryan Olson, 2005. # This module is free software and may be used, distributed, # and modified under the same terms as Python itself. """ Importing this module redirects sys.stderr so that error output, if any, will appear in a new window. Notes on the module: It is particularly handy for graphical applications that do not otherwise have a stderr stream. It mitigates most silent failures. It uses only this file plus facilities in the Python standard distribution. There are no functions to call; just import it. Import it early; it cannot catch prior errors. It can catch syntax errors in modules imported after it, but not in '__main__'. Importing it more than once is harmless. When there is no error output, it is highly efficient, because it does nothing. Upon output to sys.stderr, it runs a new process and pipes the error output. It does not import any graphical library into your program. The new process handles that. """ import sys import os import thread if __name__ == '__main__': from threading import Thread from Tkinter import * import Queue queue = Queue.Queue(99) def read_stdin(app): while 1: data = os.read(sys.stdin.fileno(), 2048) queue.put(data) if not data: break class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master.title("Error stream from %s" % sys.argv[-1]) self.pack(fill=BOTH, expand=YES) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) xscrollbar = Scrollbar(self, orient=HORIZONTAL) xscrollbar.grid(row=1, column=0, sticky=E+W) yscrollbar = Scrollbar(self) yscrollbar.grid(row=0, column=1, sticky=N+S) self.logwidget = Text(self, wrap=NONE, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) self.logwidget.grid(row=0, column=0, sticky=N+S+E+W) xscrollbar.config(command=self.logwidget.xview) yscrollbar.config(command=self.logwidget.yview) # Disallow key entry, but allow copy with self.logwidget.bind('', lambda x: 'break') self.logwidget.bind('', lambda x: None) self.after(200, self.start_thread, ()) def start_thread(self, _): t = Thread(target=read_stdin, args=(self,)) t.setDaemon(True) t.start() self.after(200, self.check_q, ()) def check_q(self, _): go = True while go: try: data = queue.get_nowait() if not data: Label(self, text="Stream closed.", relief= "sunken").grid(row=2, sticky=E+W) go = False self.logwidget.insert(END, data) self.logwidget.see(END) except Queue.Empty: self.after(200, self.check_q, ()) go = False app = Application() app.mainloop() else: class ErrorPipe(object): def __init__(self): self.lock = thread.allocate_lock() self.command = " ".join([sys.executable, __file__, sys.argv[0]]) def write(self, data): self.lock.acquire() try: if not hasattr(self, 'pipe'): self.rawpipe = os.popen(self.command, 'w') fd = os.dup(self.rawpipe.fileno()) self.pipe = os.fdopen(fd, 'w', 0) self.pipe.write(data) finally: self.lock.release() sys.stderr = ErrorPipe() From merman at o2online.de Tue Nov 15 07:12:31 2005 From: merman at o2online.de (TK) Date: Tue, 15 Nov 2005 13:12:31 +0100 Subject: codecs Message-ID: <4379d05d$0$10556$9b622d9e@news.freenet.de> Hi there, sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout) What does this line mean? Thanks. o-o Thomas From prinster at mail.com Mon Nov 28 19:18:46 2005 From: prinster at mail.com (Stephen Prinster) Date: Tue, 29 Nov 2005 00:18:46 GMT Subject: UUID? In-Reply-To: References: Message-ID: Huang Zhen wrote: > Hello, > How can I get a UUID with python? > Thanks! I've never used this, but I just saw it on Planet Python this morning: http://www.livejournal.com/users/zestyping/157957.html HTH, Steve P. From aleax at mail.comcast.net Mon Nov 21 22:57:25 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 21 Nov 2005 19:57:25 -0800 Subject: ownership problem? References: Message-ID: <1h6e7am.19do5hq1vzs5woN%aleax@mail.comcast.net> Jeffrey Schwab wrote: ... > > You may be gratified to learn that Python's main storage model > > is reference counted objects, and when an object falls out of > > all referenced scopes its finalizers run immediately. > > Thanks, that's good to know! For some reason I had it in my head that > Python always used mark & sweep. I'm used to ref-counted collection in > Perl, but I never relied on it because of a nagging (probably > ill-founded) worry about cyclic references. Does Python have any way > around this? Is there a Python equivalent to C++ destructors? Python (main implementation, known as CPython) uses mark-and-sweep (with generations &c) to deal with cyclic garbage -- but destructors (__del__ methods) *interfere* with cyclic garbage collection (there may be no safe order of freeing a bunch of cyclic garbage when objects have __del__ methods, and Python can't find it if there is, anyway). > I think Java has had a big influence, too. People just don't seem to > want to be bothered with thinking about object life cycles at all. This > seems unfortunate to me, because cleanup still has to be done, so it > just ends up getting moved outside the objects where it belongs. I > think this hurts abstraction. Python 2.5 should introduce a 'with' statement that may go partways towards meeting your qualms; it's an approved PEP, though I do not recall its number offhand. Alex From jstroud at mbi.ucla.edu Tue Nov 1 16:47:48 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 1 Nov 2005 14:47:48 -0700 Subject: Python's website does a great disservice to the language In-Reply-To: References: Message-ID: <200511011347.48938.jstroud@mbi.ucla.edu> On Tuesday 01 November 2005 09:45, CppNewB wrote: > First comment; "I hope the language is designed better than the site." The website is beautiful. I just looked. Its the logo that is a little off-putting. It makes a pretty bad first impression. Compare it to java's. Even the php logo looks better. For a real cool logo, check biopython.org. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve.morin at gmail.com Tue Nov 15 17:45:27 2005 From: steve.morin at gmail.com (Steve) Date: 15 Nov 2005 14:45:27 -0800 Subject: Shutdown hook Message-ID: <1132094726.985460.97110@g14g2000cwa.googlegroups.com> Does any one know if python has the ability to run a shutdown hook. For example you set a method to run when the python process is shutting down, like it recieved a kill signal? Basically looking for an effect like the following java code. Runtime.getRuntime().addShutdownHook(new Thread(this)); From davecook at nowhere.net Tue Nov 1 16:11:17 2005 From: davecook at nowhere.net (Dave Cook) Date: Tue, 01 Nov 2005 21:11:17 GMT Subject: Object-Relational Mapping API for Python References: <1130872943.306455.129550@g47g2000cwa.googlegroups.com> Message-ID: On 2005-11-01, Aquarius wrote: > I explored Java's Hibernate a bit and I was intrigued by how you can > map entity objects to database tables, preserving all the relations and > constraits. I am interested if there is something like this for Python > - I noticed some APIs in the "Cheeseshop", but most of them were alpha, > better, or seemed to be forsaken a long time ago. Can you recommend me > anything? SQLObject is quite mature and actively maintained. I have to say that I don't care for ORMs much (or at least many of the Python ones); you usually lose a lot of the power of relational databases. Dave Cook From mwm at mired.org Thu Nov 24 12:29:09 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 12:29:09 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <43850a7a$0$8074$9b622d9e@news.freenet.de> Message-ID: <868xvex8d6.fsf@bhuda.mired.org> Christoph Zwerschke writes: > - Because sets can only contain immutable values Not true. Sets can only contain *hashable* objects, which isn't the same thing. > This, of course, in turn raises the question ;-) Would it be desirable > to have an additional, more general set datatype that can contain > mutable objects? You can do that now: >>> from UserList import UserList >>> class HashableList(UserList): ... def __hash__(self): return id(self) ... >>> s = set([HashableList(), HashableList()]) >>> s set([[], []]) >>> for x in s: ... x.append(3) ... >>> s set([[3], [3]]) This also illustrates the danger of this approach, in that I've got two lists that will compare equal in the same set: >>> x = list(s) >>> x[0] == x[1] True Of course, in this case the two objets aren't the same, which is what is required for the mathematical definition of list: >>> x[0] is x[1] False http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From aleax at mail.comcast.net Wed Nov 9 23:42:06 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 9 Nov 2005 20:42:06 -0800 Subject: Iterator addition References: <7x4q6lm87q.fsf_-_@ruckus.brouhaha.com> Message-ID: <1h5s1dp.i6hnk31bmv4xN%aleax@mail.comcast.net> Paul Rubin wrote: > Is there a good reason to not define iter1+iter2 to be the same as > itertools.chain(iter1, iter2)? No -- feel free to define __add__ accordingly in every one of your iterator classes. If you mean for *ALL* built-in types, such as generators, lists, files, dicts, etc, etc -- I'm not so sure. Right now, if I mistakenly try to add a list to a dict, I get an exception which immediately alerts me to my mistake. I definitely wouldn't want to lose that... Alex From steve at REMOVETHIScyber.com.au Thu Nov 3 10:36:41 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 02:36:41 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: On Thu, 03 Nov 2005 13:01:40 +0000, Antoon Pardon wrote: >> Seems perfectly sane to me. >> >> What would you expect to get if you wrote b.a = b.a + 2? > > I would expect a result consistent with the fact that both times > b.a would refer to the same object. class RedList(list): colour = "red" L = RedList(()) What behaviour would you expect from len(L), given that L doesn't have a __len__ attribute? >> Why do you expect >> b.a += 2 to give a different result? > > I didn't know I did. It seems to me that you do. You didn't appear to be objecting to a line like x = b.a assigning the value of 1 to x (although perhaps you do). If that was the case, then it is perfectly reasonable to expect b.a = x + 2 to store 3 into b.a, while leaving b.__class__.a untouched. Of course, if you object to inheritance, then you will object to x = b.a as well. >> Since ints are immutable objects, you shouldn't expect the value of b.a >> to be modified in place, and so there is an assignment to b.a, not A.a. > > You are now talking implementation details. I don't care about whatever > explanation you give in terms of implementation details. I don't think > it is sane that in a language multiple occurence of something like b.a > in the same line can refer to different objects That's an implementation detail only in the sense that "while condition" is a loop is an implementation detail. It is a *design* detail. b is a name, and any reference to b (in the same namespace) will refer to the same object. At least until you rebind it to another object. But b.a is not a name, it is an attribute lookup, and by Python's rules of inheritance that lookup will look up attributes in the instance, the class, and finally any superclasses. If you persist in thinking of b.a as a name referring to a single object, of course you will be confused by the behaviour. But that's not what attribute lookup does. On the right hand side of an assignment, it will return the first existing of b.__dict__['a'] or b.__class__.__dict__['a']. On the left hand of an assignment, it will store into b.__dict__['a']. > I think it even less sane, if the same occurce of b.a refers to two > different objects, like in b.a += 2 Then it seems to me you have some serious design problems. Which would you prefer to happen? # Scenario 1 # imaginary pseudo-Python code with no inheritance: class Paragraph: ls = '\n' # line separator para = Paragraph() para.ls => AttributeError - instance has no attribute 'ls' # Scenario 2 # imaginary pseudo-Python code with special inheritance: class Paragraph: ls = '\n' # line separator linux_para = Paragraph() windows_para = Paragraph() windows_para.ls = '\n\r' # magically assigns to the class attribute linux_para.ls => prints '\n\r' # Scenario 3 # Python code with standard inheritance: class Paragraph: ls = '\n' # line separator linux_para = Paragraph() windows_para = Paragraph() windows_para.ls = '\n\r' linux_para.ls => prints '\n' -- Steven. From peter at engcorp.com Thu Nov 10 21:59:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Nov 2005 21:59:12 -0500 Subject: testing C code with python In-Reply-To: <1131661106.277887.308690@z14g2000cwz.googlegroups.com> References: <1131661106.277887.308690@z14g2000cwz.googlegroups.com> Message-ID: Bilgehan.Balban at gmail.com wrote: > A simple question - Is it common/good practice to test C code using > Python? For example one could wrap individual C functions, and test > each of them using python, maybe not for low-level things but at least > for algorithmic correctness. Anyone effectively doing this as common > practice? I doubt this is common practice (in general), but at a previous company we developed a tool that let us write tests in Python, which would then call into C code which was executing in the form of object code (in an S19 file) running inside a simulated microcontroller CPU (68HC12) which was itself implemented in Python. I realize that doesn't help you, but I just thought I'd mention it, because it was a heck of a lot of fun writing it. :-) -Peter From cito at online.de Mon Nov 28 17:54:54 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 28 Nov 2005 23:54:54 +0100 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Fredrik Lundh schrieb: > Christoph Zwerschke wrote: > >>What about design goals such as: >> >>- orthogonality >>- coherence, consistency >>- principle of least astonishment ("Python fits my brain") >>- simplicity ("kiss" principle) >>- aesthetics, symmetry >> >>Actually, which priority have the above design goals for Python? Are >>other design goals considered more important? > - A Foolish Consistency is the Hobgoblin of Little Minds > - Hypergeneralization Sucks Ok, these are nice aphorisms with some truth. But I had to think of the German excuse "Wer Ordnung h?lt ist nur zu Faul zum Suchen - ein Genie ?berblickt das Chaos." ("Those who try to keep things tidy are just too lazy to search for searching - a genius surveys the chaos"). They remind you that consistency - as every good goal - can be overemphasized and exaggerated on the cost of other good goals, but otherwise they have little wisdom in the realm of programming. In the original context (http://www.emersoncentral.com/selfreliance.htm) and IIUC, the meaning of the "foolish consistency" aphorism is: "A great mind will not stupidly think/work consistently from one day to the next, but is able to throw away beloved ideas, beliefs, habits, styles etc. if he/she finds something that is better, more true or more appropriate under changed circumstances." Try to transfer this to programming languages: "A great programming language does not have to function consistently from one version to the next, you can completely throw away a well-established syntax if you find something better." I think this would not really be desirable. Another problem I have with that aphorisms applied to Python is that it has some undertone of "Python is only intended to be used by great minds" and making it usable and understandable for "little minds" is no design goal at all. That would be a very arrogant and elitarian view. Little minds like me should be able to say "Python fits my brain" just as great minds. Even kids can understand Python (there's a Germany book "Python for Kids", http://www.way2python.de/pythonbuch/kids.html) and I think i's not disqualifying Python as a "toy language", but I consider it rather a strength of Python. Ok, there is even a book "C++ for kids", but I think in reality it is intended for adult beginners... Most of all, such solgans do not explain *when* consistency is to be considered foolish and when it is wise. Are those who suggest changes in order to make Python more consistent with itself foolish or are those foolish who reject this, saying that "Python has always been like that, nobody has cared in the past and we want to stay compatible". This could be also considered a "foolish consistency". A programming language is not a "work of art". If you are an artist, you may break symmetry and introduce all kinds of unexpected effects. Actually, as an artist, you purposfully want to provoke astonishment. But if I am using a programming language or a user interface, I don't want to be confronted with inconsistent behavior. Here, the "principle of least astonishment" is much more helpful (in my little mind's humble optionion). -- Christoph From samrobertsmith at gmail.com Sat Nov 12 07:00:56 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 04:00:56 -0800 Subject: about widget construction kit In-Reply-To: References: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com> <1d987df30511111400m19f02d25had206df638c1bc0a@mail.gmail.com> <1131753997.446010.167410@f14g2000cwb.googlegroups.com> <1d987df30511111632l350105bbo51e2f9620a156793@mail.gmail.com> Message-ID: <1d987df30511120400t20344394x4aa6fea4a5f7078f@mail.gmail.com> On 11/12/05, Fredrik Lundh wrote: > Shi Mu wrote: > > > I tried again and got the follwoing message: > > *** cannot find Tcl/Tk headers and library files > > change the TCL_ROOT variable in the setup.py file > > but i have already installed TCL under python23 > > hmm. I still think it would be easier if you used a prebuilt version, like > everyone else. > > (if you insist on using an old source release instead of the latest binaries, > follow the instructions, and make sure the TCL_ROOT variable points to > the location of the Tcl/Tk development libraries (the directory that con- > tains Tcl's "include" and "lib" directories, that is)) what is Tcl/Tk development libraries? I have a tcl folder under c:\python23. Is that what you mean? Regards, From steve at REMOVETHIScyber.com.au Sat Nov 12 00:13:17 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 12 Nov 2005 16:13:17 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <1h5ty4g.1onzjda6fc7xmN%aleax@mail.comcast.net> Message-ID: On Thu, 10 Nov 2005 21:41:52 -0800, Alex Martelli wrote: >> Obfuscation has it's place. > > What I think of this thesis is on a par of what I think of this way of > spelling the possessive adjective "its" (and equally unprintable in > polite company). Aside: given that "it's" is "it is", how would you spell the possessive case of it? > If I could choose to eradicate only one of these two > from the world, I'd opt for the spelling -- the widespread and totally > unfounded belief in the worth of obfuscation is also damaging, but less > so, since it only steals some time and energy from developers who (if > they share this belief) can't be all that good anyway;-). Not that I disagree with you about obfuscation in general, but I can think of one particular usage case for obfuscation which is neither useless nor morally suspect: "Now listen carefully class, your homework for this week is to write a program to blurgle a frobnitz. As a test of correctness, your program must return the same results as the test function blurglise. Before you get any clever ideas of copying the code from blurglise, keep in mind firstly that the source code is obfuscated, and secondly that I am not an idiot, I will recognise my own code if you try to pass it off as yours." -- Steven. From steven.bethard at gmail.com Fri Nov 18 11:22:24 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 18 Nov 2005 09:22:24 -0700 Subject: How to convert a "long in a string" to a "long"? In-Reply-To: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> References: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> Message-ID: ondekoza at gmail.com wrote: >>>>0xffffffffL > > 4294967295L > > OK, this is what I want, so I tried > > s = long("0xffffffffL") > ValueError: invalid literal for long(): 0xffffffffL >>> int("0xffffffff", 0) 4294967295L STeVe From PPNTWIMBXFFC at spammotel.com Fri Nov 4 06:01:30 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Fri, 04 Nov 2005 12:01:30 +0100 Subject: Python and Lotus Notes References: <1130941469.353649.195200@g14g2000cwa.googlegroups.com> Message-ID: The second line of your code is already a show stopper in my case: from win32com.client import Dispatch session = Dispatch('Lotus.NotesSession') session.Initialize('my_secret_passwort') When started, ends: File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\temp\notes_init.py", line 3, in ? session.Initialize('my_secret_passwort') File "c:\Python24\lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: Lotus.NotesSession.Initialize It worked before though with Version 5.x of Notes. In Notes Version 6.X they introduced the session.Initialize() - that was the point, when I couldn't create an instance anymore. I found no hint on the net... Do you have any idea what is going wrong here? Regards, Marco From fredrik at pythonware.com Tue Nov 22 13:03:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 19:03:08 +0100 Subject: Why are there no ordered dictionaries? References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com><1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net><1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net><1132652504.327803.154790@g49g2000cwa.googlegroups.com><9smdnVdh0oNCkh7eRVn-uw@speakeasy.net><11o6hr7s4886720@corp.supernews.com> <11o6m49sq9vpi75@corp.supernews.com> Message-ID: Stuart McGraw wrote: > Hmm, so two versions means one is a development version, > and the other is a stable version? I did not know that, and did > not see it documented on the site. I would say documenting > that would be an interface improvement. well, that's up to the developer. when you upload a new version, all older ones are automagically hidden. the only way to make old versions appear again is to "unhide" them via a web form. for the few packages I sampled, the older versions were stable, and the latest one was "less stable", but I didn't check all of the... > I still think it would be better to have just a package name > (with current version) listed in the index page(s), and have alternate > versions (old, alpha testing, etc) listed on the package's description > page. agreed. a "nonstable"-property in the setup file would be nice too (so that stable versions don't disappear when you upload an alpha or beta...) From eurleif at ecritters.biz Thu Nov 10 06:18:49 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 10 Nov 2005 11:18:49 GMT Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <1131620733.240589.296510@g14g2000cwa.googlegroups.com> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131595096.310029.98740@g43g2000cwa.googlegroups.com> <1131596283.073069.165700@g43g2000cwa.googlegroups.com> <1131620733.240589.296510@g14g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Leif K-Brooks wrote: > >>bonono at gmail.com wrote: >> >>>thanks. that is what I am doing now, in a more generic form : >>> >>>takewhile(p, (x for x in xrange(100000000))) >> >>How does a useless generator expression make it more generic? > > xrange is only picked as an example. I may be newbie on python but not > that dumb if all I want is a list of integer(sorted) that meets certain > criteria. > > takewhile(p, (x for x in > some_function_that_could_potentially_generate_a_long_list_of_elements_but_first_element_that_meets_the_condition_can_come_fast(*args,**kwargs))) Wrapping a function in a generator expression doesn't magically make it lazily evaluated. The whole list has to be generated and returned; using a generator expression instead of a list comprehension just means that it doesn't need to be copied in memory. From cjw at sympatico.ca Wed Nov 9 08:38:35 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 09 Nov 2005 08:38:35 -0500 Subject: Diff. between Class types and classic classes In-Reply-To: <437146a3$0$19243$626a54ce@news.free.fr> References: <1131454786.272355.314740@z14g2000cwz.googlegroups.com> <4370ba00$0$7529$626a14ce@news.free.fr> <437146a3$0$19243$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Colin J. Williams a ?crit : > >> bruno at modulix wrote: >> >>> venk wrote: >>> >>>> Hi, >>>> can some one properly explain the differences between class types and >>>> classic classes? ... Still face problems in identifying what is what. >>> >>> >>> >>> >>> I'm not sure I understand your question. Are you talking about the diff >>> between old-style and new-style classes, or the diff between classes and >>> metaclasses ? >>> >> "new" classes inherit from object. Classic classes do not. > > (snip) > >> >> I hope that this helps. > > > Colin, > > I don't personaly need much help with this !-) In fact, your answer is > almost the same as the one I was going to post - before I re-read the > OP's question. And I'm still not sure that what the OP is looking for. > > Bruno, Sorry, my reponse should have been addressed to venk. Colin W From saint.infidel at gmail.com Mon Nov 7 08:58:22 2005 From: saint.infidel at gmail.com (infidel) Date: 7 Nov 2005 05:58:22 -0800 Subject: Python and PL/SQL In-Reply-To: <1131369305.252487.30220@o13g2000cwo.googlegroups.com> References: <1131369305.252487.30220@o13g2000cwo.googlegroups.com> Message-ID: <1131371902.061620.295920@g49g2000cwa.googlegroups.com> vb_bv wrote: > Does Pyton PL/SQL programming language of Oracle support? > > Thx PL/SQL is only supported *inside* Oracle databases. Python can be used to call PL/SQL procedures (I recommend the cx_Oracle module), but you can't run Python inside the database like PL/SQL. From cito at online.de Tue Nov 29 17:18:34 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 29 Nov 2005 23:18:34 +0100 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > on the other hand, it's also possible that there are perfectly usable ways > to keep bikes and bike seats dry where Christoph works, but that he prefers > not to use them because they're violating some design rule. Depends on how you understand "perfectly usable." My collegue always carries his expensive racing bike to our office in the 3rd floor out of fear it may get wet or stolen. But I think this is not very convenient and I want to avoid discussions with our boss about skid marks on the carpet and things like that. Probably that collegue would not complain as well if he had to cast tuples to lists for counting items - you see, people are different ;-) -- Christoph From http Wed Nov 30 01:04:50 2005 From: http (Paul Rubin) Date: 29 Nov 2005 22:04:50 -0800 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: <7xoe42pt6l.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Then probably the best licence to use is just to follow the lead of > Python. For that sort of small program of limited value, I put something > like this in the code: > > Copyright (c) 2005 Steven D'Aprano. > Released under the same license as used by Python 2.3.2 itself. I've done that too, but some other post mentions that the Python license is written specifically for Python and can't be used as a "subroutine". The original GNU Emacs license (forerunner of the GPL) was the same way: it said stuff like "you may distribute copies of Emacs if..." instead of "you may distribute copies of this program if...". The GPL was the result of abstracting the Emacs license so it could be applied to other programs, but doing the abstraction took considerable thought. It wasn't just a matter of patching up stuff like the above. > I am not a lawyer and this is not legal advice, but I suggest that your > *only* defence will be to get your employer to sign a legal agreement > acknowledging that you own the code. If you like, offer them a perpetual > royalty-free non-exclusive licence to use the code, and explain how using > your own code will make you more productive in their time. They may want to use it in a closed source product (GPL-incompatible) which means in the case of GPL code, they want an exception to the GPL. In the case of GPL code written by me, I'm generally unwilling to grant such exceptions, since part of my purpose of using the GPL is to attract other contributors. The company then has to decide, either: a) accept the GPL; b) don't use the code, and do something else instead, which may end up costing more. > If they refuse, then you must absolutely keep a cast-iron barrier between > what you develop in your own time and what you develop in theirs. In some jurisdictions even such a cast-iron barrier might not be enough. > Unless you explicitly sign them away (and even that is legally dubious) > you still retain the "moral rights" to the code, The US doesn't recognize "moral rights". > Please note that merely putting the code under a GPL or other OSS licence > is NOT sufficient -- they must agree to let you DISTRIBUTE the code. If it's under the GPL, they're not allowed to prevent you from distributing it, if you have a copy. > It need not be a complicated agreement: Certainly, the best policy is to discuss things beforehand and write out an agreement, instead of relying on faulty memory, or springing surprises. From dbronner at gmail.com Tue Nov 22 18:15:32 2005 From: dbronner at gmail.com (Dave Bronner) Date: 22 Nov 2005 15:15:32 -0800 Subject: Profiling from embedded C [newbie] Message-ID: <1132701332.947340.130550@g49g2000cwa.googlegroups.com> Hi all, I'm trying to profile a large collection of scripts called from a wrapper C program through the following call: compiled_obj = CompilePythonFile(filename); ... PyObject* result = PyEval_EvalCode(compiled_obj, globals, globals); Is there an easy way to wrap/edit these calls so that they invoke the python profiler module? I'm pretty new to python, so specific examples or links to docs would be much appreciated. Thanks, Dave From twic at urchin.earth.li Fri Nov 25 22:09:48 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 26 Nov 2005 03:09:48 +0000 Subject: Yet another ordered dictionary implementation Message-ID: What up yalls, Since i've been giving it all that all over the ordered dictionary thread lately, i thought i should put my fingers where my mouth is and write one myself: http://urchin.earth.li/~twic/odict.py It's nothing fancy, but it does what i think is right. The big thing that i'm not happy with is the order list (what Larosa and Foord call 'sequence', i call 'order', just to be a pain); this is a list of keys, which for many purposes is ideal, but does mean that there are things you might want to do with the order that you can't do with normal python idioms. For example, say we wanted to move the last item in the order to be first; if this was a normal list, we'd say: od.order.insert(0, od.order.pop()) But we can't do that here - the argument to the insert is just a key, so there isn't enough information to make an entry in the dict. To make up for this, i've added move and swap methods on the list, but this still isn't idiomatic. In order to have idiomatic order manipulation, i think we need to make the order list a list of items - that is, (key, value) pairs. Then, there's enough information in the results of a pop to support an insert. This also allows us to implement the various other mutator methods on the order lists that i've had to rub out in my code. However, this does seem somehow icky to me. I can't quite put my finger on it, but it seems to violate Once And Only Once. Also, even though the above idiom becomes possible, it leads to futile remove-reinsert cycles in the dict bit, which it would be nice to avoid. Thoughts? tom -- I content myself with the Speculative part [...], I care not for the Practick. I seldom bring any thing to use, 'tis not my way. Knowledge is my ultimate end. -- Sir Nicholas Gimcrack From rnd at onego.ru Thu Nov 3 01:07:02 2005 From: rnd at onego.ru (Roman Suzi) Date: Thu, 3 Nov 2005 08:07:02 +0200 (EET) Subject: XML DOM: XML/XHTML inside a text node In-Reply-To: <1130994355.266863.264890@g14g2000cwa.googlegroups.com> References: <1130994355.266863.264890@g14g2000cwa.googlegroups.com> Message-ID: On Thu, 2 Nov 2005 noahlt at gmail.com wrote: > In my program, I get input from the user and insert it into an XHTML > document. Sometimes, this input will contain XHTML, but since I'm > inserting it as a text node, xml.dom.minidom escapes the angle brackets > ('<' becomes '<', '>' becomes '>'). I want to be able to > override this behavior cleanly. I know I could pipe the input through > a SAX parser and create nodes to insert into the tree, but that seems > kind of messy. Is there a better way? What about parsing the input into XML first? Is there any point in including unescaped code into XML document unless it is XML itself? > Thanks. > > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From pwatson at redlinepy.com Tue Nov 15 11:10:12 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 15 Nov 2005 10:10:12 -0600 Subject: Is Python worth it?? In-Reply-To: References: <20051114225249.89689.qmail@web35901.mail.mud.yahoo.com> Message-ID: <3tufj5Fucte5U1@individual.net> Simon Brunning wrote: > On 14/11/05, john boy wrote: > >>I have started out trying to learn Python for my first programming language. >> I am starting off with the book "how to think like a computer scientist." >>I spend about 4-5 hrs a day trying to learn this stuff. It is certainly no >>easy task. I've been at it for about 1-2 weeks now and have a very >>elementary picture of how Python works. I am teaching myself from home and >>only recieve help from this forum. Can anybody give me a timeframe as to >>how long it usually takes to pick something like this up, so I can maybe >>figure out a way to pace myself? I can dedicate a good amount of time to it >>everyday. Any advice on what is the best way to learn Python? I am a >>fairly educated individual with a natural sciences degree (forestry), so I >>also have a decent math background. Are there any constraints >>mathematically or logic "wise" that would prevent me from building a firm >>grasp of this language? > > > Keep at it. > > Everyone is different, so don't worry about how long it takes you vs. > how long others might take. If you have no programming background, > there's a lot to learn. Using Python is a good choice, I think, 'cos > it gets a lot of extranious crud that many other languages insist on > out of your way, but there's still a lot to learn. > > The best way to learn? Go through the tutorials - but if you get an > idea for a mini-project of your own, don't be afraid to dive off and > give it a go. Try to solve you own problems for a while, 'cos that's a > valuable skill, but don't get to the point of frustration. Ask for > help here or on the tutor mailing list[1]. > > And have fun. > > [1] http://mail.python.org/mailman/listinfo/tutor > > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ Python is a great choice for a first language. I agree with the tutorial recommendations of others. I would suggest that you focus on getting out of it what you want out of it. Get some data about rainfall and correlate it with regional fires, economic output, or religious practices. That will get you reading data, calculating, and writing output. Read more code than you write. Download the Python sources and unpackage them on your machine. You do not have to build the executable. Lot's of the Python library functions are written in Python. Try to explain what the code is doing. If you do not yet understand (after applying due diligence and using Google), then ask questions. Questions are good. Questions are our friend. Write as much code as you can. Get comfortable with a debugger where you can watch the action happen. There are many fundamental computer concepts such as memory, storage, persistence, threading, and all that. Do not worry about understanding these in the first few weeks. Focus on getting out of it something that you want. Understanding the concepts will come to you as you are a practitioner. From smithsm at samuelsmith.org Tue Nov 15 17:15:32 2005 From: smithsm at samuelsmith.org (Samuel M. Smith) Date: Tue, 15 Nov 2005 15:15:32 -0700 Subject: Configure failing why? Message-ID: I am trying to build python2.4.2 on an arm 9 running Debian 3 Sarge when I run ./configure it fails with ./configure checking MACHDEP... linux2 checking EXTRAPLATDIR... checking for --without-gcc... no checking for --with-cxx=... no checking for c++... c++ checking for C++ compiler default output file name... a.out checking whether the C++ compiler works... configure: error: cannot run C++ compiled pro grams. If you meant to cross compile, use `--host'. See `config.log' for more details. Inside config.log I find checking for C++ compiler default output file name configure:1782: c++ conftest.cc >&5 configure:1785: $? = 0 configure:1831: result: a.out configure:1836: checking whether the C++ compiler works configure:1842: ./a.out ./configure: line 1: ./a.out: Permission denied configure:1845: $? = 126 configure:1854: error: cannot run C++ compiled programs. If you meant to cross compile, use `--host'. See `config.log' for more details. It appears that for some reason the a.out file that the configure script is making is not getting execute permissions enable by the configure script I have build python 2.4.2 successfully on Debian 2 and never had this problem Any ideas why this is happening? ********************************************************************** Samuel M. Smith Ph.D. 2966 Fort Hill Road Eagle Mountain, Utah 84043 801-768-2768 voice 801-768-2769 fax ********************************************************************** "The greatest source of failure and unhappiness in the world is giving up what we want most for what we want at the moment" ********************************************************************** From homeusenet2 at brianhv.org Thu Nov 24 18:06:03 2005 From: homeusenet2 at brianhv.org (Brian Victor) Date: Thu, 24 Nov 2005 23:06:03 GMT Subject: python gui using boa References: <1132637738.473190.311620@g43g2000cwa.googlegroups.com> <1132771693.777165.63860@g43g2000cwa.googlegroups.com> <1132863202.952590.33290@g14g2000cwa.googlegroups.com> Message-ID: ash wrote: > I have another query for you - how can i make a captionless frame > draggable in wxWindows? If you look at the wxPython demo, there's a Shaped Window demo under Miscellaneous that does this. The key portion is on line 86 in my version: #v+ def OnMouseMove(self, evt): if evt.Dragging() and evt.LeftIsDown(): x, y = self.ClientToScreen(evt.GetPosition()) fp = (x - self.delta[0], y - self.delta[1]) self.Move(fp) #v- -- Brian From baudelaire_2c at yahoo.fr Fri Nov 4 11:56:52 2005 From: baudelaire_2c at yahoo.fr (N. Pourcelot) Date: Fri, 04 Nov 2005 17:56:52 +0100 Subject: how to open a windows folder? In-Reply-To: References: Message-ID: <436b92c9$0$21243$626a54ce@news.free.fr> With module os, you may execute some files. something like : os.execl("explorer.exe", *arg) (syntax ?) you sould also be able to send some command to console. Bell, Kevin wrote: > I'd love to be able to open up a windows folder, like c:\temp, so that > it pops up visually. I know how to drill down into a directory, but I > can't figure out how to open one up on screen. Would I have to make a > call to windows explorer in a similar way that I hit Excel with: > > from win32com.client import Dispatch > Excel = Dispatch("Excel.Application") > > Any clues? > From steve at REMOVETHIScyber.com.au Wed Nov 16 17:24:14 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 17 Nov 2005 09:24:14 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> Message-ID: On Wed, 16 Nov 2005 13:25:50 -0800, The Eternal Squire wrote: > The teaching of legality and ethics of incorporating > other peoples' works into one's own should begin at 6th grade and be > repeated every year until the message is driven home. I think you have that completely backwards. Sixth graders have an intuitive understanding of the economics and morality of using "things" that adults these days rarely have. Material things, objects, are scarce resources and cannot be taken with impunity. If I take your black crayon, then you have one less black crayon. Non-material things, ideas, are not scarce resources. If I take your idea of writing programs in a high-level language like Python instead of using machine code, you still have the idea and we are both better off. > The concept of intellectual property (patent, copyright, trade secret) > is an extension into the business world of issues regarding the proper > usage of ideas (e.g. scientific principles) as treated in high school > and college. Nonsense. Patents, copyrights and trade secrets are completely and utterly opposed to proper scientific principles. Alchemists and magicians tried to monopolise their knowledge. Scientists share. The proliferation of patents in the medical industry is *hurting*, not helping, medical research: scientists are reluctant to publish knowledge, or are prohibited by their employer, and the cost of doing basic research is sky-rocketing due to the need to pay licence fees. This is especially obscene when one realises that in the US 80% of the scientific research that gets patented by private companies is paid for by tax payer dollars. Your taxes pay for the science which then gets given on a silver platter to some private company who collects monopoly rents on that knowledge for 20 years. It is a nice scam if you can get away with it, and the pharmaceutical companies have got away with it. >>Do developers, when writing code consider how protected their >>code will be when considering what language they will write it in >>i.e ease of use, speed of language, maintainability and >>'obfuscatability' ? > > Typically not due to a few well-known principles: 1) Essentially an > optimized (not debug!) compilation from source code to machine language > is nearly as good as encryption for hindering reverse engineering of > the distributed code, That is utterly wrong. Reverse engineering of even optimized code is relatively easy. That is one of the big myths that plague the IT industry: "if I don't release the source code, nobody will be able to work out how my code works". It just doesn't work that way. Just ask the people working on the WINE project, who have a working, almost complete, bug-for-bug compatible reverse-engineered Windows emulator, and they've done it in their spare time. Or ask the virus writers, who often find bugs and buffer over-flows and other security holes in software before the guys with the source code find them. Reverse engineering object code is harder than reading source, but it is still not a barrier to anyone serious about working out how your code works. [snip] > The greatest theft of sales opportunities Listen to yourself. "The greatest theft of SALES OPPORTUNITIES". What is that supposed to mean? Not theft of goods, not even theft of ideas, but the theft of an opportunity to make a sale? "I might have been able to sell to that person, but now I can't, it's YOUR FAULT... I'm going to sue!!!" The greatest "theft" of sales opportunities is COMPETITION, not copying. If every food store and restaurant in the country shut down except McDonalds, then they would have all the sales opportunities anyone would ever want. Every store that competes with them is "stealing" the opportunity to make a sale. We've already seen this way of thinking. Listen to Jamie Kellner, chairman and CEO of Turner Broadcasting System: "Any time you skip a commercial you're actually stealing the programming." Listen to the arrogance: "I guess there's a certain amount of tolerance for going to the bathroom." We need a permission slip from the television stations to go to the toilet? Heaven forbid we turn the machine off, that's theft of sales opportunities. Perhaps somebody should remind these folks, we're not the customer. We're the product they are selling: they sell our eyeballs to advertisers, who give them money for the opportunity to be seen by us. If we choose to skip the commercials, that's just too bad for Jamie Kellner's business model. > Ourselves > and our children are lost generations with respect to ethics, manners, > and respect for authority, perhaps we can train our grandchildren to > behave more proprely. There is too much respect for so-called "authority", not too little. Respect for authority is just another way of saying "Don't think for yourself, do as you're told." -- Steven. From http Sat Nov 5 20:12:12 2005 From: http (Paul Rubin) Date: 05 Nov 2005 17:12:12 -0800 Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> Message-ID: <7x4q6q7f6b.fsf@ruckus.brouhaha.com> Mike Meyer writes: > The thing is, the library documentation that Xah Lee is complaining > about is a *reference document*. It says so right in the title: > "Python Library Reference". As such, it makes lousy tutorial > documentation. I'm not sure which particular library Xah Lee was complaining about but lots of the lib docs are awful even as references. > The Python Cookbook should show up a lot in this search. If other > people are providing tutorial documentation, then it's not at clear > that the PSF should be duplicating that effort. It seems to me that since the PSF is so persnickety about code licenses (and that is a good thing), it should be persnickety about documentation licenses too. Lots of FSF documentation projects were undertaken because while there were good docs in existence for whatever it was, there were none that the FSF could include in its distros. It's similarly not so great if Python users have to rely on proprietary docs. Of course the PSF has to prioritize its tasks and some things will necessarily stay far down on the "list" for quite a while, but they should at least BE on the list. From prolibertine at gmail.com Sun Nov 13 09:04:49 2005 From: prolibertine at gmail.com (prolibertine at gmail.com) Date: 13 Nov 2005 06:04:49 -0800 Subject: want some python ide Message-ID: <1131890689.729009.63430@g14g2000cwa.googlegroups.com> i want some python ide use pygtk eric3 is good for me ,but i like gtk,so i want some pygtk ide look like eric3 wing is a good python ide,but i can not download it some other python ide(must use pygtk) thx From fredrik at pythonware.com Wed Nov 16 03:53:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 09:53:28 +0100 Subject: how to bypass firewall References: <1132107044.271546.185330@g43g2000cwa.googlegroups.com> <25ield.ci.ln@lightning.itga.com.au> Message-ID: Gregory Bond wrote: > I need help getting my college degree. I downloaded a hack to bypass > the college internet firewall and the college system admins found out > and I got expelled. http://www.google.com/search?q=buy+a+degree (if not else, that link will show you how many sponsored links google is willing to place on a single page...) From tauno.voipio at INVALIDiki.fi Sun Nov 6 04:10:40 2005 From: tauno.voipio at INVALIDiki.fi (Tauno Voipio) Date: Sun, 06 Nov 2005 09:10:40 GMT Subject: Can python 'read disk sectors' like/via linux:dd ? In-Reply-To: <87d5lecnm9.fsf@thalassa.informatimago.com> References: <0e2dnVNGavtaAfDenZ2dnUVZ_sydnZ2d@is.co.za> <87d5lecnm9.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon wrote: > In unix, disks are files like any other file. So if your programming > language allows you to read and write files, it allows you to read and > write disks. > > Just write the equivalent of: > > int fd=open("/dev/hda",O_RDWR,0); > if(0<==fd){ > check_errors(lseek(fd,SECT_SIZE*sect_num,SEEK_SET)); > check_errors(read(fd,buffer,SECT_SIZE)); > modify(buffer); > check_errors(lseek(fd,SECT_SIZE*sect_num,SEEK_SET)); > check_errors(write(fd,buffer,SECT_SIZE)); > close(fd); } > > and be sure to have the access rights on /dev/hda (and to know what > you're doing!). This means in practice that your program has to run with root rights to handle complete disks or partitions. Are you attempting to create a boot block virus? -- Tauno Voipio tauno voipio (at) iki fi From duncan.booth at invalid.invalid Thu Nov 24 04:01:57 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Nov 2005 09:01:57 GMT Subject: Why is dictionary.keys() a list and not a set? References: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> <1132803762.570118.253770@o13g2000cwo.googlegroups.com> <1132806307.326654.12130@g14g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > As for the (k,v) vs (v,k), I still don't think it is a good example. I > can always use index to access the tuple elements and most other > functions expect the first element to be the key. For example : > > a=d.items() > do something about a > b = dict(a) > > But using the imaginary example : > > a = zip(d.values(), d.keys()) > do something about a > b = dict(a) # probably not what I want. > The typical use case for the (v,k) tuple would be when you want sort the contents of a dictionary by value. e.g. counting the number of occurrences of each word in a document. a = zip(d.values(), d.keys()) a.sort() a.reverse() print "Today's top 10:" print str.join(',', [ k for (v,k) in a[:10]]) Ok, so today you can do that another way, but before there was a key parameter to sort you had to build the tuple somehow: print str.join(',', sorted(a.iterkeys(), key=a.__getitem__, reverse=True)[:10]) and the advantage of the latter is of course that it works even when you've been counting the number of occurences of complex numbers in a document :) From fredrik at pythonware.com Mon Nov 21 05:37:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Nov 2005 11:37:22 +0100 Subject: unittest can not use function name 'test' ? References: <1132568536.218071.81160@z14g2000cwz.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > I found something strange in my unittest : > This code is ok (will report error ): > > class MyTest1(unittest.TestCase): > > def runTest(self): > self.assertEqual(2,3) > pass > > if __name__ == '__main__': > unittest.main() > > But if I add a function with the first name is 'test' it fails to > recognize the error: > > class MyTest1(unittest.TestCase): > def test1(self): > pass > > def runTest(self): > self.assertEqual(2,3) > pass > > if __name__ == '__main__': > unittest.main() the runTest() method is a fallback, and is only used if you don't have any test*() methods in your test case. see e.g. http://docs.python.org/lib/organizing-tests.html From andreas.lobinger at netsurf.de Tue Nov 8 04:06:43 2005 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Tue, 08 Nov 2005 10:06:43 +0100 Subject: Addressing the last element of a list In-Reply-To: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> Message-ID: Aloha, pinkfloydhomer at gmail.com wrote: > Isn't there an easier way than > lst[len(lst) - 1] = ... lst[-1] = ... Wishing a happy day LOBI From edcjones at comcast.net Sat Nov 12 15:14:06 2005 From: edcjones at comcast.net (Edward C. Jones) Date: Sat, 12 Nov 2005 15:14:06 -0500 Subject: Problem with __str__ if baseclass is list Message-ID: <-dSdnSvs0ueX0OveRVn-sw@comcast.com> #! /usr/bin/env python class A(list): def __init__(self, alist, n): list.__init__(self, alist) self.n = n def __str__(self): return 'AS(%s, %i)' % (list.__str__(self), self.n) def __repr__(self): return 'AR(%s, %i)' % (list.__repr__(self), self.n) a = A(['x', 'y'], 7) print 1, a print 2, repr(a) print 3, list.__str__(a) print 4, list.__repr__(a) """ The output is: 1 AS(AR(['x', 'y'], 7), 7) 2 AR(['x', 'y'], 7) 3 AR(['x', 'y'], 7) 4 ['x', 'y'] Why is list.__str__(a) == "AR(['x', 'y'], 7)"? Note: The problem goes away if "list.__str__(a)" is replaced with "list.__repr__(self)". """ From apardon at forel.vub.ac.be Mon Nov 7 03:55:06 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 08:55:06 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <7xpsphlxri.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-11-04, Steven D'Aprano schreef : > On Fri, 04 Nov 2005 08:08:42 +0000, Antoon Pardon wrote: > >> One other way, to implement the += and likewise operators would be >> something like the following. >> >> Assume a getnsattr, which would work like getattr, but would also >> return the namespace where the name was found. The implementation >> of b.a += 2 could then be something like: >> >> ns, t = getnsattr(b, 'a') >> t = t + 2 >> setattr(ns, 'a') >> >> >> I'm not arguing that this is how it should be implemented. Just >> showing the implication doesn't follow. > > Follow the logical implications of this proposed behaviour. > > class Game: > current_level = 1 > # by default, games start at level one > > def advance(self): > self.current_level += 1 > > > py> antoon_game = Game() > py> steve_game = Game() > py> steve_game.advance() > py> steve_game.advance() > py> print steve_game.level > 3 > py> print antoon_game.level > > What will it print? > > Hint: your scheme means that class attributes mask instance attributes. So? This proposal was not meant to replace the current behaviour. It was meant to contradict your assertion that some particular behaviour implied mutable numbers. My proposal was an example that showed the particular behaviour and didn't require mutable numbers, so it showed your assertion false. -- Antoon Pardon From mwm at mired.org Tue Nov 22 18:49:03 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 22 Nov 2005 18:49:03 -0500 Subject: about sort and dictionary References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> Message-ID: <86y83g1bww.fsf@bhuda.mired.org> rurpy at yahoo.com writes: > I think this is just another (admittedly minor) case of Python's > designers using Python to enforce some idea of programming > style purity. You say that as if it were a bad thing. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fuzzyman at gmail.com Thu Nov 10 07:56:00 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 10 Nov 2005 04:56:00 -0800 Subject: Python as a HTTP Client In-Reply-To: <1131626985.808470.308450@g47g2000cwa.googlegroups.com> References: <1131626985.808470.308450@g47g2000cwa.googlegroups.com> Message-ID: <1131627360.085800.181260@f14g2000cwb.googlegroups.com> ``urllib2`` is the standard library module you need. I've written a guide to using it (although it's very easy - but some attributes of the errors it can raise aren't documented) : http://www.voidspace.org.uk/python/articles/urllib2.shtml All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From tim.tadh at gmail.com Sun Nov 27 23:35:03 2005 From: tim.tadh at gmail.com (Tim Henderson) Date: Sun, 27 Nov 2005 23:35:03 -0500 Subject: should python have a sort list-map object in the std-lib? Message-ID: <47f7cc780511272035w42c86419t72eba6c07c14fc43@mail.gmail.com> Hi The question why are there no sorted dictionaries in python, seems to pop up with unseeming regularity. That question in itself in nonsensical sense dictionaries are hash-maps, however should python have a sorted map type object is a good question. clearly many people like have a sorted map, and sorting the keys every time seems rather wasteful, as does keeping a separate sorted list of the keys. a related question is, in python is it more efficient to a maintain a list type in sorted order by inserting each new object in the correct location (by say finding it with a binary search and then using del list[x]) or appending each new item to the end of said list and using the built-in .sort method, or sorted() function? -- Tim Henderson mail me: tim.tadh at gmail.com From michele.simionato at gmail.com Fri Nov 4 03:26:35 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 4 Nov 2005 00:26:35 -0800 Subject: Web automation with twill In-Reply-To: <1130966536.697459.250700@g49g2000cwa.googlegroups.com> References: <1130934838.388039.297650@o13g2000cwo.googlegroups.com> <1130945598.627911.264390@g49g2000cwa.googlegroups.com> <1130966536.697459.250700@g49g2000cwa.googlegroups.com> Message-ID: <1131092795.953963.297990@g14g2000cwa.googlegroups.com> BTW, O'Reilly just published an article of mines on twill: http://www.onlamp.com/pub/a/python/2005/11/03/twill.html Michele Simionato From bokr at oz.net Tue Nov 15 18:49:52 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 15 Nov 2005 23:49:52 GMT Subject: replacing multiple instances of commas beginning at specific position References: <1131990237.288604.137690@z14g2000cwz.googlegroups.com> Message-ID: <437a72b8.590582022@news.oz.net> On Tue, 15 Nov 2005 08:26:22 GMT, Dennis Lee Bieber wrote: >On 14 Nov 2005 09:43:57 -0800, "striker" declaimed >the following in comp.lang.python: > >> >> What would be the best approach to replace all instances of multiple >> commas with just one comma, except for the 4 commas prior to ADMNSRC? >> > Simplify the problem... Start by rephrasing... Since ADMNSRC is to >always have four commas leading up to it (at least, as I understand your >statement of intent), you could consider three of those to be part of >the string. So... > > Phase one: split on commas, tossing out any null fields > Phase two: replace "ADMNSRC" with ",,,ADMNSRC" > Phase three: rejoin the parts that remain. > > Doing this efficiently may be another matter but... > >data = [ "one, two, three,,,,four,,,,ADMNSRC, five,,,,six", > "one, two, three,four,,,,,,,,ADMNSRC,,,,,,eighteen, and so >on" ] > >result = [] >for ln in data: > wds = [x.strip() for x in ln.split(",") if x] > for i in range(len(wds)): > if wds[i] == "ADMNSRC": > wds[i] = ",,,ADMNSRC" > result.append(",".join(wds)) > >print result Or if data is from a single file read, maybe (untested beyond what you see ;-) >>> data = """\ ... one, two, three,,,,four,,,,ADMNSRC, five,,,,six ... one, two, three,four,,,,,,,,ADMNSRC,,,,,,eighteen, and so on ... """ >>> import re >>> rxc = re.compile(',+') >>> result = ',,,ADMNSRC'.join(','.join(rxc.split(s)) for s in data.split(',,,ADMNSRC')) >>> print result one, two, three,four,,,,ADMNSRC, five,six one, two, three,four,,,,ADMNSRC,eighteen, and so on Regards, Bengt Richter From mwm at mired.org Sat Nov 12 12:27:17 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 12 Nov 2005 12:27:17 -0500 Subject: changeing users on linux References: <1131766541.519931.313710@g44g2000cwa.googlegroups.com> <86mzka331n.fsf@bhuda.mired.org> <1131780006.243843.68360@g44g2000cwa.googlegroups.com> Message-ID: <86acg93hfu.fsf@bhuda.mired.org> darkchild50 at gmail.com writes: > the password is for loging into root The setuid call will fail unless you're already root. You can't, as some user other than root, change your userid, so the answer to the original question with the added restriction is "You can't". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mardy at users.sourceforge.net Wed Nov 30 16:03:05 2005 From: mardy at users.sourceforge.net (Mardy) Date: Wed, 30 Nov 2005 21:03:05 GMT Subject: Distutils postinstall script: useless? References: Message-ID: Le die Wed, 30 Nov 2005 15:46:43 +0000, Mardy ha scribite: > the bdist_wininst command of distutils allows me to specify a script to > be executed at the end of the installation. That's great, but how can I > know the installation path from inside the script? Answering to myself, sys.prefix combined with the dictionary INSTALL_SCHEMES from distutils.commands.install might do the work. -- Saluti, Mardy http://interlingua.altervista.org From duncan.booth at invalid.invalid Mon Nov 28 09:48:35 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Nov 2005 14:48:35 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: Antoon Pardon wrote: >> >>> def func(x): >> ... if x in [1,3,5,7,8]: >> ... print 'x is really odd' >> ... >> >>> dis.dis(func) >> ... >> 3 20 LOAD_FAST 0 (x) >> 23 LOAD_CONST 2 (1) >> 26 LOAD_CONST 3 (3) >> 29 LOAD_CONST 4 (5) >> 32 LOAD_CONST 5 (7) >> 35 LOAD_CONST 6 (8) >> 38 BUILD_LIST 5 >> 41 COMPARE_OP 6 (in) > > I'm probably missing something, but what would be the problem if this > list was created during compile time? Not much in this particular instance. 'x in aList' is implemented as aList.__contains__(x), so there isn't any easy way to get hold of the list[*] and keep a reference to it. On the other hand: def func(x): return x + [1, 3, 5, 7, 8] we could pass in an object x with an add operator which gets hold of its right hand operand and mutates it. So the problem is that we can't just turn any list used as a constant into a constant list, we need to be absolutely sure that the list is used only in a few very restricted circumstances, and since there isn't actually any benefit to using a list here rather than a tuple it hardly seems worthwhile. There might be some mileage in compiling the list as a constant and copying it before use, but you would have to do a lot of timing tests to be sure. [*] except through f.func_code.co_consts, but that doesn't count. From PPNTWIMBXFFC at spammotel.com Wed Nov 16 02:24:20 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 16 Nov 2005 08:24:20 +0100 Subject: PyExcelerator - mishandling of formulas? Message-ID: Hi, Yesterday I placed a bug report on PyExcelerators-Sourceforge-page... but I am not so sure anymore, whether this is really a bug - I could imagine that I missed something, but I don't see what. Please confirm that my bug is due to mishandling and I will gladly retreat my bug report. In a formula, I would like to point to a field on another worksheet. pyExcelerator chokes on these references! import pyExcelerator wb = pyExcelerator.Workbook() ws_summary = wb.add_sheet('Summary') ws_data = wb.add_sheet('Data') ws_summary.write(0,0, pyExcelerator.Formula('Data:A1')) <--- Here it chokes! ws_data.write(0, 0, '4000') wb.save('not_parsing.xls') Is this a bug or am I doing something wrong? Regards, Marco From codecraig at gmail.com Tue Nov 15 14:01:48 2005 From: codecraig at gmail.com (py) Date: 15 Nov 2005 11:01:48 -0800 Subject: is parameter an iterable? Message-ID: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> I have function which takes an argument. My code needs that argument to be an iterable (something i can loop over)...so I dont care if its a list, tuple, etc. So I need a way to make sure that the argument is an iterable before using it. I know I could do... def foo(inputVal): if isinstance(inputVal, (list, tuple)): for val in inputVal: # do stuff ...however I want to cover any iterable since i just need to loop over it. any suggestions? From nico-NoSp at m-tekNico.net Tue Nov 15 11:29:57 2005 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Tue, 15 Nov 2005 17:29:57 +0100 Subject: Default method arguments In-Reply-To: References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a0a1b_1@newsgate.x-privat.org> Message-ID: <437a0d0f$1_2@newsgate.x-privat.org> > Using None might be problematic if None could be a valid argument. That's like saying that NULL could be a significant value in SQL. In Python, "None" *is* the empty, not significant value, and should always be used as such. Specifically, never exchange "None" for "False". -- Nicola Larosa - nico-NoSp at m-tekNico.net ...Linux security has been better than many rivals. However, even the best systems today are totally inadequate. Saying Linux is more secure than Windows isn't really addressing the bigger issue - neither is good enough. -- Alan Cox, September 2005 From jordan at talkingpanda.com Wed Nov 30 19:41:38 2005 From: jordan at talkingpanda.com (j-rock) Date: 30 Nov 2005 16:41:38 -0800 Subject: Python Guru Needed Fast!!!! Message-ID: <1133397698.392677.236790@z14g2000cwz.googlegroups.com> Talking Panda LLC is looking for a programmer to take over building applications for the iPod. Required skills below. Please email me personally. Jordan at talkingpanda.com - Expertise in text parsing and formatting. Specifically, developing parsers to extract meaningful information from freeform text, XML, HTML, SGML, spreadsheets and translate it to other formats. - Experience with and ideally preference for Python - The creativity required to come up with solutions that work within the constraints of the iPod Note Reader (up to 1000 notes at 4kb each, limited formatting options, etc.). The following skills are also a bonus: - Tkinter and/or Win32 API programming - COM - Apple Events - PyObjC / Cocoa - Web development From steve at REMOVETHIScyber.com.au Wed Nov 16 05:59:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 16 Nov 2005 21:59:07 +1100 Subject: Default method arguments References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a1e7a$0$6131$636a15ce@news.free.fr> Message-ID: On Wed, 16 Nov 2005 09:48:47 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: >> I would like to see _marker put inside the class' scope. That prevents >> somebody from the outside scope easily passing _marker as an argument >> to instance.f. It also neatly encapsulates everything A needs within >> A. > > Surely that makes it easier for someone outside the scope to pass in > marker: > >>> instance = A(5) > >>> instance.f(instance._marker) > 5 Sure, but they have to explicitly qualify marker with the instance. If they want to do that, I'm not going to stop them. But I'm trying to avoid tempting them from doing this: instance.f(_marker) and then complain that it doesn't print _marker. In other words, I don't want to take away their ability to shoot themselves in the foot, but I want them to have to *think about it* before doing so. -- Steven. From hcslmf at texlife.com Mon Nov 21 15:36:55 2005 From: hcslmf at texlife.com (brolewis) Date: 21 Nov 2005 12:36:55 -0800 Subject: Reading a subprocesses stdout on Windows In-Reply-To: <438229c3-79118348-02d7-4123-8e51-0000df1ac063@news.szn.dk> References: <1132603718.835058.146620@z14g2000cwz.googlegroups.com> <438229c3-79118348-02d7-4123-8e51-0000df1ac063@news.szn.dk> Message-ID: <1132605415.802167.64570@g49g2000cwa.googlegroups.com> commands is Unix only. This is Windows specific From eight02645999 at yahoo.com Mon Nov 7 04:54:20 2005 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 7 Nov 2005 01:54:20 -0800 Subject: pls help me with strange result In-Reply-To: References: <1131353588.072795.320660@g14g2000cwa.googlegroups.com> Message-ID: <1131357260.616371.48470@f14g2000cwb.googlegroups.com> hi thanks! i used your method to rearrange the try,except clauses, and the problem is solved. I also redefined my funcs to get rid of the try/except clauses and leave it to the caller to do the job of try/except. From maxm at mxm.dk Thu Nov 24 08:51:24 2005 From: maxm at mxm.dk (Max M) Date: Thu, 24 Nov 2005 14:51:24 +0100 Subject: Python Midi Package: writing events non-chronologically In-Reply-To: References: Message-ID: <4385c490$0$38645$edfadb0f@dread12.news.tele.dk> tim wrote: > Someone using Python Midi Package from > http://www.mxm.dk/products/public/ lately? > > I want to do the following : > write some note events in a midi file > then after doing that, put some controllers at the beginning of the > midifile > (because I want to be able to make those dependant on what notes were > just written) > > def midctrls(): > global roffset, melchan, roffset, gmt, timedisplay, out_file, midi, > usednotes, n > midi.reset_time() #seems to do nothing > for cha in range(16): > if cha==1: > midi.abs_time=0 #seems to do nothing > midi._relative_time = 0 #seems to do nothing, but I can > imagine why > midi._absolute_time = 0 #seems to do nothing > midi.update_time(new_time=0, relative=0) #although I give > the variable relative=0 it seems to be relative ? > midi.continuous_controller(cha, 0, 122) > (snip) > > With this code I want a controller number 0 with value 122 to be written > at the beginning of my midifile. > It is written at the end, how I move the writing position to the beginning? > You should make a wrapper around the library that handles the midi events in a data structure. When your musical structure is then is complete, you use the midi library to write it to disk. I have attached a simple example here. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Notes2midi.py URL: From martin at v.loewis.de Mon Nov 28 15:13:20 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 28 Nov 2005 21:13:20 +0100 Subject: New Ordered Dictionery to Criticise In-Reply-To: <1133197857.754686.133740@g44g2000cwa.googlegroups.com> References: <1133197857.754686.133740@g44g2000cwa.googlegroups.com> Message-ID: <438b64e0$0$21049$9b622d9e@news.freenet.de> Fuzzyman wrote: > Criticism solicited (honestly) :-) A couple of minor points: - I would drop 2.2 compatibility - self=self isn't needed in the functions, because of nested scopes - popitem(self) can be rewritten as def popitem(self): try: key = self._sequence.pop() except IndexError: # always try to give the same exception string as # dict raise KeyError("popitem(): dictionary is empty") return key, self.pop(key) - One problem with the FancyDict is that it allows d.keys.append(100) Regards, Martin From kylotan at gmail.com Wed Nov 16 04:37:06 2005 From: kylotan at gmail.com (Ben Sizer) Date: 16 Nov 2005 01:37:06 -0800 Subject: Python obfuscation In-Reply-To: <86fypxr82g.fsf@bhuda.mired.org> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <86fypxr82g.fsf@bhuda.mired.org> Message-ID: <1132133826.129889.97630@g47g2000cwa.googlegroups.com> Mike Meyer wrote: > "Ben Sizer" writes: > > In my > > case, providing a free download of any lost executables or data upon > > presentation of a legitimate license key should be adequate. > > My special handling for such > things - and *especially* for entertainment software, where the media > gets handled by children - is "Return that POS." That's funny, I could have sworn that a few messages above you suggested I "Try Alex's solution, and put the data on a network server that goes through whatever authentication you want it to." Are you claiming therefore that it's more acceptable to you to have to access the data remotely every time you use the software than once per install? > Worse yet, you play > semantic games so you can claim not to be violating fair use rights in > the process. No, I am just pointing out that you are mixing up the concept of an actual 'right' such as one embodied in a state's constitution, with an implied 'right' that is just an exemption from committing an offence. The term 'right' does not even appear in the relevant part of US copyright law, except to state that it is a limitation on the copyright holder's rights. -- Ben Sizer. From pwatson at redlinepy.com Mon Nov 14 23:43:09 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Mon, 14 Nov 2005 22:43:09 -0600 Subject: Installing tkinter with Python 2.4.2 on FC4 In-Reply-To: <3to0eaFthb51U1@individual.net> References: <3to0eaFthb51U1@individual.net> Message-ID: <3tt7auFu5d71U1@individual.net> Paul Watson wrote: > I cannot yet get tkinter working on 2.4.2. I have installed the tk rpms > from FC4. I have checked to see that TKPATH is available in > Modules/Setup. > > How can I verify that I have tcl/tk installed correctly and it is the > correct version (8+)? Surely, there must be a better way to do this than what I ended up doing. Please respond so that someone will do better than I did. To get this to work, I whacked the ./Modules/Setup file references to tk things. Two lines were changed from /usr/local/* to /usr/*. The X11 lines were simply uncommented. I had to install a few more RPMs from the FC4 CDs for tk and tcl. That led to installing some more xorg-x11 RPMs. After that, ./configure; make clean; make; make test; # *** Always uncomment this (leave the leading underscore in!): _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ # *** Uncomment and edit to reflect where your Tcl/Tk libraries are: # -L/usr/local/lib \ -L/usr/lib \ # *** Uncomment and edit to reflect where your Tcl/Tk headers are: # -I/usr/local/include \ -I/usr/include \ # *** Uncomment and edit to reflect where your X11 header files are: -I/usr/X11R6/include \ # *** Or uncomment this for Solaris: # -I/usr/openwin/include \ # *** Uncomment and edit for Tix extension only: # -DWITH_TIX -ltix8.1.8.2 \ # *** Uncomment and edit for BLT extension only: # -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ # *** Uncomment and edit for PIL (TkImaging) extension only: # (See http://www.pythonware.com/products/pil/ for more info) # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ # *** Uncomment and edit for TOGL extension only: # -DWITH_TOGL togl.c \ # *** Uncomment and edit to reflect your Tcl/Tk versions: # -ltk8.2 -ltcl8.2 \ -ltk8.4 -ltcl8.4 \ # *** Uncomment and edit to reflect where your X11 libraries are: -L/usr/X11R6/lib \ # *** Or uncomment this for Solaris: # -L/usr/openwin/lib \ # *** Uncomment these for TOGL extension only: # -lGL -lGLU -lXext -lXmu \ # *** Uncomment for AIX: # -lld \ # *** Always uncomment this; X11 libraries to link with: -lX11 From steve at REMOVETHIScyber.com.au Fri Nov 4 13:29:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 05:29:23 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> <7xk6fovb1t.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 04 Nov 2005 04:42:54 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> There are good usage cases for the current inheritance behaviour. > > Can you name one? Any code that relies on it seems extremely dangerous to me. Dangerous? In what way? A basic usage case: class Paper: size = A4 def __init__(self, contents): # it makes no sense to have class contents, # so contents go straight into the instance self.contents = contents To internationalise it for the US market: Paper.size = USLetter Now create a document using the default paper size: mydocument = Paper("Four score and seven years ago") print mydocument.size == USLetter => True Now create a document using another paper size: page = Paper("Eleventy MILLION dollars") page.size = Foolscap Because that's an instance attribute, our default doesn't change: assert Paper().size == mydocument.size == USLetter assert page.size != mydocument.size In case it wasn't obvious, this is the same inheritance behaviour Python objects exhibit for methods, except that it isn't normal practice to add methods to instances dynamically. (It is more common to create a subclass.) But you can do it if you wish, at least for classes you create yourself. Objects in Python inherit behaviour from their class. Objects in Python inherit state from their class, unless their state is specifically stored in a per-instance basis. Here's another usage case: class PrintableWidget(Widget): prefix = "START " suffix = " STOP" def __str__(self): return self.prefix + Widget.__str__(self) + self.suffix PrintableWidgets now print with a default prefix and suffix, which can be easily changed on a per-instance basis without having to create sub-classes for every conceivable modification: english_gadget = PrintableWidget("data") print english_gadget => prints "START data STOP" dutch_gadget = PrintableWidget("data") dutch_gadget.prefix = "BEGIN " dutch_gadget.suffix = " EINDE" print dutch_gadget => prints "BEGIN data EINDE" I have to ask... did OO programming suddenly fall out of favour when my back was turned? People still use C++, C#, Objective-C and Java, right? Why are so many folks on this list having trouble with inheritance? Have I missed something? -- Steven. From mwm at mired.org Tue Nov 29 18:35:19 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 29 Nov 2005 18:35:19 -0500 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> <1133041306.601950.213710@g43g2000cwa.googlegroups.com> <86oe45d8rj.fsf@bhuda.mired.org> Message-ID: <86psojownc.fsf@bhuda.mired.org> "Andrew Koenig" writes: > "Mike Meyer" wrote in message > news:86oe45d8rj.fsf at bhuda.mired.org... >> Definitely not. The most recent change to the copyright laws made >> works of music recorded to fullfill a contract "work for hire" by >> default. > If there's a contract -- i.e., a written agreement, then why does it matter? The default applies if the contract doesn't say who owns the work. This was a move by the recording companies so they could get ownership of works simply by not saying who owned it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From http Fri Nov 25 17:04:58 2005 From: http (Paul Rubin) Date: 25 Nov 2005 14:04:58 -0800 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <1132841680.454026.203420@z14g2000cwz.googlegroups.com> <11ocu1og1660965@corp.supernews.com> <1132928461.261842.132720@g47g2000cwa.googlegroups.com> <11oehpnecp556df@corp.supernews.com> Message-ID: <7xfypkidth.fsf@ruckus.brouhaha.com> Ed Jensen writes: > I think free software/open source has existed long enough and with > enough varied licenses (GPL, LGPL, modified LGPL (see wxWidgets), BSD, > X11, MIT, Apache, etc.) that we'd basically know without question if > less restritive licenses (like BSD) were causing projects to fail vs. > projects that use very heavy handed licenses (like GPL). Apache and > Python are two of my favorite examples, followed by the *BSD operating > systems. Python and *BSD are getting far less volunteer development love than, say, GCC or Linux, and the licensing is at least part of the reason. Also, numerous GCC ports done by hardware companies (for their CPU's) have been released under the GPL that would definitely have been proprietary if it had been permitted. That is not speculation, it is known from discussions with those hardware companies at the time. G++ (the original C++ front end for GCC) also would have been proprietary. From simon.brunning at gmail.com Sat Nov 5 10:21:12 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Sat, 5 Nov 2005 15:21:12 +0000 Subject: Pythonwin - Word automation - Removing watermark not working In-Reply-To: <312cfe2b0511041313q6c2ba396u1d81b97089ff63e0@mail.gmail.com> References: <312cfe2b0511031655x22c866cdj8bd213d4d3be4ea7@mail.gmail.com> <312cfe2b0511041313q6c2ba396u1d81b97089ff63e0@mail.gmail.com> Message-ID: <8c7f10c60511050721r4f2b117du@mail.gmail.com> On 04/11/05, Gregory Pi?ero wrote: > Is there a different group/mailing list I should try? Does anyone know if > there is a pythonwin group/list for example? There is: . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at holdenweb.com Tue Nov 1 12:58:50 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Nov 2005 17:58:50 +0000 Subject: Python's website does a great disservice to the language In-Reply-To: References: Message-ID: <4367ACDA.9090902@holdenweb.com> CppNewB wrote: > I was trying to advocate using Python for an upcoming prototype, so my boss > went out to take a look at the documentation and try and get a feel for what > the language is all about. > > First comment; "I hope the language is designed better than the site." The > site is readable, but is amateurish. If I had an ounce of design skills in > me, I would take a stab at it. > > Maybe we could round up a couple of designers to donate some time? Maybe we > could build a basic CMS on top of Django or TurboGears (displaying Python's > capability as a web development stack)? > A redesign is complete, and should be deployed by the end of the year. In the meantime please assure your boss that the language *is* far better designed than the (current) web site, and that he shouldn't judge a bottle by its label :-) [Thinks: wonder if it's time to release a sneak preview]. 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 anthony at ataribaby.org Tue Nov 8 21:58:46 2005 From: anthony at ataribaby.org (Anthony L.) Date: Tue, 08 Nov 2005 20:58:46 -0600 Subject: Is mod_python 3.1 good for commercial blogging/CMS? References: <1131445452.395804.169860@g14g2000cwa.googlegroups.com> Message-ID: In article <1131445452.395804.169860 at g14g2000cwa.googlegroups.com>, "Ben Sizer" wrote: > Anthony L. wrote: > > 1. I want to use CGI through Publisher handler, instead of CGI handler > > or PSP. Despite the speed increase mod_python gives me, there is a > > problem of persistence that can be a problem when dealing with a site > > that will hosts potentially hundreds of simultaneous users. > > What problem? Could you elaborate further? Hi Ben. This is what I myself am trying to find out. From what I gather, hosts dislike long running processes, and so one reason for not supporting Python and mod_python is that, plus multiple instances of the python interpreter. Granted, a lot of this looks like old information combined with FUD, so I am suspicious. After all, high-traffic sites using mod_perl seem okay. > In theory, people use these templates to /improve/ the separation > between logic and presentation. When you just use req.write() you're > inevitably mixing logic and presentation. At least with the template > systems, you do the presentation once and the logic fills in the gaps. > It's even possible to edit the presentation in many WYSIWYG web editors > without affecting the code. Yes, I see your point. In this case it works for me (at the moment) because the HTML design will remain as is without subject to editing, whereas the look and feel (controlled by CSS) will be user-editable. > I don't think performance is a factor, really. HTML templates tend to > exist so that you can structure the page without worrying about the > Python code. They work well for fairly uniform pages that largely > require the same sort of data on each page. I am more of a programmer > than a designer so I prefer to think in terms of code and emit HTML as > it suits me. Okay, I might have been unfair in looking away from PSP then. Thanks Ben. Anthony From webograph at eml.cc Tue Nov 8 17:56:22 2005 From: webograph at eml.cc (webograph) Date: Tue, 08 Nov 2005 23:56:22 +0100 Subject: plugin interface / list Message-ID: hi, i'm about to write a script to play various audio files. what i want to write is a directory (module) containing wrappers around various players that supply a player object (inheriting from a general player object defined earlier) and an entry in a list of mime types (which player is for which type). i've tried various forms of import and __init__.py configurations, but i repeatedly have problems with the following steps: - create an object inheriting from the main script - fill the dictionary declared there (i guess the problem is actually the same) is there a standard way of doing such things? thanks in advance webograph From ale.of.ginger at gmail.com Wed Nov 9 07:16:19 2005 From: ale.of.ginger at gmail.com (ale.of.ginger at gmail.com) Date: 9 Nov 2005 04:16:19 -0800 Subject: Goto XY In-Reply-To: References: <1131499644.561039.16420@g14g2000cwa.googlegroups.com> <11n321mqmtudh19@corp.supernews.com> Message-ID: <1131538579.551798.68600@f14g2000cwb.googlegroups.com> OK - I added the import WConio line. But when I run import WConio print "going to x10,y10..." WConio.gotoxy(10,10) print "Done" the above, I get the following error: WConio.gotoxy(10,10) error: GetConOut Failed I installed the WConio to the ../site-packages/ folder in Python24, and when it didn't work I also moved the files in there to the /Lib/ folder where other things are like random, but that didn't seem to work either. From bedouglas at earthlink.net Mon Nov 21 10:48:27 2005 From: bedouglas at earthlink.net (bruce) Date: Mon, 21 Nov 2005 07:48:27 -0800 Subject: Any college offering Python short term course? In-Reply-To: Message-ID: <032401c5eeb3$04580080$0301a8c0@Mesa.com> hey... i'm looking for classes (advanced) in python/php in the bay area as well... actually i'm looking for the students/teachers/profs of these classes... any idea as to how to find them. calling the various schools hasn't really been that helpful. The schools/institutions haven't had a good/large selection... it appears that some of the classes are taught by adjunct/part-time faculty, and they're not that easy to get to... if anybody knows of user-groups that also have this kind of talent, i'd appreciate it as well... send responses to the list as well!!! thanks -bruce -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of arches73 Sent: Sunday, November 20, 2005 4:04 PM To: python-list at python.org Subject: Any college offering Python short term course? Hi, I want to learn Python. I appreciate if someone point me to the colleges / institutions offering any type of course in Python programming in the Bay area CA. Please send me the links to my email. Thanks, Arches -- http://mail.python.org/mailman/listinfo/python-list From x at y.z Sun Nov 13 11:27:25 2005 From: x at y.z (D H) Date: Sun, 13 Nov 2005 10:27:25 -0600 Subject: How to avoid "f.close" (no parens) bug? In-Reply-To: References: Message-ID: Carsten Haese wrote: > On Thu, 2 Nov 2006 23:56:22 +0200, o wrote > >>plez send me >> > > > Please tell us what bug you're talking about: > > A) Python closed the file but you expected it not to. > B) Python didn't close the file but you expected it to. > C) Python didn't warn you when you wrote "f.close" instead of "f.close()". > D) Something else. Please elaborate by giving us a code example, a description > of what you expected to happen, and a description of what happened instead. It is certainly B & C. It is a common issue. There is no way to avoid it unless you learn how to avoid it. Other than that, PyChecker may help find this kind of error. Over a year ago Guido said he wanted to include pychecker with python but it still hasn't happened, so you can download it from here: http://pychecker.sourceforge.net/ From bonono at gmail.com Sun Nov 20 04:59:08 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 01:59:08 -0800 Subject: what happens when the file begin read is too big for all lines to be read with "readlines()" In-Reply-To: References: <1132399371.267088.291000@g14g2000cwa.googlegroups.com> <437FFB57.6010101@gmail.com> Message-ID: <1132480748.046838.13290@f14g2000cwb.googlegroups.com> Xiao Jianfeng wrote: > First, I must say thanks to all of you. And I'm really sorry that I > didn't > describe my problem clearly. > > There are many tokens in the file, every time I find a token, I have > to get > the data on the next line and do some operation with it. It should be easy > for me to find just one token using the above method, but there are > more than > one. > > My method was: > > f_in = open('input_file', 'r') > data_all = f_in.readlines() > f_in.close() > > for i in range(len(data_all)): > line = data[i] > if token in line: > # do something with data[i + 1] > > Since my method needs to read all the file into memeory, I think it > may be not > efficient when processing very big file. > > I really appreciate all suggestions! Thanks again. > something like this : for x in fh: if not has_token(x): continue else: process(fh.next()) you can also create an iterator by iter(fh), but I don't think that is necessary using the "side effect" to your advantage. I was bite before for the iterator's side effect but for your particular apps, it becomes an advantage. From eurleif at ecritters.biz Fri Nov 4 16:35:05 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 04 Nov 2005 21:35:05 GMT Subject: How can I do this in Python? In-Reply-To: References: <1131118052.827738.235590@f14g2000cwb.googlegroups.com> <1131122051.701419.108200@g43g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Another alternative might be to serve a script that sent the browser > back 2 pages in its history, as long as server state hasn't changed in > the meantime. What about users with JavaScript disabled? From graham.fawcett at gmail.com Sat Nov 26 13:05:13 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 26 Nov 2005 10:05:13 -0800 Subject: Stealing focus: emacs, and PIL, in Windows In-Reply-To: <1132919000.250236.196090@g43g2000cwa.googlegroups.com> References: <1132919000.250236.196090@g43g2000cwa.googlegroups.com> Message-ID: <1133024923.799605.217060@g44g2000cwa.googlegroups.com> damonwischik at gmail.com wrote: > I'm using GNU Emacs 21.3.1 with python-mode 1.0alpha under Windows XP. > Whenever I execute a command in an edit window (with > py-execute-region), the output window steals the focus. How can I stop > this happening? [snip] > I commented out the command > (pop-to-buffer (current-buffer)) > and now the command window no longer steals focus. But I don't know if > this has any other side effects, or it there's a better way to prevent > focus being stolen. For someone who says he doesn't know Lisp, you seem to be doing just fine. :-) Not sure if there would be side-effects. Note that py-execute-string, py-execute-buffer, py-execute-def-or-class all use py-execute-region. Their behaviour may be altered by your change. But it would be easy to test. If you did encounter a problematic side-effect, you could define your own "py-execute-region-custom" as a copy of py-execute-region but with the (pop-to-buffer) call removed. Then use (require 'python-mode) ;; if you're putting this in .emacs (define-key py-mode-map "\C-c|" 'py-execute-region-custom) to redefine the keyboard mapping. (The (require 'python-mode) call ensures that the py-mode-map variable has been initialized.) You could provide an alternate mapping for your new function, of course. If you put the custom function and your define-key call both in your .emacs file, then you can easily port it to other machines (perh. easier than maintaining a patch for python-mode). Graham From anthony at ataribaby.org Tue Nov 8 22:34:30 2005 From: anthony at ataribaby.org (Anthony L.) Date: Tue, 08 Nov 2005 21:34:30 -0600 Subject: Is mod_python 3.1 good for commercial blogging/CMS? References: <1131445452.395804.169860@g14g2000cwa.googlegroups.com> Message-ID: In article , jjl at pobox.com (John J. Lee) wrote: > "Ben Sizer" writes: > [...] > > It as not easy to work with the CGI-style code in a WYSIWYG web editor > > as it is to edit a template, which is probably the main reason for > > their use. Also, coding everything with req.write() means that each > [...] > > You seem to believe CGI is incompatible with templating. Why? The > two are entirely independent of each other. > > > John He was just referring to the idea of me perhaps editing the HTML markup in my Python code using an IDE like Dreamweaver and having a difficult time. I agree, editing an HTML doc in a WYSIWYG environment would be easier than me fishing through my req.write() calls and my strings to find my markup - which is what I am doing at the moment. Anthony From mwm at mired.org Sat Nov 12 12:31:55 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 12 Nov 2005 12:31:55 -0500 Subject: passing values from one form to another References: <1131788888.332355.103660@g43g2000cwa.googlegroups.com> Message-ID: <8664qx3h84.fsf@bhuda.mired.org> eight02645999 at yahoo.com writes: > In main.py, i am able to check for the value of the user and password > field, eg > > if form.has_key("user") and form["button"].value == "Login" and > form.has_key("password"): > # show all fields > > how can i also check for the user field in the results.py script? ie , > pass the value of the "user" to the python script..so that user must > always login to get to results.py.... This isn't really a Python question. The canonical solution is to set a cookie to get the browser to pass the required information to the next form. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From uche.ogbuji at gmail.com Tue Nov 29 15:45:25 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 29 Nov 2005 12:45:25 -0800 Subject: XMLSchema Parsing In-Reply-To: References: Message-ID: <1133297125.066965.161670@g43g2000cwa.googlegroups.com> km wrote: > i'd like to know if there are any good XMLSchema (.xsd files) parsing modules in python. > regards, Parse and do what? You can parse WXS (a.k.a. XSD) with any XML parser out there. Anyway, off-head, Python tools that handle WXS, to some extent: xsv libxml2/Python lxml generateDS.py Good luck. -- 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 jeremy.d.brewer at gmail.com Tue Nov 22 12:44:51 2005 From: jeremy.d.brewer at gmail.com (jbrewer) Date: 22 Nov 2005 09:44:51 -0800 Subject: PIL FITs image decoder Message-ID: <1132681491.921657.291860@z14g2000cwz.googlegroups.com> I'm trying to read in a FITs image file for my research, and I decided that writing a file decoder for the Python imaging library would be the easiest way to accomplish this for my needs. FITs is a raw data format used in astronomy. Anyway, I followed the example in the PIL documentation online, and I also had a look at the FITs image stub file included with PIL 1.1.5. I cooked up something that should work (or nearly work), but I keep running into either one of two errors (below). The crux of the problem appears to be that my plugin isn't being registered properly and isn't being read at runtime when I call Image.open(). 1.) The library loads the FitsStubImagePlugin.py file from the site-packages directory (instead of my plugin) and then gives the following error: File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/ImageFile.py", line 255, in load raise IOError("cannot find loader for this %s file" % self.format) IOError: cannot find loader for this FITS file 2.) I remove the FitsStubImagePlugin.py, pyc files and stick my plugin in the directory instead (my plugin was already in the PYTHONPATH before). Then I get the following error: Traceback (most recent call last): File "FitsImagePlugin.py", line 111, in ? image = Image.open(fits_name).save(jpg_name) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/Image.py", line 1745, in open raise IOError("cannot identify image file") IOError: cannot identify image file This seems like I'm either doing (or not doing) something really stupid or the docs are outdated. Any help would be greatly appreciated! Jeremy ------------------------------ Code below ----------------------------------- import Image, ImageFile _handler = None ## # Install application-specific FITS image handler. # # @param handler Handler object. def register_handler(handler): global _handler _handler = handler # -------------------------------------------------------------------- # Image adapter def _accept(prefix): return prefix[:6] == "SIMPLE" class FitsImageFile(ImageFile.StubImageFile): #class FitsImageFile(ImageFile.ImageFile): format = "FITS" format_description = "FITs raw image" def _open(self): # byte offset for FITs images byte_offset = 2880 # check header for valid FITs image header_data = self.fp.read(byte_offset) # headers are stored in 80 character strings, so sort them out into a # nice list i = 0 headers = [] while header_data[i] != "\n" and i < len(header_data): headers.append(header_data[i:i + 80]) i += 81 # parse individual headers ok = False for header in headers: words = header.split() try: keyword = words[0] value = words[2] except IndexError: ok = False break if keyword == "NAXIS" and value == 2: ok = True elif keyword == "NAXIS1": xsize = value elif keyword == "NAXIS2": ysize = value if not ok: raise ValueError("file is not a valid FITs image") # size in pixels (width, height) self.size = (xsize, ysize) # mode setting is always greyscale self.mode = "F" # data descriptor self.tile = [("raw", (0, 0) + self.size, byte_offset, ("F", 0, -1))] # is this needed? loader = self._load() if loader: loader.open(self) def _load(self): return _handler def _save(im, fp, filename): if _handler is None or not hasattr("_handler", "save"): raise IOError("FITS save handler not installed") _handler.save(im, fp, filename) # register the plugin Image.register_open(FitsImageFile.format, FitsImageFile, _accept) Image.register_save(FitsImageFile.format, _save) # method given in docs #Image.register_open(FitsImageFile.format, FitsImageFile) Image.register_extension(FitsImageFile.format, ".fits") Image.register_extension(FitsImageFile.format, ".fit") # test code if __name__ == "__main__": import os fits_name = "fpC-001739-r1-0304.fit" jpg_name = os.path.splitext(fits_name)[0] + ".jpg" image = Image.open(fits_name).save(jpg_name) print "Converted FITs image '%s' to jpeg image '%s'" % (fits_name, jpg_name) From kingsleyturner at westpac.com.au Wed Nov 30 22:27:05 2005 From: kingsleyturner at westpac.com.au (Kinsley Turner) Date: Thu, 1 Dec 2005 14:27:05 +1100 Subject: Newbie: Python & Serial Port question In-Reply-To: <1133340520.3509.130.camel@swayam.transcontinental.co.in> Message-ID: python-list-bounces+kingsleyturner=westpac.com.au at python.org wrote on 30/11/2005 07:48:39 PM: > Am a python newbie. Does python have a native way to communicate with a > PC serial port? I found that pyserial needs java. > > I am using Linux..CentOS 4.2, to be exact, no java installed and > zilch/no/none/maybe never experience of java too. > > I have an application where I want to resd logs from the serial port of > an EPABX and log them to a postgreSQL database. What's the best way to > do this using python? Does anyone know of an existing software/python > library/module for this? You can't just open the serial port like a file? Perhaps you'd need to set the correct port parameters with some other app, but it should be do-able. -kt (non-removable, sorry) -- Please consider our environment before printing this email. WARNING - This email and any attachments may be confidential. If received in error, please delete and inform us by return email. Because emails and attachments may be interfered with, may contain computer viruses or other defects and may not be successfully replicated on other systems, you must be cautious. Westpac cannot guarantee that what you receive is what we sent. If you have any doubts about the authenticity of an email by Westpac, please contact us immediately. It is also important to check for viruses and defects before opening or using attachments. Westpac's liability is limited to resupplying any affected attachments. This email and its attachments are not intended to constitute any form of financial advice or recommendation of, or an offer to buy or offer to sell, any security or other financial product. We recommend that you seek your own independent legal or financial advice before proceeding with any investment decision. Westpac Institutional Bank is a division of Westpac Banking Corporation, a company registered in New South Wales in Australia under the Corporations Act 2001 (Cth). Westpac is authorised and regulated in the United Kingdom by the Financial Services Authority and is registered at Cardiff in the United Kingdom as Branch No. BR 106. Westpac operates in the United States of America as a federally chartered branch, regulated by the Office of the Comptroller of the Currency. Westpac Banking Corporation ABN 33 007 457 141. From cito at online.de Wed Nov 23 17:00:29 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 23:00:29 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132735254.039468.106660@g44g2000cwa.googlegroups.com> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <1132735254.039468.106660@g44g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > So what do you want returned when you ask for d1[1] ? The member keyed > by 1, or the item in position 1 ? In case of conflict, the ordered dictionary should behave like a dictionary, not like a list. So d1[1] should be the member keyed by 1, not the item in position 1. Only in case there is no member keyed by 1, the item in position 1 could be returned, but I think that would be too adventurous a hattrick and can lead to big confusion. Better to raise a KeyError in that case. >> But no other way to directly manipulate the keys should be provided. > Why - don't trust yourself with it ? No, because I think it is not needed if list operations like insert are directly possible on your dictionary. But maybe methods such as setkeys() and setvalues() would be nice to have in addition. Instead of writing d.sequence = new_sequence, I would write d.setkeys(new_sequence). But I'm not sure what to do if new_sequence is not a permutation of the old one. Raise a KeyError? Or even swallow this? For instance d = OrderedDict((1,11), (2,12)) d.setkeys((2, 1)) ==> d = OrderedDict((2, 11), (1, 12)) d.setkeys((3, 4)) ==> d = OrderedDict((3, 11), (4, 12)) (or KeyError?) d.setvalues((12, 11)) ==> d = OrderedDict((1, 12), (2, 11)) d.setvalues((13, 14)) ==> d = OrderedDict((1, 13), (2, 14)) (always ok) (Or maybe better set_keys in analogy to has_key?) I hesitate making keys and values managed properties, because this would conflict with them being methods in ordinary dicts. Ordered dicts should resemble ordinary dicts as closely as possible. And giving it a different name like "sequence" I find confusing and unintuitive. A resort could be the following: If keys() is given a sequence as argument, then use this as the new sequence of keys, and similar with values(). This way, no new methods need to be introduced. -- Christoph From robert.kern at gmail.com Mon Nov 21 12:59:18 2005 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 21 Nov 2005 09:59:18 -0800 Subject: Numeric array in unittest problem In-Reply-To: <1h6da2y.qucyw7nzyjejN%aleax@mail.comcast.net> References: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> <1132586037.388588.323670@g44g2000cwa.googlegroups.com> <1h6da2y.qucyw7nzyjejN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: >>>>import Numeric >>>>a=Numeric.array([1,22]) >>>>b=Numeric.array([1,33]) >>>>c = a==b >>>>c > > array([1, 0]) > >>>>assert(c) > > i.e., thanks to element-by-element evaluation, == will generally return > a true value for ANY comparison of Numeric arrays, causing a very > frequent beginner's bug to be sure. Indeed. This is why numarray and scipy_core have made arrays raise an exception when someone tries to use them as truth values. -- 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 fredrik at pythonware.com Wed Nov 23 03:39:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 09:39:51 +0100 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com><1132712643.968300.151010@g49g2000cwa.googlegroups.com><1132713954.040591.120660@f14g2000cwb.googlegroups.com> <1132718374.960509.206800@z14g2000cwz.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > led to more serious flaws like the missing if-then-else expression, > something I use in virtually every piece of code I write, and which > increases readability. you obviously need to learn more Python idioms. Python works better if you use it to write Python code; not when you mechanically translate stuff written in other languages to Python. > (Well, ok that is not the end of the world either but it's lack is irritating > as hell, and yes, I know that it is now back in favor.) the thing that's in favour is "then-if-else", not "if-then-else". From steve at REMOVETHIScyber.com.au Sat Nov 5 19:22:58 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 06 Nov 2005 11:22:58 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <7xpsphlxri.fsf@ruckus.brouhaha.com> <7x3bmcaxnt.fsf@ruckus.brouhaha.com> <7x4q6r1zb8.fsf@ruckus.brouhaha.com> <7x64r7ty4k.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 04 Nov 2005 22:19:39 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> > Next you get some performance gain by using gmpy to handle the long int arithmetic, >> >> Then whatever happens next will be my own stupid fault for prematurely optimising code. > > Huh? There's nothing premature about using gmpy if you need better long int performance. > It was written for a reason, after all. Sure, but I would be willing to bet that incrementing a counter isn't it. >> What exactly is your point? That bugs can happen if the behaviour of your >> underlying libraries changes? > > That your initialization scheme is brittle--the idea of data > abstraction is being able to change object behaviors -without- making > surprising bugs like that one. You don't even need the contrived gmpy > example. You might replace the level number with, say, a list of > levels that have been visited. Do you expect level += 1 to still work when you change level to a list of levels? The problem with data abstraction is if you take it seriously, it means "You should be able to do anything with anything". If I change object.__dict__ to None, attribute lookup should work, yes? No? Then Python isn't sufficiently abstract. As soon as you accept that there are some things you can't do with some data, you have to stop abstracting. *Prematurely* locking yourself into one *specific* data structure is bad: as a basic principle, data abstraction is very valuable -- but in practice there comes a time where you have to say "Look, just choose a damn design and live with it." If you choose sensibly, then it won't matter if your counter is an int or a long or a float or a rational -- but you can't sensibly expect to change your counter to a binary tree without a major redesign of your code. I've watched developers with an obsession with data abstraction in practice. I've watched one comp sci graduate, the ink on his diploma not even dry yet, spend an hour mapping out state diagrams for a factorial function. Hello McFly? The customer is paying for this you know. Get a move on. I've written five different implementations of factorial in ten minutes, and while none of them worked with symbolic algebra I didn't need symbolic algebra support, so I lost nothing by not supporting it. So I hope you'll understand why I get a bad taste in my mouth when people start talking about data abstraction. > I don't think the culprit is the mutable/immutable distinction += > uses, though that is certainly somewhat odd. I think Antoon is on the > right track: namespaces in Python live in sort of a ghetto unbecoming > of how the Zen list describes them as a "honking great idea". These > things we call variables are boxed objects where the namespace is the > box. So having x+=y resolve x to a slot in a namespace before > incrementing that same slot by y, maybe better uses the notion of > namespaces than what happens now. Perhaps it does, but it breaks inheritance, which is more important than purity of namespace resolution. Practicality beats purity. > I'm too sleepy to see for sure > whether it gets rid of the mutable/immutable weirdness. What weirdness? What would be weird is if mutable and immutable objects worked the same as each other. They behave differently because they are different. If you fail to see that, you are guilty of excessive data abstraction. -- Steven. From bokr at oz.net Thu Nov 3 14:01:51 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 03 Nov 2005 19:01:51 GMT Subject: Anomaly in creating class methods References: <1131016762.522810.91780@f14g2000cwb.googlegroups.com> Message-ID: <436a5026.34209590@news.oz.net> On 3 Nov 2005 03:19:22 -0800, "venk" wrote: >Hi, > given below is my interaction with the interpreter.... In one case, i >have created the class method using the "famous idiom"... and in the >other, i have tried to create it outside the class definition... why >isn't the latter working ? (of course, the presence of decorators is a >different issue).... >>>> class D: >... def f(cls): >... print cls >... >>>> D.f=classmethod(D.f) >>>> D.f >> >>>> D.f() >Traceback (most recent call last): > File "", line 1, in ? >TypeError: unbound method f() must be called with D instance as first >argument (got classobj instance instead) >>>> class D: >... def f(cls): >... print cls >... f=classmethod(f) >... >>>> D.f >> >>>> D.f() >__main__.D > I think you are on very thin ice using classmethod for old-style classes. In any case, you are not providing the same argument to classmethod in the two examples above. I'm not sure what classmethod tries to do with an unbound method, but it's not normal usage even in newstyle classes. It probably just saves the callable argument as an attribute of the classmethod instance, so the problem doesn't show until the descriptor machinery comes into play (on attribute access and calling the bound callable). >>> def showcmarg(f): print 'cmarg=%r'%f; return classmethod(f) ... >>> class D: ... def f(cls): print cls ... >>> D.f=showcmarg(D.f) cmarg= Note that that was an unbound method as the arg, that gets stored in the descriptor >>> D.f > >>> D.f() Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method f() must be called with D instance as first argument (got classobj tance instead) That's just the callable (D unbound method) you gave it complaining that the descriptor is passing the intended cls D (a classobj) instead of an instance of D to the unbound method. >>> class D: ... def f(cls): print cls ... f = showcmarg(f) ... cmarg= Note that this time that was a _function_ arg, because it was picked up as a local binding during the execution of the body of the class definition, where classmethod was called. The function will have no demands except to match its signature when the classmethod descriptor instance calls it with first arg of D. >>> D.f > >>> D.f() __main__.D You could extract the normal (function) classmethod arg from the outside though: >>> class D: ... def f(cls): print cls ... >>> D.f=showcmarg(D.f.im_func) cmarg= >>> D.f > >>> D.f() __main__.D Suggest migrating to new style classes consistently ;-) Regards, Bengt Richter From james at colannino.org Fri Nov 11 19:53:40 2005 From: james at colannino.org (James Colannino) Date: Fri, 11 Nov 2005 16:53:40 -0800 Subject: weird problem with os.chmod In-Reply-To: <43753C13.2010609@colannino.org> References: <43753C13.2010609@colannino.org> Message-ID: <43753D14.8040400@colannino.org> James Colannino wrote: >So then I entered the command print 0600, and saw that the >actual number being output was 384 (why would it output 384?!) > > Ok, so further research revealed that 0600 is actually the octal representation for 384 (which makes sense.) So then, I guess my question would have to be, is there a way for me to make Python aware that the 0600 I'm passing to int() is octal and not decimal so that I will get 384 instead of 600? James -- My blog: http://www.crazydrclaw.com/ My homepage: http://james.colannino.org/ "A well regulated militia being necessary to the security of a free state, THE RIGHT of the people to keep and bear arms SHALL NOT BE INFRINGED." --United States Constitution, Second Ammendment From fredrik at pythonware.com Mon Nov 28 09:06:49 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Nov 2005 15:06:49 +0100 Subject: Why I need to declare import as global in function References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> Message-ID: didier.doussaud at gmail.com wrote: > I have a stange side effect in my project : > > in my project I need to write "gobal" to use global symbol : > > ... > import math > ... > def f() : > global math # necessary ?????? else next line generate an error > message ????? what error message? > print math.pi you only need global in this case if you assign to the name somewhere later in the function (e.g. "math = ..." or "import math" or some other assignment) please post the error message (the entire traceback). From mwm at mired.org Thu Nov 10 20:57:46 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 20:57:46 -0500 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> Message-ID: <86ek5o54kl.fsf@bhuda.mired.org> Yu-Xi Lim writes: > Bill Mill wrote: >> Your only solution, then, is to write unpopular code. Because, as Alex >> said, it will otherwise be broken into. Let's look at two very popular >> pieces of code: Half-Life 2 and Windows XP. How are they secured? >> Previous version of these software products used sophisticated >> client-side programming to try and be secure, but the security was >> nonexistant. Users share keys and cracks with each other. > Mike Meyer wrote: > > What makes you think this is the case? There are ways to distribute > > Python modules so that the user can't just open them in a text > > editor. There are also ways to get cryptographic security for > > distributed modules. Yes, if you use the same methods you use in C++, > > it's "much harder". But by the same token, if you tried to use the > > methods you'd use in a Python program in C++, you'd find that the C++ > > version was "much harder". > This is a personal anecdote, but I'm sure it applies to at least some > people. Obviously I'm not an honest person. But I'm not so against > spending money on software that I won't buy it if there's a pretty > good copy protection system on it. The "keeping honest people honest" > argument is simplistic and as Ben said, "black and white thinking". And how much software is out there that you actually want so badly that you'll buy it rather than wait unti it's cracked? Does it make up a significant portion of the software you use? If not, then you as an example of not merely "keeping honest people honest" are that it's difference from reality is insignificant. > Ben's analogy of the house is not a perfect example, but it's still a > fair one. You know that if some one really wants to break into your > house, he will get in, regardless of your sophisticated laser trip > wire system, ex-SAS guards, and genetically-engineered guard dogs. But > as long as the cost of protection is less than the cost of the item > you're protecting (multiplied by the relevant probabilities, factoring > recurring costs, etc), it's worthwhile to spend money on > protection. If that fails, then you will of course fall back on the > law, but you still try to prevent it from happening in the first place. Sounds like you just said that manufacturers should improve their protection until they aren't making any profit on the product. That's silly. The goal isn't to maximize protection, it's to maximize profit. That means it only makes sense to spend money on better protection if the cost of the protection is less than the expected profit from adding it. The cost of the item you're protecting is irrelevant. The cost of adding copy protection is *noticably* more than the cost of the copy protection bits. A recent, heavily publicized case where Sony added copy protection to a product cost them sales, and from what I've heard, even legal fees. > I do believe that code obfuscation and copy protection measures work, > to a limited extent. Few software companies believe that their copy > protection will be uncrackable (though their marketing droids may say > otherwise), but are most willing to invest in it to at least > temporarily stave off the piracy. Anything at all acts in the "keeping honest people honest" capacity. It also delays the inevitable cracking - which is all you can do. The only thing spending more on it does is lengthen the delay. Hard data on how many sales that extra delay is responsible for is, by it's very nature, impossible to come by. You've provided anecdotal evidence that copy protection can improve sales. I've provided anecdotal evidence that adding copy protection cost sales. > Distribution of python modules as compiled bytecode is a limited form > of obfuscation. Some believe it's enough. But if there's a free > obfuscator out there than can increase the difficulty of reverse > engineering, why not use that too? Costs you nothing, and may get you > a customer or two more before some one manages to crack that. Um, if you think adding steps to the release process costs you nothing, you don't understand the release process. If you've got a way to obfuscate the code that doesn't require extra steps in the release or development process, I'd love to hear about it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From grante at visi.com Sat Nov 5 18:35:05 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Nov 2005 23:35:05 -0000 Subject: Using Which Version of Linux References: Message-ID: <11mqgd917dsrm43@corp.supernews.com> On 2005-11-05, Dan M wrote: > Personally I would recommend staying away from Fedora unless you have a > friend who is well-versed in it and willing to help. I like the > distributin ok (I run it on the laptop I'm writing this from) but it uses > RPMs for package distribution, and the rpm tools don't know how to > automatically downloaded dependencies like yum or apt do. Nonsense. You're comparing apples to oranges. If you want to compare rpm with something it would be dpkg. If you want to talk about yum or apt, then you should be comparing them to something like urpmi. If you tell it to install package X, it will analyze prerequisites, and then download and install everything required. It works almost exactly like apt-get does. Urpmi is text-mode, but there are also GUI front-ends that do the same thing. > Because of that I have to say that the RPM package tools suck > quite badly. You'd say the same think about Debian if all you had ever used was dpgk, and I dare you to try to do anything with dselect. > Debian and SUSE are both pretty good choices. -- Grant Edwards grante Yow! I just got my PRINCE at bumper sticker... But now I visi.com can't remember WHO he is... From peter at engcorp.com Thu Nov 10 07:33:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Nov 2005 07:33:34 -0500 Subject: iterate over class variables In-Reply-To: References: Message-ID: Yves Glodt wrote: > I need to iterate over a class and get all her variable names and > values, e.g. considering this example: > > class testclass: > var1 = 'ab' > var2 = 'cd' > var3 = 'ef' Is the following of any help to you? >>> class testclass: ... a = 'a' ... >>> dir(testclass) ['__doc__', '__module__', 'a'] >>> testclass.__dict__ {'a': 'a', '__module__': '__main__', '__doc__': None} >>> import inspect >>> inspect.classify_class_attrs(testclass) [('__doc__', 'data', , None), ('__module __', 'data', , '__main__'), ('a', 'data' , , 'a')] There are other methods in "inspect" which could help you. -Peter From aleax at mail.comcast.net Fri Nov 11 10:10:01 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 11 Nov 2005 07:10:01 -0800 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> <1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: <1h5up4x.z53sx5zkr9ytN%aleax@mail.comcast.net> Norman Silverstone wrote: ... > Incidentally, I am only just starting to learn about functions and have > not come across the module 're'. Also why is it (lo+hi)//2 and not > (lo+hi)/2. Using // ensures truncation, which is what you want. A single / may mean truncating division in the default legacy/compatibility mode, but with the new division behavior (which one day will become standard) it means true division, so that for example 1/2 means 0.5 -- better get used to the new behavior ASAP (which is why you can ask for new division behavior with -Qnew on Python's commandline or 'from __future__ import division' at the top of your module -- to help you get used to it). Alex From devlai at gmail.com Wed Nov 30 22:10:38 2005 From: devlai at gmail.com (Devan L) Date: 30 Nov 2005 19:10:38 -0800 Subject: Recursion bug... In-Reply-To: <1133405155.154823.134620@g47g2000cwa.googlegroups.com> References: <1133405155.154823.134620@g47g2000cwa.googlegroups.com> Message-ID: <1133406638.583675.234700@z14g2000cwz.googlegroups.com> ex_ottoyuhr wrote: > To start with, I'm new at Python, so if this is something relatively > ordinary or a symptom of thinking in C++, I apologize... > > Anyhow, I'm currently trying to write a means of generating > genetic-programming functions in Python; the details would be a little > much for a Usenet post, but suffice it to say that it would involve > trees of objects with an opcode and a variable number, between in this > case 0 and 3, of 'arguments' -- also objects of the same sort. As a > function to implement them, I'm doing something to the effect of this: > > [ex_ottoyuhr's code] > > Sorry to have given such a long example... But anyways, the problem is > that, while I think this should generate a number of children for each > toRet equivalent to the required number of children, it's actually > appending all children generated in the function to the 'root' toRet > rather than to child functions -- so that if I ask for a tree with > depth 2, and the root would have 2 arguments, the first child would > have 1, and the second child would have 2, the result is a root with a > 5-argument-long children and two child functions with 0-argument ones. > There's some other strange stuff going on here, too; in particular, > with one particular opcode, toRet is assigned a member 'value' which is > randomly generated between 0 and 10,000. All toRets assigned value seem > to be ending up with the same result... > > Could anyone explain what I'm doing wrong? I'm beginning to suspect > that Python scope rules must not work like my native C++; have I made a > common mistake? Well, for one, in your __init__ method, you never do anything with anOpcode. You simply assign the name 'opcode' to anOpcode. The reason why everything is the same is that you're accessing TreeCommand.children or Treecommand.opcode, which is shared by all instances unless you assign to it. And you never increment generated, so I don't see why the while loop would ever end, unless you intentionally wanted that. Try this code instead: max_opcode = 20 max_with_args = 15 class TreeCommand: def __init__(self, opcode) : self.opcode = opcode self.children = [] def MakeTreeCommand(depth, maxdepth) : if depth == 0: command = TreeCommand(random.randint(0, max_with_args) elif depth == maxdepth: command = TreeCommand(random.randint(max_with_args+1, max_opcode)) else: command = TreeCommand(random.randint(0, max_opcode)) if command.opcode <= max_with_args: children_required = something_greater_than_0 else: children_required = 0 generated = 0 for i in range(children_required): command.children.append(MakeTreeCommand(depth+1, maxdepth)) return command From duncan.booth at invalid.invalid Tue Nov 8 07:59:55 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Nov 2005 12:59:55 GMT Subject: Pywin32: How to import data into Excel? References: Message-ID: Tim Golden wrote: > [Dmytro Lesnyak] >> I need to import some big data into Excel from my >> Python script. I have TXT file (~7,5 Mb). I'm using >> Pywin32 library for that, but if I first try to read >> the TXT file and then save the values one by one like >> xlBook.Sheets(sheet_name).Cells(i,j).Value = value_from_TXT_file >> it takes about 10 hours to process whole data > > A few suggestions: > > + When trying to automate anything in Excel, it's > usually illuminating to record a macro which does > what you want, and then to translate that VBA code > into Python. > Another suggestion: when automating Excel, turn off the automatic recalculation (set Application.Calculation=xlManual) and then turn it back on again when you have finished. If you don't do this, Excel will attempt to recalculate the sheet after every update to a cell. Even if you don't have any formulae referencing the cells you change it still makes a big difference. From http Tue Nov 29 06:43:59 2005 From: http (Paul Rubin) Date: 29 Nov 2005 03:43:59 -0800 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: <7xpsojsmps.fsf@ruckus.brouhaha.com> "mojosam" writes: > I will be doing the bulk of the coding on my own time, because I need > to be able to take these tools with me when I change employers. > However, I'm sure that in the course of using these tools, I will need > to spend time on the job debugging or tweaking them. I do not want my > current employer to have any claim on my code in any way. Usually if > you program on company time, that makes what you do a "work for hire". > I can't contaminate my code like that. Whether your employer has claim to stuff you do on your own time depends intricately on the law in your state. California is much different from New York, for example. The platitudes you hear in this thread about it are pretty useless. "Employer" means something specific: are you paid on W2's? If not, maybe you have a "client" or "customer" rather than an "employer" and the entire picture is different. When something is work for hire is also intricate. Just because you're being paid by someone else to write something doesn't always make it a work for hire, even if you're an employee. There are no simple universal answers. To get these questions answered you really have to consult a legal adviser IN YOUR STATE. And you should explain at the very beginning to your client/customer/employer what you're doing and what rights you want to hold on to, and negotiate a written agreement. Don't take the attitude of "in what ways can I make sure that surprises I spring on the client get resolved in my favor if there's a dispute". Instead, do everything you can to avoid disputes and surprises. That means get the client need to agree in advance, in writing, to what happens with what. Every agreement I've signed in the past few years has included a release rights (from me to the employer) and a list of exceptions as part of the boilerplate. From steve at REMOVETHIScyber.com.au Sat Nov 12 19:22:55 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 13 Nov 2005 11:22:55 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <1h5ty4g.1onzjda6fc7xmN%aleax@mail.comcast.net> <86ek5l3ho2.fsf@bhuda.mired.org> Message-ID: On Sat, 12 Nov 2005 12:22:21 -0500, Mike Meyer wrote: > And if instead you lose one customer because you've denied them their > fair use rights, then your copy protection has lost you more in the > form of a cost that you overlooked than all the costs you actually > considered. In a competitive marketplace, why would I choose to buy DRMed software if there is a non-DRMed equivalent with the same functionality and equivalent cost? DRM is both an extra cost and a lower functionality applied to the software: an extra cost because if I can only run three simultaneous instances when I want four, then I need to pay more; lower functionality because things I may wish to do (like lock the original disk in the fireproof safe and install off a backup copy) may be impossible. If you are supplying to a non-competitive market, you may decide that you don't mind losing some sales. In non-competitive markets, the pressure to improve the ratio of functionality to cost is weak. [snip] > Actually, obfuscation by itself has *no* benefit. If all you do is > obfuscate the code, none of the pirates will ever notice - they'll just > copy the code without ever trying to read it. It's the copy protection > mechanisms you're trying to obfuscate that gains you the alleged > benefit. I don't think you mean copy protection, as in preventing copies -- it is difficult for an application to prevent the OS from making physical copies, and by difficult I mean "essentially impossible". Perhaps you mean access control, for example the software will only run for three people simultaneously. > Once you provide a copy protection mechanism, obfuscation has > some benefit, though the costs aren't clearly minimal, not if you're a > cometent engineer. It's the benefits of the copy protection that I claim > are insignificant. That's not quite true -- there may be instances where there is a real or perceived benefit from keeping the algorithms used secret: perhaps you have found a more efficient way to do something, or perhaps you just want to hide from your users just how bad your code really is, or perhaps you've conned^H^H^H^H convinced them to pay a premium price for reduced functionality and don't want them bypassing your access control mechanisms. The problem is, developers often have a ridiculously over-inflated opinion of the worth of their code, and the business people behind them even more so. Everybody[1] thinks that their two-bit Visual Basic calculator app is going to be the next Microsoft Windows and make them a fortune, but only if they keep the source code secret. Because so much code is secret, people fail to appreciate just how little innovation there really is in the IT industry, and imagine that just because they personally sweated blood for months writing the code, it must be valuable. Anyway, I think this is all a storm in a teacup. With the possible exception of game console software, I think the idea of shrink-wrapped software generally and software licencing particularly is a temporary aberration. In a decade, software obfuscation will only exist as a way for hackers to prove how clever they are, as in the Obfuscated C Contest. Until then, well, if you think you can a commercial advantage by annoying your customers, knock yourselves out. [1] By "everyone" I mean "lots of people who should know better". -- Steven. From jstroud at mbi.ucla.edu Wed Nov 9 00:38:12 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 8 Nov 2005 21:38:12 -0800 Subject: overloading *something In-Reply-To: <1h5obt1.ml6ib01swfdhbN%aleax@mail.comcast.net> References: <1h5obt1.ml6ib01swfdhbN%aleax@mail.comcast.net> Message-ID: <200511082138.12495.jstroud@mbi.ucla.edu> On Monday 07 November 2005 20:36, Alex Martelli wrote: > Ron Adam wrote: > > James Stroud wrote: > > > Hello All, > > > > > > How does one make an arbitrary class (e.g. class myclass(object)) > > > behave like a list in method calls with the "*something" operator? What > > > I mean is: [snip] > > A dictionary would be pretty much the same except subclassed from a > > dictionary of course. > > I believe this one is correct (but I have not checked in-depth!). Does anyone else find the following annoying: py> from UserDict import UserDict py> aud = UserDict({"a":1, "b":2}) py> def doit(**kwargs): ... print kwargs ... py> aud {'a': 1, 'b': 2} py> doit(**aud) Traceback (most recent call last): File "", line 1, in ? TypeError: doit() argument after ** must be a dictionary UserDict should be isomorphic with a dict. The fact that it is not in this case seems terribly un-pythonic to me. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From arkanes at gmail.com Fri Nov 18 18:47:40 2005 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Nov 2005 17:47:40 -0600 Subject: Confused about namespaces In-Reply-To: <1132356583.703129.241070@g47g2000cwa.googlegroups.com> References: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> <1132356583.703129.241070@g47g2000cwa.googlegroups.com> Message-ID: <4866bea60511181547x4d1329f5y64849ee3b7f2254b@mail.gmail.com> On 18 Nov 2005 15:29:43 -0800, KvS wrote: > Ok, makes sense but didn't seem "natural" to me, although it is an > obvious consequence of what you just pointed out, namely that modules > are evaluated in their own namespace, something to keep in mind... On > the other hand it does apparently work recursively "the other way > around" since I didn't explicitly import wx in main.py but only > indirect via importing GUIclasses in which wx is imported right? > it worked because all the code that used stuff from the wx namespace was in GUIclasses.py. If you tried to use create wx classes directly in your toplevel file it would fail unless you did an "import wx" first. Now, as a slight consequence of the specific way you imported, it may appear to do something different - when GUIClasses.py imported wx, an entry in the modules namespace was created with the value "wx", and the value being the wx module. When you do "from GUIClasses import *", that imports all the symbols in GUIClasses namespace into your local namespace, including the "wx" entry. This kind of cascading behavior is one reason that "from foo import *" is frowned up, because the namespace pollution can cause confusing bugs. > Thanks. :). > > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Tue Nov 22 10:36:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 16:36:51 +0100 Subject: about sort and dictionary References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132667795.525317.25980@g14g2000cwa.googlegroups.com> Message-ID: > Still don't see why even you ask it again. fyi, I'm not " fredrik at pythonware-dot-com.no-spam.invalid ", and I've never, as far I know, posted from "readfreenews.net" From roccomoretti at hotpop.com Mon Nov 7 14:43:56 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 07 Nov 2005 13:43:56 -0600 Subject: Map of email origins to Python list In-Reply-To: <1131390365.721288.272070@g47g2000cwa.googlegroups.com> References: <1131390365.721288.272070@g47g2000cwa.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Rocco Moretti wrote: > >>It's also a testament to the limited value of physically locating people >>by internet addresses - If you zoom in on the San Fransico bay area, and >>click on the southern most bubble (south of San Jose), you'll see the >>entry for the Mountain View postal code (94043) - a massive list which >>contains mostly gmail.com accounts, but also contains accounts with .de >>.ca .uk .pl .it .tw and .za domains. I doubt all of the people in that >>list live in sunny California, let alone in Mountain View proper. > > > North of that bubble is a second massive list also labeled Mountain > View > 94043. I found my name on that list and I live in the Chicago area. > Moutain View is, perhaps, where aol.com is located? These bubbles are > showing the location of the server that's registered under the domain > name? Actually, it looks like they are the *same* list. I haven't gone through all of the names, but I spot checked a few, and it looks like yours, among others, are listed in both spots. (The southern one looks like it is a mislocated duplicate, as it is nowhere close to Mountain View, and is stuck in the middle of a golf course.) From steve at holdenweb.com Sat Nov 19 12:59:07 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 Nov 2005 17:59:07 +0000 Subject: Using win32ui.CreateFileDialog() to get the name of a file. In-Reply-To: <1132417639.273376.27820@g47g2000cwa.googlegroups.com> References: <1132417639.273376.27820@g47g2000cwa.googlegroups.com> Message-ID: Joey C. wrote: > Hello. > I'm writing a program that creates a series of batch operations to > convert movies to be used on iPodLinux. The programs that do the > encoding and conversions are seperate from mine and all mine does is > use os.system() to call the program. > > However, it needs to get an input file and an output file. Originally > I was using just raw input, but I got adventuresome and decided to try > win32ui.CreateFileDialog(). But this will only open or save a file and > its output will be either 1 or a failure. How might I go about using > it to get the _file name_ of a file. > For example. > Box appears asking user to find a file they want. They double click on > the file. Let's call it C:\Video.avi > Then another dialog box appears asking them where to save it. They > save it at C:\iPodVideo.avi. > > Now the Python program extracts the name of these files and then uses > os.system() to run: > mencoder.exe -[parameters] C:\Video.avi -o C:\iPodVideo.avi > > Note that I'm not actually inputting the contents of the file, I'm just > passing the file name along. > > How might I do this? Thanks. > After you've had the user interact with the dialog you should call its GetFileName() method. The interactive interpreter can be useful in finding things like this out (though many details of objects can remain hidden in the Windows environment): >>> dir(d) ['GetFileExt', 'GetFileName', 'GetFileTitle', 'GetPathName', 'GetPathNames', 'GetReadOnlyPref', 'SetOFNInitialDir', 'SetOFNTitle'] >>> d.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 kent37 at tds.net Sun Nov 20 22:18:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Nov 2005 22:18:11 -0500 Subject: Web-based client code execution In-Reply-To: <4381390F.1090004@redlinepy.com> References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> <438066d7$1_3@newspeer2.tds.net> <4381390F.1090004@redlinepy.com> Message-ID: <438139cf$1_3@newspeer2.tds.net> Paul Watson wrote: > Kent Johnson wrote: >> Stephen Kellett wrote: >>> ActiveState do a version of Python that can run in a script tag like >>> JavaScript and VBScript. This requires Windows Scripting Host. They >>> also do a similar thing for Perl, not sure about TCL. >> >> See >> http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830 > > Please correct my misunderstanding if I am wrong, but I thought that > this runs server-side only and requires Microsoft IIS as the httpd > server. Is that correct? I haven't tried it but the referenced article seems to be about including Python in a web page to be run in-browser by IE. Kent From apardon at forel.vub.ac.be Mon Nov 28 05:10:31 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2005 10:10:31 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> <86fypkim4x.fsf@bhuda.mired.org> Message-ID: Op 2005-11-25, Mike Meyer schreef : > Antoon Pardon writes: >> Well this is, is one thing I have a problem with. >> >> The python people seem to be more concerned with fighting things >> that could be used counter the python philosophy, than search for >> things that enable working in the python philosophy. > > And what's wrong with that? It seems a bit intollerant and contraproductive to me. If thet would just concentrated on what they want, they could have progressed further on that road, then where they are now, because progress sometimes simple stops because other could use something for what it was not intended. >>> Yes. And if you need a red hammmer, you should get a red hammer, not >>> use red spray paint on one that wasn't designed to be red. Just >>> because *you* don't see how providing a red option violates the >>> philosophy of python doesn't mean that it doesn't do so. >> >> Well this seems to be the main conflict between those who would >> like Python to go a bit further and those that oppose it. >> >> Should the priority be to enable python's philosophy or should >> it be the priority to limit python to only allow it's philosophy. > > Those two statements say the same thing. They are not. > Part of the Python philosphy, > from "import this", is that there should only be one obvious way to do > it. It doesn't say that. It says: There should be one-- and preferably only one --obvious way to do it. Here you see the difference on emphasis. You are focussing on the only one, while the original Python Koan seems to focus on the there should be one. So supose someone proposes a change that will introduce one obvious way, to solve a particular problem. However it introduces a second obvious way to solve an other problem too. I think we should accept such a proposal. It seems you and a lot of others seem to think such proposals should be rejected. > By enabling that part of Python's philosphy, you're automatically > limiting python to not allow other - specifically non-pythonic - ways > to do the same thing. No it doesn't. Supose someone proposes a change that will introduce one obvious way, to solve a particular problem. However it introduces a second non pythonic way to solve an other problem. I don't think there is something wrong with accepting this change. However it seems you do. -- Antoon Pardon From iddw at hotmail.com Tue Nov 29 13:22:02 2005 From: iddw at hotmail.com (Dave Hansen) Date: Tue, 29 Nov 2005 12:22:02 -0600 Subject: newbie question concerning formatted output References: Message-ID: On Tue, 29 Nov 2005 17:40:08 GMT in comp.lang.python, Thomas Liesner wrote: [...]> >So instead of: > >3905 >3009 >0000 [...] > >i'd like to have: > >3905 3009 0000 [...] > >This is the codesnippet i am using: > >#!/usr/bin/python > >import string >inp = open("xyplan.nobreaks","r") >data = inp.read() >for words in data.split(): > print words >inp.close() > >Any hints? Here's an obvious, if naive, implementation: data = imp.read().split() for i in range(0,len(data),3): tl = data[i:i+3] for d in tl: print d, print inp.close() HTH, -=Dave -- Change is inevitable, progress is not. From bonono at gmail.com Wed Nov 2 08:00:00 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 2 Nov 2005 05:00:00 -0800 Subject: Most efficient way of storing 1024*1024 bits In-Reply-To: References: Message-ID: <1130936400.902700.301330@g44g2000cwa.googlegroups.com> C ? Tor Erik S?nvisen wrote: > Hi > > I need a time and space efficient way of storing up to 6 million bits. Time > efficency is more important then space efficency as I'm going to do searches > through the bit-set. > > regards tores From xray_alpha_charlie at yahoo.com Mon Nov 7 10:57:13 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Mon, 7 Nov 2005 07:57:13 -0800 (PST) Subject: RAW_INPUT Message-ID: <20051107155713.88147.qmail@web35913.mail.mud.yahoo.com> I am having trouble with the following example used in a tutorial: print "Halt !" s = raw_input ("Who Goes there? ") print "You may pass,", s I run this and get the following: Halt! Who Goes there? --thats it....if I hit enter again "You may pass," appears... In the example after running you should get: Halt! Who Goes there? Josh You may pass, Josh I'm assuming s=Josh...but that is not included in the statement at all I don't know how you put "Josh" in or how you got it to finish running w/o hitting enter after "Who goes there?" What am I doing wrong? thanks, -xray- --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From siona at chiark.greenend.org.uk Fri Nov 18 12:32:59 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 18 Nov 2005 17:32:59 +0000 (GMT) Subject: How to convert a "long in a string" to a "long"? References: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> Message-ID: Steven Bethard wrote: >ondekoza at gmail.com wrote: >> s = long("0xffffffffL") >> ValueError: invalid literal for long(): 0xffffffffL > >>> int("0xffffffff", 0) >4294967295L So why does the base argument to int() (or long()) default to 10 and not 0? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From simon.brunning at gmail.com Fri Nov 11 14:41:06 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 11 Nov 2005 19:41:06 +0000 Subject: Python Countdown In-Reply-To: <20051111192208.93680.qmail@web35912.mail.mud.yahoo.com> References: <20051111192208.93680.qmail@web35912.mail.mud.yahoo.com> Message-ID: <8c7f10c60511111141u4196c852v@mail.gmail.com> On 11/11/05, john boy wrote: > I am running the following program from the example in "how to think like a > computer scientist" > > def countdown(n): > if n ==0: > print "Blastoff!" > else: > print n > countdown (n-1) > > countdown (1000) > > When I set "n"= 1000 the program runs in interpreter and stops counting down > at 14 instead of running all the way to "Blastoff". If I set n = 985 it > completes the program. If I set n=1200 it runs to 214 and stops. Why is > this program only counting to 986....Anybody have an answer?? > I am using Python 2.4.2 Look at this: import sys sys.getrecursionlimit() It's set to 1000 by default. (Are you using IDLE or something? That would explain where your other 14 levels of stack went.) You can change it if you want to: sys.setrecursionlevel(2000) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From jimmy at retzlaff.com Mon Nov 14 10:40:50 2005 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Mon, 14 Nov 2005 07:40:50 -0800 Subject: py2exe and pyGTK (was "Error") Message-ID: danger wrote: > hi everybody, i have a problem with py2exe that gives me this error: > > ImportError: could not import pango > ImportError: could not import pango > Traceback (most recent call last): > File "acqua.py", line 40, in ? > File "gtk\__init__.pyc", line 113, in ? > AttributeError: 'module' object has no attribute 'Font' > > does anybody knows how to solve it? Does http://www.anti-particle.com/py2exe.shtml help? Jimmy From aleax at mail.comcast.net Mon Nov 21 10:59:59 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 21 Nov 2005 07:59:59 -0800 Subject: Numeric array in unittest problem References: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> <1132586037.388588.323670@g44g2000cwa.googlegroups.com> Message-ID: <1h6da2y.qucyw7nzyjejN%aleax@mail.comcast.net> ajikoe at gmail.com wrote: > Sorry Peter, > > Try this.... > > import unittest > import Numeric > > class myTest(unittest.TestCase): > def runTest(self): > var1 = Numeric.array([1,22]) > var2 = Numeric.array([1,33]) > self.assertEqual(var1,var2) > > if __name__ == '__main__': > unittest.main() Try this interactively and you'll see why: >>> import Numeric >>> a=Numeric.array([1,22]) >>> b=Numeric.array([1,33]) >>> c = a==b >>> c array([1, 0]) >>> assert(c) i.e., thanks to element-by-element evaluation, == will generally return a true value for ANY comparison of Numeric arrays, causing a very frequent beginner's bug to be sure. Try Numeric.alltrue(c), or Numeric.allclose(a,b) ... Alex From swarnapsv at yahoo.co.in Sat Nov 5 18:58:52 2005 From: swarnapsv at yahoo.co.in (Swarna) Date: 5 Nov 2005 15:58:52 -0800 Subject: Modify HTML data Message-ID: <1131235132.163505.280600@g43g2000cwa.googlegroups.com> Hi all, Can anyone help me with this ? I am using scp in python to copy a html file on remote server, to my local machine. Now, i need to update this html file in my local machine ( by adding a new Hyperlink to the existing table od hyperlinks ) and copy it back (overwriting the old copy ) to the remote server. Thanks, for your time ! Swarna. From http Sat Nov 5 01:19:39 2005 From: http (Paul Rubin) Date: 04 Nov 2005 22:19:39 -0800 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <7xpsphlxri.fsf@ruckus.brouhaha.com> <7x3bmcaxnt.fsf@ruckus.brouhaha.com> <7x4q6r1zb8.fsf@ruckus.brouhaha.com> Message-ID: <7x64r7ty4k.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > Next you get some performance gain by using gmpy to handle the long int arithmetic, > > Then whatever happens next will be my own stupid fault for prematurely optimising code. Huh? There's nothing premature about using gmpy if you need better long int performance. It was written for a reason, after all. > > and guess what? Eventually a version of your game comes along > > that enables the postulated (but not yet implemented) mutable int > > feature of gmpy for yet more performance gains. > > This would be using Python3 or Python4? No, it would be a gmpy feature, not a Python feature. So it could be used with any version of Python. > What exactly is your point? That bugs can happen if the behaviour of your > underlying libraries changes? That your initialization scheme is brittle--the idea of data abstraction is being able to change object behaviors -without- making surprising bugs like that one. You don't even need the contrived gmpy example. You might replace the level number with, say, a list of levels that have been visited. I don't think the culprit is the mutable/immutable distinction += uses, though that is certainly somewhat odd. I think Antoon is on the right track: namespaces in Python live in sort of a ghetto unbecoming of how the Zen list describes them as a "honking great idea". These things we call variables are boxed objects where the namespace is the box. So having x+=y resolve x to a slot in a namespace before incrementing that same slot by y, maybe better uses the notion of namespaces than what happens now. I'm too sleepy to see for sure whether it gets rid of the mutable/immutable weirdness. From steve at holdenweb.com Wed Nov 2 12:32:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Nov 2005 17:32:28 +0000 Subject: Python and MySQL In-Reply-To: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: Aquarius wrote: > I appologize in advance for this strange (and possibly stupid) > question. > > I want to know if there is a way to interface a MySQL database without > Python-MySQL or without installing anything that has C files that need > to be compiled. The reason for this, is that I want to develop a > certain web application, but my hosting provider (!#@$!@#%) isn't very > eager to supply Python-MySQL (or any modules to python). Is there an > alternative approach I could use to pass around this ridiculos lack of > functionality? > You'll definitely need something to call the database API functions, I suspect. You could do a *private* install of the module though, surely, on your web host? 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 dcrespo at gmail.com Tue Nov 8 10:35:01 2005 From: dcrespo at gmail.com (dcrespo) Date: 8 Nov 2005 07:35:01 -0800 Subject: How to convert a number to hex number? In-Reply-To: References: <1131442115.025438.326670@g49g2000cwa.googlegroups.com> Message-ID: <1131464101.546746.107110@g47g2000cwa.googlegroups.com> And if you want only the hex number, try: >>>hex(255)[2:] 'ff' From carsten at uniqsys.com Wed Nov 23 20:07:41 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 23 Nov 2005 20:07:41 -0500 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> Message-ID: <20051124005226.M57600@uniqsys.com> On Wed, 23 Nov 2005 23:39:22 +0100, Christoph Zwerschke wrote > Carsten Haese schrieb: > > > Thus quoth the Zen of Python: > > "Explicit is better than implicit." > > "In the face of ambiguity, refuse the temptation to guess." > > > > With those in mind, since an odict behaves mostly like a dictionary, [] > > should always refer to keys. An odict implementation that wants to allow > > access by numeric index should provide explicitly named methods for that > > purpose. > > Exactly. But I don't think in this case such methods would be > needed. You easily get the i-th value in the ordered dict as > d.values()[i]. > > -- Chris True enough, but unless the odict has its list of values on hand, you're asking the odict to build a list of all its values just so that you can get the i'th element. Having a method that does the equivalent of d[d.sequence[i]] would be cleaner and more efficient. -Carsten From dalius.dobravolskas at gmail.com Fri Nov 18 03:01:43 2005 From: dalius.dobravolskas at gmail.com (dalius.dobravolskas at gmail.com) Date: 18 Nov 2005 00:01:43 -0800 Subject: os.path.expanduser('~/foo') and MSWindows "My Documents" In-Reply-To: <*firstname*nlsnews-994431.22563617112005@news.verizon.net> References: <*firstname*nlsnews-994431.22563617112005@news.verizon.net> Message-ID: <1132300903.052746.310240@g44g2000cwa.googlegroups.com> python >>> import os >>> help(os.path.expanduser) >>> import platform >>> platform.system() 'Windows' >>> platform.release() 'XP' >>> :-) Dalius From mikael at isy.liu.se Tue Nov 8 06:00:05 2005 From: mikael at isy.liu.se (Mikael Olofsson) Date: Tue, 08 Nov 2005 12:00:05 +0100 Subject: how to stop a loop with ESC key? [newbie] In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > works for me, when running it from a stock CPython interpreter in a windows > console window, with focus set to that window. > > what environment are you using? Could be IDLE. The code Fredrik proposed works well for me in the Python console window, but not in IDLE (thats under XP). I guess that IDLE makes use of msvcrt itself. Let's remember that the OP describes himself as a newbie in the subject, so he might not know the difference between those two interactive environments. /MiO From aleax at mail.comcast.net Wed Nov 23 23:39:49 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 20:39:49 -0800 Subject: Why are there no ordered dictionaries? References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <438258f2.411334718@news.oz.net> <4383635b.479535916@news.oz.net> <1132734447.104113.99140@o13g2000cwo.googlegroups.com> Message-ID: <1h6hymi.l5poxa18ur75N%aleax@mail.comcast.net> Christoph Zwerschke wrote: ... > d.ksort() = d.sortkeys() > d.asort() = d.sortvalues() > > d.sort() could default to one of them (not sure which one). Define JUST d.sort, you can trivially implement the other as d.sort(key=d.get). Alex From steve at holdenweb.com Thu Nov 24 03:46:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 08:46:04 +0000 Subject: wxPython Licence vs GPL In-Reply-To: <4385783D.8050201@REMOVEMEcyber.com.au> References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> <4385783D.8050201@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Steve Holden wrote: > > >>The thrust of my original remarks was to try to persuade the OP that the >>original comment about changing the code was ingenuous. If you take some >>code under license as a starting point then even if no line of code >>remains unchanged at the end of the process your code is arguably a >>derivative work of the original. > > > "Derivative work" is not a well-formed concept. Many > copyright lawyers have made many fortunes arguing > whether or not this work or that work is a derivative > work of some other. > > > Hence my use of the word "arguably". 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 fredrik at pythonware.com Thu Nov 10 11:37:19 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Nov 2005 17:37:19 +0100 Subject: A Tcl/Tk programmer learns Python--any advice? References: <1131502967.138632.94840@g47g2000cwa.googlegroups.com><1131552039.774736.298520@z14g2000cwz.googlegroups.com> Message-ID: Svenn Are Bjerkem wrote: > (and python can not do "set result [exec someprog << $input]" as far as > I know) execute a pro import subprocess From rrr at ronadam.com Mon Nov 7 23:10:01 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 08 Nov 2005 04:10:01 GMT Subject: Returning a value from a Tk dialog In-Reply-To: <0qqdnfVlLqpIYPLenZ2dnUVZ_tudnZ2d@comcast.com> References: <0qqdnfVlLqpIYPLenZ2dnUVZ_tudnZ2d@comcast.com> Message-ID: Gordon Airporte wrote: > The dialogs in tkColorChooser, tkFileDialog, etc. return useful values > from their creation somehow, so I can do stuff like this: > > filename = tkFileDialog.askopenfilename( master=self ) > > I would like to make a Yes/No/Cancel dialog that can be used the same > way (returning 1/0/-1), but I just cannot figure out how to do it. At > best I've been able to get some kind of instance id from the object. How > does this work? All of the dialogs you mention use functions as a caller. And then the function is returning the result. From tkColorChooser... def askcolor(color = None, **options): "Ask for a color" if color: options = options.copy() options["initialcolor"] = color return Chooser(**options).show() In this case the Chooser(**options) initiates the dialog, and then the show() method is called and it returns the value. The return line above is the same as... cc = Chooser(**options) color = cc.show() return color The other dialogs work in same way. They are all based on tkCommonDialog, so look in tkCommonDialog.py to see exactly what's going on. Cheers, Ron From peter at engcorp.com Sun Nov 20 14:52:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Nov 2005 14:52:17 -0500 Subject: Underscores in Python numbers In-Reply-To: <1132497336.495571.142540@g43g2000cwa.googlegroups.com> References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> <1132476670.992305.106250@o13g2000cwo.googlegroups.com> <1132497336.495571.142540@g43g2000cwa.googlegroups.com> Message-ID: <7LKdnRwmT9dzTh3eRVn-uQ@powergate.ca> bonono at gmail.com wrote: > Peter Hansen wrote: > >>But why would anyone want to create numeric literals for credit card >>numbers? >> > May be for space saving ? But storage space being so cheap, this is not > a very good reason, but still a reason. Space saving where? Why would you have any credit card numbers stored in any application? Even a credit card company isn't going to write code that has the numbers stored as *literals*! There's only one place I can think of right now where you might want that: in automated tests for code that processes credit card numbers. And you definitely do not need to "save space" in that situation... -Peter From could.net at gmail.com Wed Nov 30 20:58:18 2005 From: could.net at gmail.com (could ildg) Date: Wed, 30 Nov 2005 17:58:18 -0800 Subject: Is Python string immutable? Message-ID: <311b5ce10511301758y13707430l13a27182713c79b@mail.gmail.com> In java and C# String is immutable, str=str+"some more" will return a new string and leave some gargabe. so in java and C# if there are some frequent string operation, StringBuilder/StringBuffer is recommanded. Will string operation in python also leave some garbage? I implemented a net-spider in python which includes many html string procession. After it running for sometime, the python exe eats up over 300M memory. Is this because the string garbages? If String in python is immutable, what class should I use to avoid too much garbages when processing strings frequently? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Fri Nov 11 20:21:12 2005 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 11 Nov 2005 17:21:12 -0800 Subject: weird problem with os.chmod In-Reply-To: <43753D14.8040400@colannino.org> References: <43753C13.2010609@colannino.org> <43753D14.8040400@colannino.org> Message-ID: <43754388.6060303@islandtraining.com> James Colannino wrote: >James Colannino wrote: > > > >>So then I entered the command print 0600, and saw that the >>actual number being output was 384 (why would it output 384?!) >> >> >> >> > >Ok, so further research revealed that 0600 is actually the octal >representation for 384 (which makes sense.) So then, I guess my >question would have to be, is there a way for me to make Python aware >that the 0600 I'm passing to int() is octal and not decimal so that I >will get 384 instead of 600? > > int('0600',8) will do, but why would you want to do that? Any of x = 0600 x = 384 x = 0x180 x = int('0600',8) will bind x to the same value (110000000 in binary if you care). But once you've got the valued defined, through whatever human readable representation you want, the command chmod(filename, x) can be issued without further thought. From p at ulmcnett.com Wed Nov 30 19:53:24 2005 From: p at ulmcnett.com (Paul McNett) Date: Wed, 30 Nov 2005 16:53:24 -0800 Subject: wxPython installation issues on Debian In-Reply-To: <1133388676.563922.55190@g14g2000cwa.googlegroups.com> References: <1132795557.301034.92000@o13g2000cwo.googlegroups.com> <1133373197.812027.135740@g44g2000cwa.googlegroups.com> <1133388676.563922.55190@g14g2000cwa.googlegroups.com> Message-ID: <438E4984.1010804@ulmcnett.com> amhoov at yahoo.com wrote: > Thanks a lot for the clarification. I don't have a compelling reason > not to use 2.3 other than having to install the modules I've already > set up for 2.4. Not really a big deal. Looks like I'll be switching to > 2.3. Umm, for what it's worth: I'm on Ubuntu (a Debian derivative), using Python 2.4.2 and wxPython 2.6. The wxPython was installed using 'apt-get install python-wxGtk2.6'. So I don't know why you say you need to use Python 2.3 as I don't even have that on my system. -- Paul McNett http://paulmcnett.com http://dabodev.com From kent37 at tds.net Sun Nov 20 07:18:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Nov 2005 07:18:00 -0500 Subject: Web-based client code execution In-Reply-To: References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> Message-ID: <438066d7$1_3@newspeer2.tds.net> Stephen Kellett wrote: > In message <1132342910.799932.58720 at g44g2000cwa.googlegroups.com>, Steve > writes > >> AJAX works because browsers can execute javascript. I don't know of a >> browser that can execute python. Basically your stuck with java or >> javascript because everything else really isn't cross platform. > > > ActiveState do a version of Python that can run in a script tag like > JavaScript and VBScript. This requires Windows Scripting Host. They also > do a similar thing for Perl, not sure about TCL. See http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830 Kent From mwm at mired.org Wed Nov 30 15:23:31 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 15:23:31 -0500 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> <86u0duodzl.fsf@bhuda.mired.org> <7xlkz663re.fsf@ruckus.brouhaha.com> Message-ID: <86ek4xopfg.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> Letting the class author declare whether or not the client can add >> attributes is wrong for the same reasons - and in the same places - >> that letting the class author declare that the client shouldn't be >> allowed to access specific attributes, and so on, is wrong. > The same logic can apply to what the class operations should do. The > answer is the same in both cases. That's why subclassing and > inheritance were invented. Exactly. Adding an attribute is isomorphic to subclassing, except it doesn't' take any boilerplate. Unless you do something to prevent people from subclassing, they can always write the boilerplate and pretty much continue as before. I don't believe there's a good reason for preventing the boilerplate free method, and repeated requests for a use case for this have gone unsatisied. Have you got a use case? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jepler at unpythonic.net Wed Nov 2 22:38:44 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 2 Nov 2005 21:38:44 -0600 Subject: install warning In-Reply-To: <1130986201.152126.248670@z14g2000cwz.googlegroups.com> References: <1130986201.152126.248670@z14g2000cwz.googlegroups.com> Message-ID: <20051103033844.GA17398@unpythonic.net> You are importing and using, directly or indirectly, the "strop" module. Here's an example from the interactive interpreter which triggers the warning: $ python2.3 Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import strop >>> strop.strip(" abc ") __main__:1: DeprecationWarning: strop functions are obsolete; use string methods 'abc' Most of the things in strop are now simply methods on string objects: >>> " abc ".strip() 'abc' Another way to prevent the warning from being printed is through use of the 'warnings' module, which is documented on docs.python.org. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From aum at spam.me.please Mon Nov 7 05:44:02 2005 From: aum at spam.me.please (aum) Date: Mon, 07 Nov 2005 23:44:02 +1300 Subject: PyFLTK - an underrated gem for GUI projects References: Message-ID: On Mon, 07 Nov 2005 12:25:49 +0100, egbert wrote: > PyFLTK is not a debian package - yet. > Is nobody interested, or is there a more specific reason ? AFAIK, the maintainer feels it's still at release-candidate stage. When he's happy with it, I'm sure he could be persuaded to make arrangements to .deb it, or get someone else to. In the meantime, it does build ok on Debian, provided you build/install libfltk from source, and set the FLTK_HOME env var to point into it before running the pyfltk setup.py, as per the instructions in pyfltk tarball. -- Cheers David From fuzzyman at gmail.com Thu Nov 24 10:09:26 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Nov 2005 07:09:26 -0800 Subject: Help me to catch this exception :-) In-Reply-To: References: Message-ID: <1132844966.571253.186270@g49g2000cwa.googlegroups.com> I don't know the answer, but I like the problem. :-) What happens with the standard CGIHttpServer ? Fuzzyman http://www.voidspace.org.uk/python/index.shtml From dcrespo at gmail.com Fri Nov 18 14:02:40 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 18 Nov 2005 11:02:40 -0800 Subject: How to do "new_variable = (variable) ? True : False; " (php) on python? Message-ID: <1132338596.452441.139200@g44g2000cwa.googlegroups.com> Hello to all, How can I do new_variable = (variable) ? True : False; in Python in one line? I want to do something like this: dic = {'item1': (variable) ? True-part : False-part} Any suggestions? Daniel From berrybear at gmx.net Mon Nov 28 10:36:49 2005 From: berrybear at gmx.net (Anton81) Date: Mon, 28 Nov 2005 16:36:49 +0100 Subject: Precision for equality of two floats? Message-ID: Hi! When I do simple calculation with float values, they are rarely exactly equal even if they should be. What is the threshold and how can I change it? e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:" Anton From rnd at onego.ru Thu Nov 3 01:12:06 2005 From: rnd at onego.ru (Roman Suzi) Date: Thu, 3 Nov 2005 08:12:06 +0200 (EET) Subject: Pychecker Re: Nested List Question In-Reply-To: <1130996191_2067@spool6-east.superfeed.net> References: <1130995475_2055@spool6-east.superfeed.net> <1h5f4t2.1yv785h120xalfN%aleax@mail.comcast.net> <1130996191_2067@spool6-east.superfeed.net> Message-ID: On Thu, 3 Nov 2005, Chris McCoy wrote: > Thank you! I've been banging my head against the wall! > > Chris M. >> gridSystemId = [[None]*columns]*rows > > You've made gridSystemID a list of `rows` references to the SAME "inner" > list, so the behavior you observe is the only possible one. > > If you want copies instead, ASK for copies...: > > gridSystemId = [ [None]*columns for x in xrange(rows) ] Interesting, could not pychecker recognize such situations in Python code and give warnings? Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From tony.meyer at gmail.com Sun Nov 27 00:22:32 2005 From: tony.meyer at gmail.com (Tony Meyer) Date: Sun, 27 Nov 2005 18:22:32 +1300 Subject: python-dev Summary for 2005-11-01 through 2005-11-15 Message-ID: <6c63de570511262122s1c6143fai6f8d726ddc7648cf@mail.gmail.com> [The HTML version of this Summary will be available at http://www.python.org/dev/summary/2005-11-01_2005-11-15.html] ============= Announcements ============= ---------------------------------------- PyPy 0.8.0 and Gothenburg PyPy Sprint II ---------------------------------------- `PyPy 0.8.0`_ has been released. This third release of PyPy includes a translatable parser and AST compiler, some speed enhancements (transated PyPy is now about 10 times faster than 0.7, but still 10-20 times slower than CPython), increased language compliancy, and some experimental features are now translatable. This release also includes snapshots of interesting, but not yet completed, subprojects including the OOtyper (a RTyper variation for higher-level backends), a JavaScript backend, a limited (PPC) assembler backend, and some bits for a socket module. The next PyPy Sprint is also coming up soon. The Gothenborg PyPy Sprint II is on the 7th to 11th of December 2005 in Gothenborg, Sweden. Its focus is heading towards phase 2, which means JIT work, alternate threading modules, and logic programming. Newcomer-friendly introductions will also be given. The main topics that are currently scheduled are the L3 interpreter (a small fast interpreter for "assembler-level" flow graphs), Stackless (e.g. Tasklets or Greenlets), porting C modules from CPython, optimization/debugging work, and logic programming in Python. .. _`PyPy 0.8.0`: http://codespeak.net/pypy/dist/pypy/doc/release-0.8.0.html Contributing threads: - `PyPy 0.8.0 is released! < http://mail.python.org/pipermail/python-dev/2005-November/057878.html>`__ - `Gothenburg PyPy Sprint II: 7th - 11th December 2005 < http://mail.python.org/pipermail/python-dev/2005-November/058143.html>`__ [TAM] ------------------------ PyCon Sprint suggestions ------------------------ Every PyCon has featured a python-dev `sprint`_. For the past few years, hacking on the AST branch has been a tradition, but since the AST branch has now been merged into the trunk, other options are worth considering this year. Several PEP implementations were suggested, including `PEP 343`_ ('with:'), `PEP 308`_ ('x if y else z'), `PEP 328`_ ('absolute/relative import'), and `PEP 341`_ ('unifying try/except and try/finally'). Suggestions to continue the AST theme were also made, including one of the "global variable speedup" PEPs, `Guido's instance variable speedup idea`_, using the new AST code to improve/extend/rewrite the optimization steps the compiler performs, or rewriting PyChecker to operate from the AST representation. Phillip J. Eby also suggested working on the oft-mentioned bytes type. All of these suggestions, as well as any others that are made, are being recorded on the `PythonCore sprint wiki`_. .. _sprint: http://wiki.python.org/moin/PyCon2006/Sprints .. _PEP 343: http://www.python.org/peps/pep-0343.html .. _PEP 308: http://www.python.org/peps/pep-0308.html .. _PEP 328: http://www.python.org/peps/pep-0328.html .. _PEP 341: http://www.python.org/peps/pep-0341.html .. _Guido's instance variable speedup idea: http://mail.python.org/pipermail/python-dev/2002-February/019854.html .. _PythonCore sprint wiki: http://wiki.python.org/moin/PyCon2006/Sprints/PythonCore Contributing threads: - `python-dev sprint at PyCon < http://mail.python.org/pipermail/python-dev/2005-November/057830.html>`__ - `PEP 328 - absolute imports (python-dev sprint at PyCon) < http://mail.python.org/pipermail/python-dev/2005-November/057853.html>`__ [TAM] -------------------------------------- Reminder: Python is now on Subversion! -------------------------------------- Just a reminder to everyone that the Python source repository_ is now hosted on Subversion. A few minor bugs were fixed, so you can make SVK mirrors of the repository successfully now. Be sure to check out the newly revised Python Developers FAQ_ if you haven't already. .. _repository: http://svn.python.org/projects/ .. _FAQ: http://www.python.org/dev/devfaq.html Contributing threads: - `Freezing the CVS on Oct 26 for SVN switchover < http://mail.python.org/pipermail/python-dev/2005-November/057823.html>`__ - `svn checksum error < http://mail.python.org/pipermail/python-dev/2005-November/057843.html>`__ - `Problems with revision 4077 of new SVN repository < http://mail.python.org/pipermail/python-dev/2005-November/057867.html>`__ - `No more problems with new SVN repository < http://mail.python.org/pipermail/python-dev/2005-November/057888.html>`__ - `dev FAQ updated with day-to-day svn questions < http://mail.python.org/pipermail/python-dev/2005-November/057999.html>`__ - `Mapping cvs version numbers to svn revisions? < http://mail.python.org/pipermail/python-dev/2005-November/058051.html>`__ - `Checking working copy consistency < http://mail.python.org/pipermail/python-dev/2005-November/058056.html>`__ - `Is some magic required to check out new files from svn? < http://mail.python.org/pipermail/python-dev/2005-November/058065.html>`__ [SJB] --------------------------- Updating the Python-Dev FAQ --------------------------- Brett Cannon has generously volunteered to clean up some of the developers' documentation and wants to know if people would rather the bug/patch guidelines to be in a classic paragraph-style layout or a more FAQ-style layout. If you have an opinion on the topic, please let him know! Contributing threads: - `dev FAQ updated with day-to-day svn questions < http://mail.python.org/pipermail/python-dev/2005-November/058025.html>`__ - `Revamping the bug/patch guidelines (was Re: Implementation of PEP 341) < http://mail.python.org/pipermail/python-dev/2005-November/058108.html>`__ [SJB] ========= Summaries ========= ----------- Event loops ----------- This thread initiated in discussion on sourceforge about patches 1049855_ and 1252236_; Martin v. L?wis and Michiel de Hoon agreed that the fixes were fragile, and that a larger change should be discussed on python-dev. Michiel writes visualization software; he (and others, such as the writers of matplotlib) has trouble creating a good event loop, because the GUI toolkit (especially Tkinter) wants its own event loop to be in charge. Michiel doesn't actually need Tkinter for his own project, but he has to play nice with it because his users expect to be able to use other tools -- particularly IDLE -- while running his software. Note that this isn't the first time this sort of problem has come up; usually it is phrased in terms of a problem with Tix, or not being able to run turtle while in IDLE. Event loops by their very nature are infinite loops; once they start, everything else is out of luck unless it gets triggered by an event or is already started. Donovan Baarda suggested looking at Twisted for state of the art in event loop integration. Unfortunately, as Phillip Eby notes, it works by not using the Tkinter event loop. It decides for itself when to call dooneevent (do-one-event). It is possible to run Tkinter's dooneevent version as part of your own event loop (as Twisted does), but you can't really listen for its events, so you end up with a busy loop polling, and stepping into lots of "I have nothing to do" functions for every client eventloop. You can use Tkinter's loop, but once it goes to sleep waiting for input, everything sort of stalls out for a while, and even non-Tkinter events get queued instead of processed. Mark Hammond suggests that it might be easier to replace the interactive portions of python based on the "code" module. matplotlib suggests using ipython instead of standard python for similar reasons. Another option might be to always start Tk in a new thread, rather than letting it take over the main thread. There was some concern (see patch 1049855) that Tkinter doesn't - and shouldn't - require threading. [Jim Jewett posted a summary of this very repetitive and confusing (to the participants, not just summarizers!) thread towards its end, which this summary is very heavily based on. Many thanks Jim!] Contributing threads: - `Event loops, PyOS_InputHook, and Tkinter < http://mail.python.org/pipermail/python-dev/2005-November/057954.html>`__ - `Event loops, PyOS_InputHook, and Tkinter - Summary attempt < http://mail.python.org/pipermail/python-dev/2005-November/058034.html>`__ .. _1049855: http://www.python.org/sf/1049855 .. _1252236: http://www.python.org/sf/1252236 [TAM] ----------------------------- Importing .pyc and .pyo files ----------------------------- Osvaldo Santana Neto pointed out that if a .pyo file exists, but a .pyc doesn't, then a regularly run python will not import it (unless run with -O), but if the .pyo is in a zip file (which is on the PYTHONPATH) then it will import it. He felt that the inconsistency should be addressed and that the zipimport behaviour was preferable. However, Guido said that his intention was always that, without -O, *.pyo files are entirely ignored (and, with -O, *.pyc files are entirely ignored). In other words, it is the zipimport behaviour that is incorrect. Guido suggested that perhaps .pyo should be deprecated altogether and instead we could have a post-load optimizer optimize .pyc files according to the current optimization settings. The two use cases presented for including .pyo files but not .py files were in situations where disk space is at a premium, and where a proprietary "canned" application is distributed to end users who have no intention or need to ever add to the code. A suggestion was that a new bytecode could be introduced for assertions that would turn into a jump if assertions were disabled (with -O). Guido thought that the idea had potential, but pointed out that it would take someone thinking really hard about all the use cases, edge cases, implementation details, and so on, in order to write a PEP. He suggested that Brett and Phillip might be suitable volunteers for this. Contributing thread: - `Inconsistent behaviour in import/zipimport hooks < http://mail.python.org/pipermail/python-dev/2005-November/057959.html>`__ [TAM] --------------------------------------- Default __hash__() and __eq__() methods --------------------------------------- Noam Raphael suggested that having the default __hash__() and __eq__() methods based off of the object's id() might have been a mistake. He proposed that the default __hash__() method be removed, and the default __eq__() method compare the two objects' __dict__ and slot members. Jim Fulton offered a counter-proposal that both the default __hash__() and __eq__() methods should be dropped for Python 3.0, but Guido convinced him that removing __eq__() is probably a bad idea; it would mean an object wouldn't compare equal to itself. In the end, Guido decided that having a default __hash__() method based on id() isn't really a bad decision; without it, you couldn't have sets of "identity objects" (objects which don't have a usefully defined value-based comparison). He suggested that the right decision was to make the hash() function smarter, and have it raise an exception if a class redefined __eq__() without redefining __hash__(). (In fact, this is what it used to do, but it was lost when object.__hash__() was introduced.) Contributing threads: - `Why should the default hash(x) == id(x)? < http://mail.python.org/pipermail/python-dev/2005-November/057859.html>`__ - `Should the default equality operator compare values instead of identities? < http://mail.python.org/pipermail/python-dev/2005-November/057868.html>`__ - `For Python 3k, drop default/implicit hash, and comparison < http://mail.python.org/pipermail/python-dev/2005-November/057924.html>`__ [SJB] --------------------------- Indented multi-line strings --------------------------- Avi Kivity reintroduced the oft-requested means of writing a multi-line string without getting the spaces from the code indentation. The usual options were presented:: def f(...): ... msg = ('From: %s\n' 'To: %s\n' 'Subject: Host failure report for %s\n') ... msg = '''\ From: %s To: %s Subject: Host failure report for %s''' ... msg = textwrap.dedent('''\ From: %s To: %s Subject: Host failure report for %s''') Noam Raphael suggested that to simplify the latter option, textwrap.dedent() should become a string method, str.dedent(). There were also a few suggestions that this sort of dedenting should have syntactic support (e.g. with an appropriate string prefix). In general, the discussion harkened back to `PEP 295`_, a similar proposal that was previously rejected. People tossed the ideas around for a bit, but it didn't look like any changes were likely to be made. .. _PEP 295: http://www.python.org/peps/pep-0295.html Contributing threads: - `indented longstrings? < http://mail.python.org/pipermail/python-dev/2005-November/058042.html>`__ - `str.dedent < http://mail.python.org/pipermail/python-dev/2005-November/058058.html>`__ - `OT pet peeve (was: Re: str.dedent) < http://mail.python.org/pipermail/python-dev/2005-November/058072.html>`__ [SJB] ------------------ Continued AST work ------------------ Neal Norwitz has been chasing down memory leaks; he believes that the current AST is now as good as before the AST branch was merged in. Nick explained that he is particularly concerned about the returns hidden inside in macros in the AST compiler's symbol table generation and bytecode generation steps. Niko Matsakis suggested that an arena is the way to go for memory management; the goal is to be able to free memory en-masse whatever happens and not have to track individual pointers. Jeremy Hylton noted that the AST phase has a mixture of malloc/free and Python object allocation; he felt that it should be straightforward to change the malloc/free to use an arena API, but that a separate mechanism would be needed to associate a set of PyObject* with the arena. The arena concept gained general approval, and there was some discussion about how best to implement it. In other AST news Rune Holm submitted two_ patches_ for the AST compiler that add better dead code elimination and constant folding and Thomas Lee is attempting to implement `PEP 341`_ (unification of try/except and try/finally), and asked for some help (Nick Coghlan gave some suggestions). .. _two: http://www.python.org/sf/1346214 .. _patches: http://www.python.org/sf/1346238 .. _PEP 341: http://python.org/peps/pep-0341.html Contributing threads: - `Optimizations on the AST representation < http://mail.python.org/pipermail/python-dev/2005-November/057865.html>`__ - `Implementation of PEP 341 < http://mail.python.org/pipermail/python-dev/2005-November/058075.html>`__ - `ast status, memory leaks, etc < http://mail.python.org/pipermail/python-dev/2005-November/058089.html>`__ - `Memory management in the AST parser & compiler < http://mail.python.org/pipermail/python-dev/2005-November/058138.html>`__ - `PEP 341 patch & memory management (was: Memory management in the AST parser & compiler) < http://mail.python.org/pipermail/python-dev/2005-November/058142.html>`__ [TAM] --------------------------------------------------------------------- Adding functional methods (reduce, partial, etc.) to function objects --------------------------------------------------------------------- Raymond Hettinger suggested that some of the functionals, like map or partial, might be appropriate as attributes of function objects. This would allow code like:: results = f.map(data) newf = f.partial(somearg) A number of people liked the idea, but it was pointed out that map() and partial() are intended to work with any callable, and turning these into attributes of function objects would make it hard to use them with classes that define __call__(). Guido emphasized this point, saying that complicating the callable interface was a bad idea. Contributing thread: - `a different kind of reduce... < http://mail.python.org/pipermail/python-dev/2005-November/057828.html>`__ [SJB] -------------------------------------------------- Distributing debug build binaries (python2x_d.dll) -------------------------------------------------- David Abrahams asked whether it would be possible for python.org to make a debug build of the Python DLL more accessible. Thomas Heller pointed out that the Microsoft debug runtime DLLs are not distributable (which is why the Windows installer does not include the debug version of the Python DLL), and that the ActiveState distribution contains Python debug DLLs. Tim Peters explained that when he used to collect up the debug-build bits at the time the official installer was built, they weren't included in the main installer, because they bloated its size for something that most users don't want. He explained that he stopped collecting the bits because no two users wanted the same set of stuff, and so it grew so large that people complained that it was too big. Tim suggested that the best thing to do would be to define precisely what an acceptable distribution format is and what exactly it should contain. Martin indicated that he would accept a patch that picked up the files and packages them, and he would include them in the official distribution. Contributing thread: - `Plea to distribute debugging lib < http://mail.python.org/pipermail/python-dev/2005-November/057896.html>`__ [TAM] ----------------------------------- Creating a python-dev-announce list ----------------------------------- Jack Jansen suggested that a low-volume, moderated, python-dev-announce mailing list be created for time-critical announcements for people developing Python. The main benefit would be the ability to keep up with important announcements such as new releases, the switch to svn, and so on, even when developers don't have time to keep up with all threads. Additionally, it would be easier to separate out such announcements, even when following all threads. Although these summaries exist (and the announcements section at the top pretty much covers what Jack is after), the summaries occur at least a week after the end of the period that they cover, which could be as much as three weeks after any announcement (if it occurred on the first of a month, for example). I suggested that a simpler possibility might follow along the lines of the PEP topic that the python-checkins list provides (a feature of Mailman). This would still require some sort of effort by the announcer (e.g. putting some sort of tag in the subject), but wouldn't require an additional list, or additional moderators. However, Martin pointed out that this would put an extra burden on people to remember to post to such a list; this burden would also exist using the Mailman topic mechanism. There wasn't much apparent support for the list, so this seems unlikely to occur at present. Of course, that could be because the people that would like it are too busy to have noticed the thread yet <0.5 wink>, so perhaps there is more to come. Contributing thread: - `Proposal: can we have a python-dev-announce mailing list? < http://mail.python.org/pipermail/python-dev/2005-November/057880.html>`__ [TAM] ------------------------------------- Notifications of weakref dereferences ------------------------------------- When integrating with another system (such as gtk), it can be useful if each object in the other system maps to (at most) one python wrapper. If python references drop to zero, then the next python reference would (by default) create a different wrapper object. So the wrapper tries to stay alive (with only a weak reference to the true object) as long as the true object does. But if that wrapper does get used, it needs to replace the weak reference with a strong reference. The standard weakref callbacks weren't quite up to the task, but it looked like there were workarounds, either by abusing weakref methods in a subtask, or by changing the architecture slightly. Contributing thread: - `Weak references: dereference notification < http://mail.python.org/pipermail/python-dev/2005-November/057961.html>`__ [Jim Jewett] -------------------------------------------- Should 1.2 be a floating point or a decimal? -------------------------------------------- There was general agreement that decimal might deserve a literal marker of its own in python 3.0, but much less agreement that it should be the default floating or fixed point representation. Decimals are better for many business applications, but floats are faster and are better for most scientific and engineering applications. Contributing thread: - `Unifying decimal numbers. < http://mail.python.org/pipermail/python-dev/2005-November/057951.html>`__ [Jim Jewett] ----------------------- Speeding up int(string) ----------------------- Uncle Timmy wants python to do better on certain benchmarks, and gave `an example`_. The bottleneck turns out to be parsing an integer from a string. At the moment, this is not only slow, it has potential bugs. Patches were submitted, but had not been applied at the time this summary was written. .. _an example: http://spoj.sphere.pl/ Contributing threads: - `int(string) (was: DRAFT: python-dev Summary for 2005-09-01 through 2005-09-16) < http://mail.python.org/pipermail/python-dev/2005-November/057994.html>`__ - `to_int -- oops, one step missing for use. < http://mail.python.org/pipermail/python-dev/2005-November/058006.html>`__ - `(no subject) < http://mail.python.org/pipermail/python-dev/2005-November/058023.html>`__ [Jim Jewett] ---------------------------------------------------- Building Python with Visual C++ 2005 Express Edition ---------------------------------------------------- Is it possible? Probably, but like other newer VC++ there are problems, particularly with changes to crt, and deprecation of standard interfaces. It won't become the "standard" build tool. Contributing thread: - `Building Python with Visual C++ 2005 Express Edition < http://mail.python.org/pipermail/python-dev/2005-November/058024.html>`__ [Jim Jewett] ------------------------ Freezing mutable objects ------------------------ `Last fortnight's thread` about ways to take an immutable snapshot of an otherwise mutable object continued. Discussions centered around how true the reflection has to be, and how to do this efficiently; an agreement was difficult to come to. Contributing thread: - `apparent ruminations on mutable immutables (was: PEP 351, the freeze protocol) < http://mail.python.org/pipermail/python-dev/2005-November/057839.html>`__ .. _Last fortnight's thread: http://www.python.org/dev/summary/2005-10-16_2005-10-31.html#freeze-protocol [TAM] =============== Skipped Threads =============== - `Divorcing str and unicode (no more implicit conversions). < http://mail.python.org/pipermail/python-dev/2005-November/057827.html>`__ - `[C++-sig] GCC version compatibility < http://mail.python.org/pipermail/python-dev/2005-November/057831.html>`__ - `PYTHOPN_API_VERSION < http://mail.python.org/pipermail/python-dev/2005-November/057879.html>`__ - `Adding examples to PEP 263 < http://mail.python.org/pipermail/python-dev/2005-November/057891.html>`__ - `Class decorators vs metaclasses < http://mail.python.org/pipermail/python-dev/2005-November/057904.html>`__ - `PEP 352 Transition Plan < http://mail.python.org/pipermail/python-dev/2005-November/057911.html>`__ - `PEP submission broken? < http://mail.python.org/pipermail/python-dev/2005-November/057935.html>`__ - `cross-compiling < http://mail.python.org/pipermail/python-dev/2005-November/057939.html>`__ - `[OTAnn] Feedback < http://mail.python.org/pipermail/python-dev/2005-November/057941.html>`__ - `Weekly Python Patch/Bug Summary < http://mail.python.org/pipermail/python-dev/2005-November/057949.html>`__ - `Coroutines (PEP 342) < http://mail.python.org/pipermail/python-dev/2005-November/058133.html>`__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from November 01, 2005 through November 15, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the 7th summary written by the python-dev summary squad of Steve Bethard and Tony Meyer (so nice to be back on time!). To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/2005-10-01_2005-10-15.html .. _original text file: http://www.python.org/dev/summary/2005-11-01_2005-11-15.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Wed Nov 9 20:53:00 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Thu, 10 Nov 2005 01:53:00 GMT Subject: Pythonising the vim (e.g. syntax popups) -> vimpst In-Reply-To: References: <200511091609.09613.email@christoph-haas.de> Message-ID: <0Kxcf.3783$Ea3.955649@twister.southeast.rr.com> Roman Roelofsen wrote: >>Evening, >> >>Is there a decent way to get that help into vim? Or like showing docstrings >>or help that I get through pydoc on request? I've been working myself >>through a pile of vim macros/plugins but couldn't find even one which >>simplifies programming in Python. Further issues would be handling the > > > Hi Christoph, > Hi Vim users, > > The last 5 days I?ve been working on a code-completion/calltips plugin for > vim. It?s working pretty good but not finished yet. I will anounce the first > beta version on this mailling list. I hope during the next week. > > I recorded a swf-video so that you can take a look at the current status. > Link: http://www.tuxed.de/vimpst/video.tar.gz > > Note that it is not necessary to generate symboltable files, etc. Everything > is done "on demand". It is even possible to change the python implementation > e.g. CPython, Jython, IronPython. > > It is also possible to add some "special feature" interceptor. Currently this > is working for SQLObject: > Lets say you have the class User and the attribute username is a alternate ID. > Then, the method User.byUsername("...") will always return a User object. > vimpst checks this and provides a suitable help. Right on! Good luck! Can't wait! From bonono at gmail.com Thu Nov 24 02:32:07 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 23:32:07 -0800 Subject: wxPython Licence vs GPL In-Reply-To: References: Message-ID: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> Steve Holden wrote: > Whether or not some fragments of code remain unchanged at the end of > your project, if you start out with a piece of source code lifted from > wxPython then what you have created is definitely a "derivative work" > and, as such, you must take into account the wxPython license in your > licensing of the derivative work. > Is that true ? What if I remove/replace the copyright doubtful portion with another implementation ? I believe this happens all the time in commerical software sue too. From http Sat Nov 26 03:36:51 2005 From: http (Paul Rubin) Date: 26 Nov 2005 00:36:51 -0800 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> <86fypkim4x.fsf@bhuda.mired.org> Message-ID: <7xhd9zerfg.fsf@ruckus.brouhaha.com> Mike Meyer writes: > Those two statements say the same thing. Part of the Python philosphy, > from "import this", is that there should only be one obvious way to do > it. By enabling that part of Python's philosphy, you're automatically > limiting python to not allow other - specifically non-pythonic - ways > to do the same thing. Sometimes there are zero obvious ways to do it, or an obvious way that doesn't work, so if you want to do it at all, you have to find a contorted way. At that point it's normal to ask why there isn't an obvious way that works. All too often, the answer is "that would be un-Pythonic". From bonono at gmail.com Thu Nov 24 04:04:46 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 01:04:46 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: <1132820426.374743.51410@g49g2000cwa.googlegroups.com> Message-ID: <1132823086.393860.150830@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > > I know that is a single list of tuples, I mean that can be used as > > well. > > > > for k, _ in d.items(): print k > > for _, v in d.items(): print v > > for k in d.keys(): print k > > for v in d.values(): print v > > > > Would there be a noticeable performance difference ? > > Sloppy use of print statements is a great way to produce misleading > benchmarks [1], since the time it takes to print lots of stuff tends to > overshadow the actual algorithm (for bonus points, print to a terminal > window, and use "time" to measure performance, so you get startup > times as well). If you don't necessarily want to print all the stuff, my > original assertion still holds: > > "creating a list full of tuples just to pull them apart and throw > them all away isn't exactly the most efficient way to do things" > > Consider a dictionary with one million items. The following operations > > k = d.keys() > v = d.values() > > creates two list objects, while > > i = d.items() > > creates just over one million objects. In your "equivalent" example, Sorry. I lose you here. Could you explain in detail what do you mean by "two list objects" vs one million objects ? From aleax at mail.comcast.net Fri Nov 18 17:24:02 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 18 Nov 2005 14:24:02 -0800 Subject: Importing a class without knowing the module References: <867jb6n7cw.fsf@bhuda.mired.org> <86veyqlnrn.fsf@bhuda.mired.org> <1h66rw8.wlp7nb19e5629N%aleax@mail.comcast.net> <86k6f6lgvy.fsf@bhuda.mired.org> <1h66w9j.1d82do2qfe2b1N%aleax@mail.comcast.net> <86zmo2jvsw.fsf@bhuda.mired.org> <1h67qx0.1y62ktrcq00pbN%aleax@mail.comcast.net> <86psoxkcgb.fsf@bhuda.mired.org> Message-ID: <1h686or.1t4dvb17nsb8wN%aleax@mail.comcast.net> Mike Meyer wrote: ... > > How do you arrange a module so that its classes' __module__ attributes > > don't tell you the name of the module "that would be useful", yet the > > module's __file__ DOES give you information that you can usefully > > process, heuristically I assume, to infer a module name that IS useful? > > So what module name do you import if C.__module__ is __main__? In this case, I would strongly suggest that raising an exception upon the attempt to marshal is better than trying to guess that the file holding the main script could later be innocuously imported from a different script, or, alternatively, that the same main script would be running when a future unmarshaling attempt is done. "In the face of ambiguity, refuse the temptation to guess" is a sound principle. > > I just don't see it, which of course doesn't mean it can't be done, with > > sufficient evil ingenuity. But since you're the one arguing that this > > case is important enough to be worth dwelling on, > > I'm not dwelling on it, you are. All I did was recommend using the > module name if you had one, and if not then the file name was your > best bet. You chose to ignore part of my statement to focus on the > part you disagreed with, because you thought what I had suggested in > the first place was a better idea. I pointed out this oversight on > your part, and you've been dwelling on it ever since. I don't see the history of this thread the same way as you do, apparently. I first posted to this thread in a post identified as: """ Date: Thu, 17 Nov 2005 17:28:56 -0800 Message-ID: <1h66lub.295q3b19n84anN%aleax at mail.comcast.net> """ and later replied to a post of yours identified as: """ Date: Thu, 17 Nov 2005 23:27:45 -0500 Message-ID: <86k6f6lgvy.fsf at bhuda.mired.org> """ i.e., your post, to which I was replying, was about 3 hours later than my original one. My original post said: > BEFORE the text you're commenting on?!), but anyway I think that using > the class's __module__ rather than __file__ should be what you want. so it seems incorrect to say that you had "suggested in the first place" the idea of using __module__; on the contrary, in a previous post of yours, the first one of yours on this thread, specifically: """ Date: Thu, 17 Nov 2005 19:10:39 -0500 Message-ID: <867jb6n7cw.fsf at bhuda.mired.org> """ your ENTIRE suggestion -- what you "suggested in the first place" -- was the entirely wrong: > How about adding Foo.__file__ to the serialized data? So, it seems to me that you're the one dwelling on the issue, because you made the original wrong suggestion, and after I corrected it, repeated and are now defending the gist of it (though not the obviously wrong idea of using a non-existent __file__ attribute of the Foo class). > Frankly, I thought you were brighter than that, have no idea why > you're acting like this, and frankly don't think you need a tutor. I > figured this out by fooling around with the interpreter before posting > in the first place, you certainly know enough to do the same. "Before posting in the first place" (your post at 19:10 EST) you clearly had not tested your suggestion (nor had you claimed to, until now). In any case, if your specific idea is that mucking around with the __file__ attribute of the __main__ module is a reasonable way to solve the conumdrum of marshaling instances of classes defined in __main__ (which, as per the first paragraph of this post, I dispute) it would have been vastly preferable to say so in the first place, rather than expressing this particular case as just an "If not" (wrt "You can use the module name if you have it available") -- particularly since you DO have the module name available for classes defined in __main__, it's just suspicious and risky to use it in marshaling. Incidentally, pickle DOES just use the module name in marshaling even in this case -- the opposite tack to what you suggest, and, in its own special way, almost as wrong, IMHO (just guessing the other way, in the presence of obvious ambiguity). Still, pickle does take ONE precaution worth noticing: it checks that the class it's marshaling is, in fact, the same object that's available under that class's name from the module it belongs to -- otherwise (e.g., for classes dynamically defined inside a function), it raises a PicklingError. As a general point, refusing to marshal data that strongly smells like it will be hard or unlikely to unmarshal later is commendable prudence, and I would recommend this general, prudent approach strongly. Alex From http Thu Nov 10 17:27:32 2005 From: http (Paul Rubin) Date: 10 Nov 2005 14:27:32 -0800 Subject: exceptions, internals (introspection?) References: <4373ae4a$1@nntp.zianet.com> <7x64r04473.fsf@ruckus.brouhaha.com> <4373c62d$1@nntp.zianet.com> Message-ID: <7xek5onnor.fsf@ruckus.brouhaha.com> "ej" writes: > for key in dir(traceback_): > print "traceback_.%s =" % key, eval("traceback_.%s" % key) Don't use eval for this. Use getattr(traceback_, key). > traceback_.tb_frame = > traceback_.tb_lasti = 18 > traceback_.tb_lineno = 6 > traceback_.tb_next = None Yeah. As /F mentioned, there's also a traceback module that parses this stuff out for you. From pmartin at snakecard.com Mon Nov 21 17:37:16 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Mon, 21 Nov 2005 16:37:16 -0600 Subject: compiling Python under Windows References: <29pgf.12621$ih5.5110@dukeread11> <4382418A.2070902@v.loewis.de> Message-ID: Thanks, Regards, Philippe "Martin v. L?wis" wrote: > Philippe C. Martin wrote: >>>My mistake: The makefile (as written in the readme!) looks for bzip 1.0.2 >>> >> >> PS: since bzip.org does not have 1.0.2 source anymore, can I just rename >> 1.0.3 ? > > That should work; alternatively, you can change the project file. > > Regards, > Martin From mandus at gmail.com Tue Nov 29 06:18:39 2005 From: mandus at gmail.com (Mandus) Date: Tue, 29 Nov 2005 11:18:39 +0000 (UTC) Subject: After migrating from debian to ubuntu, tkinter "hello world" doesn't work References: <1133204577.772209.6300@z14g2000cwz.googlegroups.com> Message-ID: 28 Nov 2005 11:02:57 -0800 skrev mortuno at gmail.com: > Hi > > My tkinter apps worked fine in debian linux (woody and sarge) > I moved to ubuntu 5.10 > > I follow the 'hello world' test as seen in > http://wiki.python.org/moin/TkInter > > > import _tkinter # with underscore, and lowercase 't' > import Tkinter # no underscore, uppercase 'T' > Tkinter._test() # note underscore in _test() works just fine on my ubunty 5.10. Make sure you have the python2.4-tk package installed (sudo apt-get install python2.4-tk). -- Mandus - the only mandus around. From Michael.Coll-Barth at VerizonWireless.com Wed Nov 2 11:34:26 2005 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Wed, 2 Nov 2005 11:34:26 -0500 Subject: Which is worse, Xah's stuff or everyone's effing crap about it? And don't even get me started on that MS bashing or top posting nonsense Message-ID: <20051102163444.3EBBE1E851A@bag.python.org> Actually, the continuous complaining and ranting about Xah's 'postings' are far worse than Xah's actual postings. I can filter his stuff to /dev/null. The drivel that follows is almost as bad as the moronic effluent about how extra-python things should be done or not be done or the legal notices that one's company tacks on at the end of messages. for x in ( 'Grow up', 'Shut up', ' and get a life' ): print 'Life could be good' -----Original Message----- From: every idiot on this list, now including me... > Something I don't quite understand, if people think it is troll, just > ignore it. What I see is that people are feeding it by commenting about > either him or his post. I saw a number of threads ended up that > way(like the rather long one about Microsoft). -------------- next part -------------- ___________________________________________________________________ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to 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 me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From dont at spam.me Mon Nov 28 17:02:24 2005 From: dont at spam.me (Bugs) Date: Mon, 28 Nov 2005 14:02:24 -0800 Subject: Book: Cross-Platform GUI Programming with wxWidgets? In-Reply-To: <1133191147.864680.235820@g47g2000cwa.googlegroups.com> References: <1133191147.864680.235820@g47g2000cwa.googlegroups.com> Message-ID: <0sedndMNedzu4xbenZ2dnUVZ_tudnZ2d@comcast.com> kdahlhaus at yahoo.com wrote: > I was wondering if people using wxPython found this book useful? Is it > worth the money? Thanks > It might be better for Python folks to just wait for this book, due Jan 1, 2006: http://www.manning.com/books/rappin http://www.amazon.com/gp/product/1932394621/002-8046606-2517641?v=glance&n=283155&n=507846&s=books&v=glance From manuel11g at gmail.com Sun Nov 27 15:27:16 2005 From: manuel11g at gmail.com (Manuel11g) Date: 27 Nov 2005 12:27:16 -0800 Subject: Basic about Python class Message-ID: <1133123236.518007.123750@z14g2000cwz.googlegroups.com> Hello, I am a new programmer in Python and a need some help. Where can i get a basic tutorial about Class. I don't know nothing about Object Oriented Programming. Can you help me? From daniel.kabs at gmx.de Wed Nov 9 07:17:03 2005 From: daniel.kabs at gmx.de (Daniel Kabs) Date: Wed, 09 Nov 2005 13:17:03 +0100 Subject: page faults when spawning subprocesses In-Reply-To: <1131526746.894342.182260@z14g2000cwz.googlegroups.com> References: <1131526746.894342.182260@z14g2000cwz.googlegroups.com> Message-ID: <4371f646$0$21943$9b4e6d93@newsread2.arcor-online.net> Dave Kirby wrote: > I am working on a network management program written in python that has > multiple threads (typically 20+) spawning subprocesses which are used > to communicate with other systems on the network. ... Let me check if I got you right: You are using fork() inside a thread in a multi-threaded environment. That sounds complicated. :-) Have a look at http://www.opengroup.org/onlinepubs/009695399/functions/fork.html It mentions your use of fork, i.e. to create a new process running a different program (in this case the call to fork() is soon followed by a call to exec()). If you fork in your multi-threaded environment, what happens with all your threads? The document resorts to "the effects of calling functions that require certain resources between the call to fork() and the call to an exec function are undefined.". Maybe you are just experiencing this :-) The document above recommends: "to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called." Maybe this discussion is also of some help: http://groups.google.com/group/comp.programming.threads/browse_thread/thread/37fe7e050b44c329/217660515af867ea?tvc=2#217660515af867ea Cheers Daniel From andrea_gavana at tin.it Sun Nov 6 09:39:23 2005 From: andrea_gavana at tin.it (Andrea Gavana) Date: Sun, 6 Nov 2005 15:39:23 +0100 Subject: Icon on wx.MDIParentFrame References: <1131286351.026457.36070@g49g2000cwa.googlegroups.com> Message-ID: <436e1658$0$6022$4fafbaef@reader4.news.tin.it> Hello Len > I would like to put an Icon on the frame but cannot figure out how to > do it any help. What about: wx.MDIParentFrame.SetIcon(self, icon) ? I usually take a look also to the wxPython API docs at: http://www.wxpython.org/docs/api/ Or I use some google-fu to find answers, both for Python and wxPython. However, > It appears that wxPython suffers from the same problem as most software > packages. I find that the reference manual is only of any real help > once you have a pretty good understanding of how the software works in > the first place. The "docs subject" appears to be hot this week ;-) . You are perfectly right, in my opinion. However, I am quite sure that the new wxPython book (scheduled for december or something around december) will be a useful and nice reference for newbies and experts. HTH. Andrea. -- "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77 From apardon at forel.vub.ac.be Thu Nov 17 03:51:47 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Nov 2005 08:51:47 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <86r79ji8lt.fsf@bhuda.mired.org> <86k6f9r9sh.fsf@bhuda.mired.org> <863blwpfxd.fsf@bhuda.mired.org> Message-ID: Op 2005-11-16, Mike Meyer schreef : > Antoon Pardon writes: >> Op 2005-11-15, Mike Meyer schreef : >>> Antoon Pardon writes: >>>>>> Like having an assignment operator (let use @= for it) next to a >>>>>> (re)bind operator. >>>>>> We could then have something like the following. >>>>>> a = 5 >>>>>> b = a >>>>>> a @= 7 >>>>>> b ==> would result in 7. >>>>> You've just overwritten the object referred to by the token "5" in the >>>>> source code with the value 7, so you get: >>>>> print 5 >>>>> 7 >>>> You have a valid point, but I think a different approach is possible. >>>> Don't make the distinction between mutable and immutable types but >>>> between mutable and immutable objects. So an int wouldn't be an >>>> immutable type, but 5 would be an immutable object. >>>> So the code above I gave would throw an exception, but the following >>>> might work. >>>> a @= 5 >>>> b = a >>>> b @= 7 >>>> a ==> would result in 7. >>> >>> Which solves that issue but brings up - well, more issues. What >>> happens if the third line is 'b @= "seven"'? Does this require an >>> extra level of indirection in the implementation? Avoiding that kind >>> of thing was the reason for suggesting this: >> >> It depends on how far you want to go. >> >> I think one can argue that in case of an inplace replacement, this >> only makes sense if the two objects belong to the same class. So >> no extra level of indirection is then required. > > Now factor in inheritance. Do users of this facility have to worry > about static OO typing? That is, two objects that are otherwise > completely interchangeable will raise an exception if you try to > assign one to a variable holding the other, because they have the > wrong type. That seems unpythonic. I don't care much about pythonic or not. It seems a very volatile concept, that adapts as the language evolves. I wouldn't be surprised if augmented arithmetic operations would have been considered unpythonic at some point. You could see this limitation as a wart, but IMO the idea would still be usefull with that limitation. The limitation would ensure for example that although the value of an argument could change, it's class couldn't. I think that is worthwhile. >> Otherwise it really depends on how the builtin objects are implemented. >> For user classes, a somewhat simplistic implementation could be >> something like: >> >> def '@=' (one, two): >> one.__dict__.clear() >> one.__dict__.update(two.__dict__) > > Wouldn't one.__dict__ = dict(**two.__dict__) be a bit better? > > Anyway, this won't' work if the class of one of the objects has > slots. So? I wrote it was a simplistic idea. but things like setattr and getattr, still work with objects that have slots. So which attributes are present for a particulare object has to be available in the python interpreter. So my guess is that slots wont be the big stumbling block, should one consider implementing something like this. >>> The critical thing is that this doesn't introduce any new facilities >>> into the language, just some new syntax, so there's no implementation >>> impact. In fact, if you're willing to put up with some notational >>> abuse, we can do this now: >>> >>> class Ref(object): >>> _unbound = object() >>> def __new__(cls, value = _unbound): >>> """We're an object, but need to ignore the optional argument.""" >>> >>> return object.__new__(cls) >>> >>> def __init__(self, value = _unbound): >>> """Bind the optional value, if provided.""" >>> if value is not self._unbound: >>> self._value = value >>> >>> def __pos__(self): >>> """Return value, if bound.""" >>> try: >>> return self._value >>> except AttributeError: >>> raise ValueError, "%s object does not have a value stored." % \ >>> self.__class__.__name__ >>> >>> def __iadd__(self, value): >>> self._value = value >>> return self >>> >>> Usage: >>> >>>>>> x = Ref.Ref() >>>>>> x += 23 >>>>>> +x >>> 23 >>>>>> a = x >>>>>> x += 25 >>>>>> +a >>> 25 >>>>>> a += "this is a test" >>>>>> +x >>> 'this is a test' >>> >>> Since it doesn't have real lannguage support, things like +x += 25 >>> don't work. That's the only obvious gotcha. Maybe ~ would be a better >>> prefix. >> >> I'm a bit puzzled on how you would implement this as real language >> support. As far as I understand this only works with Ref objects. > > Correct. That's the point. > >> You can't do something like the following. >> >> l = [3, 7] >> a = Ref(l[0]) >> >> Instead you would have to do something like >> l = [Ref(3), Ref(7)] >> a = l[0] >> >> So it seems that if you want to use this idea for implementing langauge >> support you will have to wrap all objects in a Ref internally and this >> seems some kind of extra indirection too. > > No, the idea is to expose this class to the user. They would have to > explicitly wrap objects that they want to be able to be get a > reference to. Well that seems less usefull to me. Let me explain, what I would like it for. Sometime I'm programming with tree like structures. Occasionaly such a tree has to be restructured. Now of course I could write it like this: def restruct(tr): if ...: tr.left = restruct(tr.left) tr.right = restruct(tr.right) tmp = tr.left tr.left = tmp.right tmp.right = tr return tmp. ... tree = restruct(tree) But this feels wrong to me. It gives the impression that the following would give you a new restructured tree while the old one is still available, which isn't so: newtree = restruct(tree) IMO being able to write: restruct(tree) With as a result that tree would now be the new root of the restructered tree, would better convey what is going on. Now having to make my tree object into a ref, which would mean all nodes in the tree, seems overkill. Maybe we can consider in-out parameters in python? It is not as powerfull as reference variables or in place replacements but from what I have seen here in the newsgroup would be sufficient for most users that ask for something like this. -- Antoon Pardon From riek at zem.uni-bonn.de Thu Nov 3 11:13:31 2005 From: riek at zem.uni-bonn.de (riek at zem.uni-bonn.de) Date: 3 Nov 2005 08:13:31 -0800 Subject: python, mssql and unicode Message-ID: <1131034411.281189.17770@g43g2000cwa.googlegroups.com> Hello, I am using pymssql (http://pymssql.sourceforge.net/) to insert data from a web-frontend (encoded in utf-8) into fields of type nvarchar of an MS-SQL Server 2000. The problem is, ms-sql server uses ucs-2 and not utf-8. I have looked around a bit but found no suitable solution to this problem so far except converting the utf-8 into latin-1 which will restrict the characters to western europe languages. Does any one have some suggestions? Thank you for your help! Simon From steve at REMOVEMEcyber.com.au Thu Nov 24 03:12:33 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 24 Nov 2005 19:12:33 +1100 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132756197.635519.114180@g47g2000cwa.googlegroups.com> <1132775825.182959.314090@g43g2000cwa.googlegroups.com> Message-ID: <438575F1.908@REMOVEMEcyber.com.au> rurpy at yahoo.com wrote: > Fredrik Lundh wrote: > >>def convert(old): >> >> new = dict( >> CODE=old['CODEDATA'], >> DATE=old['DATE'] >> ) >> >> if old['CONTACTTYPE'] == 2: >> new['CONTACT'] = old['FIRSTCONTACT'] >> else: >> new['CONTACT'] = old['SECONDCONTACT'] >> >> return new > > > I don't find your code any more readable than the OP's > equivalent code: > > def convert(old): > new = { > CODE: old['CODEDATA'], > DATE: old['DATE'], > CONTACT: old['FIRSTCONTACT'] \ > if old['CONTACTTYPE'] == 2 \ > else old['OLDDCONTACT'] > } > return new The problem I have with your code is that it is too similar to: def convert(old): new = { CODE: old['CODEDATA'], DATE: old['DATE'], CONTACT: old['FIRSTCONTACT'] } if old['CONTACTTYPE'] == 2: else: old['OLDDCONTACT'] return new Yes, the above code is broken. But it *looks* right, at first glance, unless you train yourself to never write if cond: TRUE_CLAUSE else: FALSE_CLAUSE as a two-liner. Regardless of whatever benefits the ternary operator is going to have, in my opinion allowing people to write TRUE_CLAUSE if COND else FALSE_CLAUSE will increase the amount of poorly written, hard to read code. > The OPs code make one pass through the dict, your's makes > two. The original code binds a name to an empty dict, then rebinds the name to a populated dict. Your code simply creates the dict in one step. Fredrik's code creates an initial dict, then adds a new key and value to it. That's hardly making two passes through the dict -- what does that even mean? > I do not know what effect (if any) that has in the case of > a very large dict. Quick and dirty speed test: py> from time import time py> def makedict1(): ... return dict.fromkeys(range(1000)) ... py> def makedict2(): ... D = {} ... for i in range(1000): ... D[i]=None ... return D ... py> assert makedict1() == makedict2() py> def test(func, n=100): ... t = time() ... for i in range(n): ... tmp = func() ... return (time() - t)/n ... py> test(makedict1) 0.00020779848098754884 py> test(makedict2) 0.00042409896850585936 That's not timing quite the same thing you refer to, but it is suggestive: if you create an empty dict, and then populate it one item at a time, it will take approximately twice as long as creating the non-empty dict directly. As a very unscientific, system-dependent, statistically shoddy ball-park estimate, it looks like each item assignment to a pre-existing dict takes less than 0.0000002s. So if you had a dict and added another million items to it, one at a time, it might take an extra 0.2s in total more than what it would have taken you if you wrote those one million items in your source code. I can live with that. -- Steven. From DustanGroups at gmail.com Mon Nov 21 08:32:09 2005 From: DustanGroups at gmail.com (Dustan) Date: 21 Nov 2005 05:32:09 -0800 Subject: Cross-Platform ReadKey Message-ID: <1132579929.601664.230200@g47g2000cwa.googlegroups.com> I found this site that has the code for readkey for Windows, Unix, and in an updated version, Mac: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 . The Mac object returns a character whether or not a key was pressed. I modified the Windows object to do the same when I downloaded it, but I have no idea how to make the Unix object instantly return either the character or an empty string. Any help??? From peter at engcorp.com Fri Nov 25 18:45:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Nov 2005 18:45:46 -0500 Subject: Writing pins to the RS232 In-Reply-To: <1132953944.656557.31910@g14g2000cwa.googlegroups.com> References: <1132953944.656557.31910@g14g2000cwa.googlegroups.com> Message-ID: jay.dow at gmail.com wrote: > I want to write to the pins of an RS232 without using the serial > protocol. The use would be every pin could act to complete a circuit > in customized hardware. I could use python to communicate serially to > a BASIC stamp or a Javelin stamp and then use the stamp to set however > many pins as 0's or 1's but should it be that hard to do with python. > I've looked through how python does serial with the "serial" module but > it just uses Java's javax.comm libraries. Is there anyway to do very > low level device writing to COM ports? As Roy indicates, you can't practically make a serial port on a PC do this. I just wanted to note that you've misunderstood the presence of the Java stuff in pyserial. If you're running under Jython then that stuff is used, but if you're on Windows the file win32serial.py (or something like that... going by memory) is what will be used, not the java one. Also, pyparallel should let you get closer to what you want, and in fact questions about using it are certainly on-topic here, though troubleshooting hardware issues are probably not. -Peter From kevins at ctechservices.com Mon Nov 14 20:54:30 2005 From: kevins at ctechservices.com (QuadriKev) Date: 14 Nov 2005 17:54:30 -0800 Subject: Where can I find an example that uses FTP standard library? Message-ID: <1132019670.324893.227060@g43g2000cwa.googlegroups.com> I am fairly new to programming in Python. There are a number of cases where I would like to see examples of programs written. I like to write them on Windows and in some cases put them on my Linux server to do something useful. I am also interested in using Telnet to check services and things on the Linux server. Can someone give me direction on the best place for examples? Full example of something written with GTK or wxPython would be very interesting also. TIA From grante at visi.com Wed Nov 2 22:46:56 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 03 Nov 2005 03:46:56 -0000 Subject: reading internet data to generate random numbers. References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> Message-ID: <11mj21gr6rjgc65@corp.supernews.com> On 2005-11-02, Neil Schemenauer wrote: > Grant Edwards wrote: >> Doesn't your OS have an entropy-gathering RN generator built-in? > > Alternatively, if you want lots of high-quality random numbers, buy > a cheap web camera: http://www.lavarnd.org/. The thermal noise present in a CCD sensor is a good source of random bits, but I don't get what all the stuff about taking "snapshots of a physical chaotic process" has to do it. > Using data from the Internet is just a bad idea. I think that the timing of certain network events is one of the Linux kernel's entropy sources. -- Grant Edwards grante Yow! I'm shaving!! I'M at SHAVING!! visi.com From peter at engcorp.com Sun Nov 6 15:16:42 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 06 Nov 2005 15:16:42 -0500 Subject: Modify HTML data In-Reply-To: <1131298307.445951.63000@g49g2000cwa.googlegroups.com> References: <1131235132.163505.280600@g43g2000cwa.googlegroups.com> <1131298307.445951.63000@g49g2000cwa.googlegroups.com> Message-ID: Swarna wrote: > Peter Hansen wrote: >>Swarna wrote: >>>I am using scp in python to copy a html file on remote server, to my >>>local machine. Now, i need to update this html file in my local machine >>>( by adding a new Hyperlink to the existing table od hyperlinks ) and >>>copy it back (overwriting the old copy ) to the remote server. >> >>If you are using scp to copy the file from the remote server in the >>first place, what's stopping you from using scp to copy it back? > > I might be vague in expressing my problem.....the problem is not with > scp. What i need is how to modify the html file in my local machine > that i got from remote server. Ah, so all that stuff about scp was just to distract us from the real problem? Okay, so Lorenzo's advice is fine: grab an HTML parser and use that to figure out where things are. Or if the problem is defined simply enough, you could use a regular expression (re module). BeautifulSoup is often recommended when the HTML is not necessarily very clean... Personally, I'd start with an re and move on from there only if that was for some reason not sufficient. -Peter From dan.j.weber at gmail.com Thu Nov 17 20:29:55 2005 From: dan.j.weber at gmail.com (dan.j.weber at gmail.com) Date: 17 Nov 2005 17:29:55 -0800 Subject: Reading a file in same directory as code with relative path Message-ID: <1132277395.552201.81830@g14g2000cwa.googlegroups.com> I'm trying to read an XML file in the same directory as my python code, using minidom: document = xml.dom.minidom.parse("data.xml") How can I read in the file "data.xml" without knowing it's full path--just that it's in the same directory as my code file? Thanks for any help with this. I'm new to python and really liking it so far. From cito at online.de Sat Nov 26 16:39:00 2005 From: cito at online.de (Christoph Zwerschke) Date: Sat, 26 Nov 2005 22:39:00 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <43885b80$0$18644$9b622d9e@news.freenet.de> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> Message-ID: >>> class mylist1(list): >>> def __hash__(self): return 0815 >>> >>> class mylist2(list): >>> def __hash__(self): return id(self) >>> >>> Which of these user-defined types would you call "hashable"? > Mike Meyer wrote: >> The latter two, as the given __hash__ meets the specifications for >> __hash__. Martin v. L?wis wrote: > This is not true. The second definition of __hash__ does not meet > the specifications: > "The only required property is that objects which compare equal have the > same hash value" As Mike has written in his last posting, you could easily "fix" that by tweaking the equality relation as well. So technically speaking, Mike is probably right. It would completely break common-sense semantics, because for mylist2, if I have a=[1] and b=[1] then I will have a!=b. This would not be very reasonable, but probably allowed by Python. -- Christoph From steve at REMOVETHIScyber.com.au Sat Nov 26 23:34:39 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 27 Nov 2005 15:34:39 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> <86oe49wyky.fsf@bhuda.mired.org> <86acfsgols.fsf@bhuda.mired.org> <86sltjg2s8.fsf@bhuda.mired.org> <86y83bdmln.fsf@bhuda.mired.org> Message-ID: On Sat, 26 Nov 2005 18:18:44 -0500, Mike Meyer wrote: > The GPL is *not* such a license - it places > restrictions on the redistribution. Which is what I said in the first > place. If you want me to agree that the GPL puts more conditions on distribution than the MIT/BSD licence, then I'll happily agree. If you want me to describe that as a "restrictive licence", then I refuse. Look: would you agree that the BSD licence is a restrictive licence? You can't get much more liberal than the BSD licence -- in fact some people argue that if you are going to use a BSD licence, you might as well just put the work in the public domain. I can respect the argument for putting works in the public domain. But *technically* the BSD licence does restrict the distributor, because they must give attribution. But there is a difference between the existence of a "restriction" and the licence being "restrictive". If you can see that difference, you will understand why I do not agree to describe the GPL as "restrictive" -- and if you can't see that difference, then you must also describe the BSD licence as restrictive. [snip] > So that's the basis of the disagreement. I'm using "restriction" with > the intent of communicating it's normal english meaning, Your meaning is about as far from the plain English sense of "restrictive" as it is possible to get without actually contradicting the dictionary meaning. And that's the reason for my vehement disagreement with the suggestion that the GPL is "restrictive". We've already had one suggestion that if you ask 100 ordinary people what free software means, 99 will say "free of cost" rather than free like speech. (Thanks to Ed for that thought-experiment.) I suggest that you if told 100 ordinary people that there is software that allowed you to make as many copies as you liked, to give them away for free or sell them for as much money as you wanted, to install it on as many computers you liked, and that they didn't have to pay a single cent for that software if they didn't want to, and that to be allowed to do that all you had to do was to pass those rights on to those you give the software to, then asked them if those conditions were "restrictive", I think all 100 of them would look at you like you came from another planet. If you want to use "restrictive" in the hair-splitting, pedantic, non-plain English sense of "containing any restriction no matter how infinitesimal", then please have the honesty to describe the BSD licence as restrictive too. Then we can all agree that all software licences are restrictive and that moral rights are restrictive ("but what if I *want* to plagiarise the author of this public domain work?"). I think that your usage of the word is about as useful as plutonium underwear, but if you are going to use it in that way, at least be consistent. -- Steven. From simon.brunning at gmail.com Tue Nov 15 06:28:30 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 15 Nov 2005 11:28:30 +0000 Subject: compare list In-Reply-To: <8c11e4350511150316l3f35253dkd42f98842e55119a@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <1d987df30511142330t39b137fdpdc9eee56e73d6e1f@mail.gmail.com> <4379AA95.80806@cc.umanitoba.ca> <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> <8c7f10c60511150227v297140e1n@mail.gmail.com> <1d987df30511150258j7848d3d5o61905f5ac935a6b0@mail.gmail.com> <8c7f10c60511150305p29c7ab48u@mail.gmail.com> <8c11e4350511150316l3f35253dkd42f98842e55119a@mail.gmail.com> Message-ID: <8c7f10c60511150328sfe52e8q@mail.gmail.com> On 15/11/05, Ben Bush wrote: > an error reported: > Traceback (most recent call last): > File > "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\temp\try.py", line 8, in ? > from sets import Set as set > ImportError: cannot import name Set > >>> Works for me. You don't have a sets module of your own, do you? Try this, and report back what you see: import sets print sets.__file__ print dir(sets) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at REMOVETHIScyber.com.au Fri Nov 11 23:47:18 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 12 Nov 2005 15:47:18 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <1131725491.983050.90210@g47g2000cwa.googlegroups.com> Message-ID: On Fri, 11 Nov 2005 08:11:32 -0800, petantik wrote: > the argument that most people buy software rather than get a pirated > version depends on the country that they are in e.g. china's piracy > problem where shops sell pirated software with no retribution by the > state - remember china is about to be the worlds largest economic > superpower > > The above problem illustrate why code needs to be protected in an > effective way, by law and code protection schemes I'm sorry, what problem? You haven't actually stated a problem -- in fact, you have just given a perfect example of why the so-called "problem" is not a problem at all. Let us see: Historically, the UK had no concept of intellectual property rights until very recently, and even when it was introduced, it was very limited until the late 20th century. Likewise for continental Europe. Nevertheless, the UK and Europe became economic superpowers. The USA, like China and Russia today, was a pirate nation for the first century or two of its existence. American publishers simply reprinted English books without paying royalties until well into the 20th century. Hollywood got its start by fleeing the east coast to California, where enforcement of Thomas Edison's patents on motion picture technology was not enforced. The USA has become an economic superpower. China has little effective protection for artificial monopoly rights over ideas. China is becoming an economic superpower. So where is the problem? Ah, now I understand it. Having become rich and powerful by ignoring so-called intellectual property, the UK, Europe and especially the USA is desperate to ensure that the developing world does not also become rich and powerful. One way of doing so is to force a system of artificial government-granted monopolies, together with all the proven economic inefficiencies of such monopolies, on the developing world. -- Steven. From aum at spam.me.please Sun Nov 6 19:23:40 2005 From: aum at spam.me.please (aum) Date: Mon, 07 Nov 2005 13:23:40 +1300 Subject: PyFLTK - an underrated gem for GUI projects Message-ID: Hi all, I've been doing a fair bit of python gui programming on and off, jumping between different widget sets along the way, from anygui, to pythoncard, to tkinter/PMW, then to wxPython/wxGlade, and have now settled on a python gui API that seems to get barely a mention - PyFLTK. PyFLTK (http://pyfltk.sourceforge.net) is a SWIG-generated Python wrapper around the multiplatform FLTK widget set ('Fast Light Tool Kit' - http://fltk.sourceforge.net). In recent months, this wrapper has stabilised to the point where it's fit for production projects. A recent development that's given PyFLTK even more power is the companion utility program, 'flconvert', which takes gui layout files (created with the FLTK 'fluid' gui designer program) and turns them into importable Python modules that Simply Just Work. Every widget set has its place, and I feel this applies in no small part to PyFLTK. To me, wxPython is like a 12-cylinder Hummer, with fuzzy dice hanging from the mirror, fridge and microwave in the back, and DVD consoles on every seat, towing a campervan - absolute power and luxury, giving 8mpg if you're lucky. wxPython has the cost of a massive disk and memory footprint. A 'hello, world' turned into a windoze exe with py2exe weighs in at around 15MB, and takes 6-10 seconds to load up on a 2GHz Athlon box, about as long as Photoshop! For large and intricate apps, wxPython is a logical choice, but for smaller progs it's serious overkill IMHO. Whereas PyFLTK feels more like an average suburban 4-door sedan giving 70mpg, nothing too flash, but easy to drive, easy to park and generally comfortable, and easy to look after. The widget set is pretty simple, but covers all the basics and includes good rich-text features in listboxes, as well as an html viewer that supports html2.0 and parts of html3.0. Some of the things I'm liking about PyFLTK include: - way less code to get things done - some nice automagic, for instance in setting up tiling (similar to wx's splitter windows) - an absolute minimum of 'voodoo programming' (which was a constant bugbear for me with tkinter) - apps compile small, and start up fast - a really good designer program - fltk's 'fluid' program is light years ahead of wxglade imho Also, FLTK's intuitive, semantically clear API makes it really approachable for newcomers. One can write a 'hello, world' in 5 lines: import fltk label = "something here" # to stop string being gc'ed w = fltk.Fl_Window(100, 100, 300, 200, label) w.show() fltk.Fl.run() So I hope this humble message might inspire some folks to have a serious look at pyfltk. For many situations, PyFLTK can take you to break-even point quickly, and deliver net savings in time and effort after that. -- Cheers David -- Cheers David From twic at urchin.earth.li Sun Nov 13 12:57:48 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 13 Nov 2005 17:57:48 +0000 Subject: Iterator addition In-Reply-To: <3tp834FtpasuU1@individual.net> References: <7x4q6lm87q.fsf_-_@ruckus.brouhaha.com> <1h5s1dp.i6hnk31bmv4xN%aleax@mail.comcast.net> <7xslu5cdhz.fsf@ruckus.brouhaha.com> <1131847923.361393.233530@g47g2000cwa.googlegroups.com> <3tp834FtpasuU1@individual.net> Message-ID: On Sun, 13 Nov 2005, Reinhold Birkenfeld wrote: > bearophileHUGS at lycos.com wrote: > >> Tom Anderson: > >>> And we're halfway to looking like perl already! Perhaps a more >>> pythonic thing would be to define a "then" operator: >>> >>> all_lines = file1 then file2 then file3 >> >> Or a "chain" one: >> >> all_lines = file1 chain file2 chain file3 This may just be NIH syndrome, but i like that much less - 'then' makes for something that reads much more naturally to me. 'and' would be even better, but it's taken; 'andthen' is a bit unwieldy. Besides, "chain file2" is going to confuse people coming from a BASIC background :). > That's certainly not better than the chain() function. Introducing new > operators for just one application is not pythonic. True, but would this be for just one application With python moving towards embracing a lazy functional style, with generators and genexps, maybe chaining iterators is a generally useful operation that should be supported at the language level. I'm not seriously suggesting doing this, but i don't think it's completely out of the question. tom -- limited to concepts that are meta, generic, abstract and philosophical -- IEEE SUO WG From robert.kern at gmail.com Tue Nov 22 23:16:31 2005 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 22 Nov 2005 20:16:31 -0800 Subject: email module documentation In-Reply-To: <1391261.ocLkZXfqrF@teancum> References: <1391261.ocLkZXfqrF@teancum> Message-ID: David Bear wrote: > I'm confused about how to use the email module in python 2.4.x > > I'm using python packaged with suse 9.3. > >>From the module documetation at http://docs.python.org/lib/node597.html I > found the following example (items cut): > > import email > > ... > msg = email.message_from_file(fp) > .. > > Yet, when I try this I get the message > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'message_from_file' > > so I dir(email) reveals: > > ['__builtins__', '__doc__', '__file__', '__name__', 'cStringIO', 'email', > 'getMessage', 'sys'] > > This is nothing like the documentation on python.org. > > Any idea what I am missing? That's not what I have on OS X with Python 2.4.1. In [1]: import email In [2]: dir(email) Out[2]: ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', 'message_from_file', 'message_from_string'] Are you sure that you're getting the right file? Check email.__file__ . -- 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 metiu.uitem at gmail.com Fri Nov 25 06:51:42 2005 From: metiu.uitem at gmail.com (metiu) Date: 25 Nov 2005 03:51:42 -0800 Subject: Guification of console app In-Reply-To: References: <1132871970.821787.204830@g14g2000cwa.googlegroups.com> <1132909528.263090.326890@g47g2000cwa.googlegroups.com> Message-ID: <1132919502.165111.178790@o13g2000cwo.googlegroups.com> I like it! Thanks! From bokr at oz.net Thu Nov 24 06:23:33 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 24 Nov 2005 11:23:33 GMT Subject: defining the behavior of zip(it, it) (WAS: Converting a flatlist...) References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: <4385a284.626776126@news.oz.net> On Wed, 23 Nov 2005 17:55:35 +0100, "Fredrik Lundh" wrote: > >so how equivalent must something be to be equivalent? > quack, quack? ;-) Regards, Bengt Richter From fuzzyman at gmail.com Wed Nov 23 03:40:54 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Nov 2005 00:40:54 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: <1132735254.039468.106660@g44g2000cwa.googlegroups.com> Christoph Zwerschke wrote: > One implementation detail that I think needs further consideration is in > which way to expose the keys and to mix in list methods for ordered > dictionaries. > > In http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 > the keys are exposed via the keys() method which is bad. It should be a > copy only, like for ordinary dicts (one comment also mentions that). > > In Foord/Larosa's odict, the keys are exposed as a public member which > also seems to be a bad idea ("If you alter the sequence list so that it > no longer reflects the contents of the dictionary, you have broken your > OrderedDict"). > So don't do it. ;-) > I think it would be probably the best to hide the keys list from the > public, but to provide list methods for reordering them (sorting, > slicing etc.). > > For instance: > > d1 = OrderedDict( (1, 11), (2, 12), 3, 13) ) > > d1[1:] ==> OrderedDict( (2, 12), 3, 13) ) > So what do you want returned when you ask for d1[1] ? The member keyed by 1, or the item in position 1 ? You can access the members using list operations on the sequence attribute. E.g. d1[d1.sequence[index]] This could probably be made more convenient. > d1[0] + d1[2] ==> OrderedDict( (1, 11), (3, 13) ) > > d1.reverse() ==> OrderedDict( (3, 13), (2, 12), 1, 11) ) > Interesting idea. > d1.insert(1, (4, 14)) > ==> OrderedDict( (1, 11), (4, 14), (2, 12), 3, 13) ) > Also an interesting idea. > etc. > > But no other way to directly manipulate the keys should be provided. > Why - don't trust yourself with it ? All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -- Christoph From bonono at gmail.com Wed Nov 9 09:02:41 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 06:02:41 -0800 Subject: append to non-existing list In-Reply-To: References: Message-ID: <1131544961.869354.70080@g49g2000cwa.googlegroups.com> Thomas Bellman wrote: > The next time you go shopping at your local super-market, do > *not* get a shopping-cart (or shopping-basket, or any similar > container). As you pick up the things you want to buy, try > to put them into the non-existing cart. Perhaps you will then > become enlightened. But in PHP(and I believe Perl), it is more like : "oops, I need a cart. Hello, I need a cart here, please" and magically, someone wheel you a cart which you can put your stuff in. The "@" is the magic calls for service. So as a customer, this sounds like better service but that will create problems to the super market as it need extra staff for this service and the environment is noiser, that is another story. From inyeol.lee at siliconimage.com Mon Nov 28 13:52:36 2005 From: inyeol.lee at siliconimage.com (Inyeol Lee) Date: Mon, 28 Nov 2005 10:52:36 -0800 Subject: [pyparsing] How to get arbitrary text surrounded by keywords? Message-ID: <20051128185236.GA23313@siliconimage.com> I'm trying to extract module contents from Verilog, which has the form of; module foo (port1, port2, ... ); // module contents to extract here. ... endmodule To extract the module contents, I'm planning to do something like; from pyparsing import * ident = Word(alphas+"_", alphanums+"_") module_begin = Group("module" + ident + "(" + OneOrMore(ident) + ")" + ";") module_contents = ??? module_end = Keyword("endmodule") module = Group(module_begin + module_contents + module_end) (abobe code not tested.) How should I write the part of 'module_contents'? It's an arbitrary text which doesn't contain 'endmodule' keyword. I don't want to use full scale Verilog parser for this task. -Inyeol From fredrik at pythonware.com Tue Nov 22 11:26:30 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 17:26:30 +0100 Subject: Dictionary string parser References: Message-ID: Sebastjan Trepca wrote: > is there any library or some way to parse dictionary string with list, > string and int objects into a real Python dictionary? > > For example: > > >>> my_dict = dict_parser("{'test':'123','hehe':['hooray',1]}") > > I could use eval() but it's not very fast nor secure. it's definitely slower than eval (which is written in C, after all), but it's definitely more limited, and hopefully also more secure: import cStringIO import tokenize def _parse(token, src): if token[1] == "{": out = {} token = src.next() while token[1] != "}": key = _parse(token, src) token = src.next() if token[1] != ":": raise SyntaxError("malformed dictionary") value = _parse(src.next(), src) out[key] = value token = src.next() if token[1] == ",": token = src.next() return out elif token[1] == "[": out = [] token = src.next() while token[1] != "]": out.append(_parse(token, src)) token = src.next() if token[1] == ",": token = src.next() return out elif token[0] == tokenize.STRING: return token[1][1:-1].decode("string-escape") elif token[0] == tokenize.NUMBER: try: return int(token[1], 0) except ValueError: return float(token[1]) else: raise SyntaxError("malformed expression") def myeval(source): src = cStringIO.StringIO(source).readline src = tokenize.generate_tokens(src) return _parse(src.next(), src) print myeval("{'test':'123','hehe':['hooray',0x10]}") {'test': '123', 'hehe': ['hooray', 16]} hope this helps! From fredrik at pythonware.com Sun Nov 20 03:43:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 09:43:10 +0100 Subject: PATH environment variable References: <1132451443.807757.251540@g43g2000cwa.googlegroups.com> Message-ID: mirandacascade at yahoo.com wrote: > Based on a search of other posts in this group, it appears as though > os.environ['PATH'] is one way to obtain the PATH environment variable. > > My questions: > 1) is it correct that os.environ['PATH'] contains the PATH environment > variable? yes. > 2) are there other ways to obtain the PATH environment variable? if so, > is one way of obtaining the PATH environment variable preferable to > another way? no. using the environ variable is the preferred way to read environment variables. From steve at holdenweb.com Fri Nov 25 03:36:48 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Nov 2005 08:36:48 +0000 Subject: return in loop for ? In-Reply-To: References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: <4386CD20.2010000@holdenweb.com> Steven D'Aprano wrote: > On Thu, 24 Nov 2005 12:51:34 +0000, Duncan Booth wrote: > > >>Steven D'Aprano wrote: >> >> >>>>While outwardly they apear to offer a technique for making software >>>>more reliable there are two shortcomings I'm leery of. First, no >>>>verification program can verify itself; >>> >>>That's not a problem if there exists a verification program A which >>>can't verify itself but can verify program B, which in turn also can't >>>verify itself but will verify program A. >>> >> >>That is logically equivalent to the first case, so it doesn't get you >>anywhere. (Just combine A and B into a single program which invokes A >>unless the input is A when it invokes B instead.) > > > Then there you go, there is a single program which can verify itself. > > I think you are confabulating the impossibility of any program which can > verify ALL programs (including itself) with the impossibility of a program > verifying itself. Programs which operate on their own source code do not > violate the Halting Problem. Neither do programs which verify some > subset of the set of all possibly programs. > > There seems to have been some misattribution in recent messages, since I believe it was *me* who raised doubts about a program verifying itself. This has nothing to do with the Halting Problem at all. A very simple possible verification program is one that outputs True for any input. This will also verify itself. Unfortunately its output will be invalid in that and many other cases. I maintain that we cannot rely on any program's assertions about its own formal correctness. 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 steve at REMOVETHIScyber.com.au Thu Nov 10 17:24:15 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 11 Nov 2005 09:24:15 +1100 Subject: different binding behavior References: Message-ID: On Thu, 10 Nov 2005 22:43:53 +0100, Gabriel Zachmann wrote: > It seems to me that the following behavior of python (2.4.1) is inconsistent: We've just had a HUGE thread arguing about this behaviour, just three or five days ago. Let's not start it again. In a nutshell, the behaviour is because ints are immutable and can't be changed in place, and lists are mutable and can be changed in place. Imagine that ints could be changed in place. Then you could do this: x = 0 x += 1 Now the int 0 has the value of 1. So: print 2 + 0 => prints 3 Confusion and horror. So of course x += 1 can't change the int in place, it has to rebind x to a new int. -- Steven. From mandus at gmail.com Wed Nov 30 16:19:34 2005 From: mandus at gmail.com (Mandus) Date: Wed, 30 Nov 2005 21:19:34 +0000 (UTC) Subject: After migrating from debian to ubuntu, tkinter "hello world" doesn't work References: <1133204577.772209.6300@z14g2000cwz.googlegroups.com> <1133353417.658614.224330@f14g2000cwb.googlegroups.com> Message-ID: 30 Nov 2005 04:23:37 -0800 skrev mortuno at gmail.com: > > Mandus ha escrito: > >> works just fine on my ubunty 5.10. Make sure you have the python2.4-tk >> package installed (sudo apt-get install python2.4-tk). >> > > yes, i got it. > It's a fresh instalation from a cd in a brand new laptop. I tried to > reinstall python2.4-tk and many other packeges :-( > If you think it may help, I can drop you my complete 'dpkg --get-selections'. Just tell me where you want it. mvh, -- Mandus - the only mandus around. From aleax at mail.comcast.net Thu Nov 24 03:53:34 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 24 Nov 2005 00:53:34 -0800 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <1132809362.857730.185130@g14g2000cwa.googlegroups.com> Message-ID: <1h6ia9x.hvthhf1vrmpy9N%aleax@mail.comcast.net> bonono at gmail.com wrote: ... > > qualification, you're quite likely to get such disclaimers. If you > > don't want them, learn to ask about stopping your users from > > ACCIDENTALLY doing X, and no reasonable respondant will fail to notice > > the qualification. > Interestingly, that is what I read from the OP, even without the > "ACCIDENTALLY". While I followed the maxim "in the face of ambiguity, refuse the temptation to guess" and didn't put words in his mouth that he had in fact not said: I explained what he could do, and how that wouldn't work IF he did NOT mean ``accidentally''. Not sure if this refusal to assume that the requests are _necessarily_ sensible comes from my several years of experience fielding question in this and other newsgroups, or my even more years of experience as a consultant, both freelance and "in-house" within large organizations... Alex From steve at holdenweb.com Tue Nov 29 03:33:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Nov 2005 08:33:00 +0000 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > Fredrik Lundh schrieb: [...] >>I suggest you look up the phrase "bike shed effect". next, go read some >>recent PEP:s to see what's really going on in the Python design universe. > > > The bike shed effect is a good explanation and so true. About 8 years > ago when I started to work at my current working place at the university > I suggested that a bike shed should be provided for people like me. > Since then, a lot of million euro projects have been carried out, like > introducing SAP software and new projects are in progress. But my bike > still is getting wet and anyway, it's still bothering me. > Yes, but that's the academic world, and bike sheds are a real-world requirement so they will tend to be ignored indefinitely. 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 jeff at schwabcenter.com Wed Nov 9 09:00:28 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Wed, 09 Nov 2005 14:00:28 GMT Subject: Python doc problem example: gzip module (reprise) In-Reply-To: <86u0em7oxo.fsf@bhuda.mired.org> References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131455018.179436.230410@g44g2000cwa.googlegroups.com> <86u0em7oxo.fsf@bhuda.mired.org> Message-ID: <0incf.3656$Ea3.897611@twister.southeast.rr.com> Mike Meyer wrote: > "Xah Lee" writes: > > >>Newsgroups: comp.lang.perl.misc >>PS: I won't cross-post as I'm not subscribed to the Python group. > > > Very wisely done. Then from Xah Lee, we get; > > >>I have cross posted it for you. > > > Proving once again that he's stupider than spam. Please help google > find him that way by adding this link to your pages: > > stupider than spam > > thank you, > References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> <1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: Norman Silverstone wrote: > On Fri, 11 Nov 2005 01:39:40 +1100, Steven D'Aprano wrote: > > >>On Thu, 10 Nov 2005 13:30:05 +0000, Norman Silverstone wrote: >> >> >>>>In that case, think of "bisection". Originally, all the computer knows >>>>is that the number is in some range, say 0 to 100. It can then guess >>>>the midpoint, 50. If it's right, yay! Otherwise: if it's told to go >>>>lower, then the range is now 0 to 49 -- if higher, it's 51 to 100; in >>>>each case the range was just halved (actually, a bit more than halved). >>> >>>Thank you, I thought that might be the case. So, I will have to settle >>>down and try to write some pseudo-code first. I hope to be back. >> >>Heh, you will find that Python is practically executable pseudo-code! >> >>Untested: >> >> >>def guess_number(): >> # please don't cheat the poor computer... >> print "Guess a number." >> lo = 0 >> hi = 100 >> while True: >> guess = (lo+hi)//2 >> ans = raw_input("Is it %d? y/n " % guess) >> if ans in ('y', 'yes'): >> break >> ans = raw_input("Too high? y/n ") >> if ans in ("y", "yes"): >> hi = guess-1 >> else: >> lo = guess+1 >> >>This should run, and it will *almost* do what you want. > > > Thanks for that but I think it is too simplistic. It appears OK for the > first guess, which is 50 but, what about the next guess. If the guess is > too high then the next guess has to be 50/2. However, if it is too low > then the next guess must be first guess + (100-second guess)/2. In general > terms, if guess is too high then next guess must (guess - lowest > possible)/2 and if too low then it is guess + (highest possible - > guess)/2. > > Comments please. > > Norman > Effectively you want to start with a minposs and maxposs, which are set to 0 and 100 respectively. Your guess should bisect the range (as nearly as it can given that you are dealing with integers, and you have to be careful to get the awkward boundary conditions right). So your first guess will be 50. If your guess is too low then replace minposs with your guess (in this case 50); if too high, replace maxposs with your guess; loop to generate the next guess, and so on. In practice since log2(100) > 5 your five guesses won't always be enough (though seven should be). Hope this helps. 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 aleax at mail.comcast.net Tue Nov 8 00:48:05 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 7 Nov 2005 21:48:05 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> Message-ID: <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> wrote: > Everything works fine with v1.16. I'm sure I was doing something wrong. > I shouldn't be testing that late at night. ;-) > > It looks like the warning about "tp_compare" has been fixed. I didn't touch tp_compare specifically, so the fix must have been a side effect (?). > > I will try to build a version for Windows, but that may take me a day > or two. Great, pls let me know when you do (particularly if you're willing to make your build available to others -- if you send it to me I can make it downloadable from sourceforge). > Thanks for the updates to gmpy! You're welcome, and thank YOU for the feedback &c. Alex From bignose+hates-spam at benfinney.id.au Fri Nov 11 18:51:34 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Nov 2005 10:51:34 +1100 (EST) Subject: Needed class whose instances are many test cases References: <1131706265.113961.63370@f14g2000cwb.googlegroups.com> Message-ID: Roy Smith wrote: > Ben Finney wrote: > > Test cases should each run individually, from a known state, and > > not depend on any other tests. You can define a fixture for > > several tests in the unittest.TestCase methods setUp() and > > tearDown(), to establish and clear up respectively for each test. > > In general, I certainly agree with the above. The problem is that > sometimes setup is so expensive, it becomes impractical to do a full > setup/teardown cycle for each test. That's what mock objects are for. The test fixture should be minimal, having only the interface needed to test that the production code does what it should, with almost no functionality behind that interface. -- \ "I always had a repulsive need to be something more than | `\ human." -- David Bowie | _o__) | Ben Finney From bonono at gmail.com Sat Nov 19 09:47:39 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 19 Nov 2005 06:47:39 -0800 Subject: Underscores in Python numbers In-Reply-To: References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> Message-ID: <1132411659.430829.226270@g49g2000cwa.googlegroups.com> Sybren Stuvel wrote: > bonono at gmail.com enlightened us with: > > Of course, also support the locale variant where the meaning of "," > > and "." is swapped in most European countries. > > This is exactly why I wouldn't use that notation. What happens if it > is hardcoded into the source? I mean, that's what we're talking about. > Then the program would have to have an indication of which locale is > used for which source file. Without that, a program would be > interpreted in a different way on different computers. I think that > would be rather messy. > As mentioned in another post, we have that situation in all other places. Such as mm/dd/yyyy vs dd/mm/yyyy decimal("10.23") - would european people expect decimal("10,23") to work ? 0xffff - a notation for base 16 why can't I have "E100.000,23" to mean "100,000.23" ? Nothing but notation. From cjw at sympatico.ca Tue Nov 29 14:31:20 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 29 Nov 2005 14:31:20 -0500 Subject: wxPython : getting started In-Reply-To: <438c8dc4$1@epflnews.epfl.ch> References: <438c8dc4$1@epflnews.epfl.ch> Message-ID: <702jf.2187$Et5.154918@news20.bellglobal.com> David Sulc wrote: > Hi ! > > I've looked all over (internet, books, etc.) and I haven't found a very > good ressource to get started with wxPython (yes, I've been through > their tutorial). > > What I would basically like to do for starters is to be able to define > the main panel being displayed. For example : > 1. wxFrame contains a wxPanel (call it mainPanel). > 2. mainPanel contains another panel (childPanelA) > 3. another panel has been defined (childPanelB) but is not displayed > (the user can only see childPanelA inside mainPanel) > 4. by clicking on a menu entry (for example), the displayed panel is now > childPanelA (which is inside mainPanel) > > So how do I do this ? I realize it's a very basic question, but it's > been driving me mad... > > Also, is there any good open source wxPython program that I could study ? > > Thanks for any help... David, I'm dodging your question but you might find this soon to be released book helpful: http://www.manning.com/books/rappin Also Boa Constructor is a helpful tool. Colin W. From steve at holdenweb.com Tue Nov 8 22:54:09 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 09 Nov 2005 03:54:09 +0000 Subject: Newb ?? In-Reply-To: References: Message-ID: Chad Everett wrote: > Hi all, I am new to the group. Trying to learn Python programming on my > own. I am working through Michael Dawson's Book Python Programming for the > absolute beginner. > > I am tring to write a program that is a number guessing game. I want to be > able to give the user 5 tries to guess the number before the program ends. > > I get the result that I want when the user misses after the 5th try. But it > does not go down to my closing statement to end. Rather is askes for > another guess. > > I appreciate any help you can give. If this is not the correct group for > these types of questions, I apologize and hope that you can direct me to > another NG. > > Thanks, > Chad > > import random > > print "\tWelcome to 'Guess my Number'!" > print "\nI'm Thinking of a Number between 1 and 100." > print "\nTry to Guess it in as few attempts as possible.\n" > > #Set the initial values > the_number = random.randrange(100) + 1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #Guessing Loop > > while (guess != the_number): > if (guess >the_number): > print "Lower..." > else: > print "Higher..." > guess = int(raw_input("Take another Guess:")) > tries +=1 > if tries == 5: > print "Sorry you lose." > print "The Correct Number was ", the_number > > > print "You guess correctly!!" > print "The number was:", the_number > print "You got it correct in", tries, "tries" > > raw_input("Press Enter to exit the program") > > I don't personally think the two possible solutions you've been given are very pythonic. All you really need to do to get the loop termination conditions right (he says confidently, and with absolutely no testing at all) is change the while line to while guess != the_number and tries <=5: but there are other things wrong with the program. In "pseudo-code" (stuff that helps you think about the problem without being able to feed it into an interpreter) your solution should be while not guessed and guesses < 5 guess number if guessed congratulate user else crow and rub user's face in it At present your code will always tell the user she guessed correctly, even after it's told her she lost. See if this (tested) rewrite makes sense to you: import random print "\tWelcome to 'Guess my Number'!" print "\nI'm Thinking of a Number between 1 and 100." print "\nTry to Guess it in as few attempts as possible.\n" #Set the initial values the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess:")) tries = 1 #Guessing Loop while guess != the_number and tries < 5: if (guess >the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take another Guess:")) tries +=1 if guess == the_number: print "You guess correctly!!" print "The number was:", the_number print "You got it correct in", tries, "tries" else: print "Sorry you lose." print "The Correct Number was ", the_number 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 alanmk at hotmail.com Wed Nov 2 11:39:10 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 02 Nov 2005 16:39:10 +0000 Subject: Python and MySQL In-Reply-To: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: [Aquarius] > I appologize in advance for this strange (and possibly stupid) > question. > > I want to know if there is a way to interface a MySQL database without > Python-MySQL or without installing anything that has C files that need > to be compiled. The reason for this, is that I want to develop a > certain web application, but my hosting provider (!#@$!@#%) isn't very > eager to supply Python-MySQL (or any modules to python). Is there an > alternative approach I could use to pass around this ridiculos lack of > functionality? Possibly not want you want to hear, but I'd strongly recommend to stop wasting your time with a hosting company that doesn't support the technologies you need. Instead, try a hosting company that supports python: there are lots and lots http://wiki.python.org/moin/PythonHosting Life's too short to spend your time hacking around artificial barriers to progress. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From larry.bates at websafe.com Thu Nov 17 15:17:49 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 17 Nov 2005 14:17:49 -0600 Subject: how to organize a module that requires a data file In-Reply-To: References: Message-ID: <437CE56D.8010606@websafe.com> Personally I would do this as a class and pass a path to where the file is stored as an argument to instantiate it (maybe try to help user if they don't pass it). Something like: class morph: def __init__(self, pathtodictionary=None): if pathtodictionary is None: # # Insert code here to see if it is in the current # directory and/or look in other directories. # try: self.fp=open(pathtodictionary, 'r') except: print "unable to locate dictionary at: %s" % pathtodictionary else: # # Insert code here to load data from .txt file # fp.close() return def get_stem(self, arg1, arg2): # # Code for get_stem method # The other way I've done this is to have a .INI file that always lives in the same directory as the class with an entry in it that points me to where the .txt file lives. Hope this helps. -Larry Bates Steven Bethard wrote: > Ok, so I have a module that is basically a Python wrapper around a big > lookup table stored in a text file[1]. The module needs to provide a > few functions:: > > get_stem(word, pos, default=None) > stem_exists(word, pos) > ... > > Because there should only ever be one lookup table, I feel like these > functions ought to be module globals. That way, you could just do > something like:: > > import morph > assist = morph.get_stem('assistance', 'N') > ... > > My problem is with the text file. Where should I keep it? If I want to > keep the module simple, I need to be able to identify the location of > the file at module import time. That way, I can read all the data into > the appropriate Python structure, and all my module-level functions will > work immediatly after import. > > I can only think of a few obvious places where I could find the text > file at import time -- in the same directory as the module (e.g. > lib/site-packages), in the user's home directory, or in a directory > indicated by an environment variable. The first seems weird because the > text file is large (about 10MB) and I don't really see any other > packages putting data files into lib/site-packages. The second seems > weird because it's not a per-user configuration - it's a data file > shared by all users. And the the third seems weird because my > experience with a configuration depending heavily on environment > variables is that this is difficult to maintain. > > If I don't mind complicating the module functions a bit (e.g. by > starting each function with "if _lookup_table is not None"), I could > allow users to specify a location for the file after the module is > imported, e.g.:: > > import morph > morph.setfile(r'C:\resources\morph_english.flat') > ... > > Then all the module-level functions would have to raise Exceptions until > setfile() was called. I don't like that the user would have to > configure the module each time they wanted to use it, but perhaps that's > unaviodable. > > Any suggestions? Is there an obvious place to put the text file that > I'm missing? > > Thanks in advance, > > STeVe > > [1] In case you're curious, the file is a list of words and their > morphological stems provided by the University of Pennsylvania. From claudio.grondi at freenet.de Sun Nov 13 08:06:32 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 13 Nov 2005 13:06:32 -0000 Subject: Want to perform unattended installation of SW using python References: <1131879424.943510.320180@g47g2000cwa.googlegroups.com> <1131881151.003036.215510@o13g2000cwo.googlegroups.com> Message-ID: <3tooj6Ftmhd9U1@individual.net> Use AutoIt3 for it and be happy: http://www.autoitscript.com/autoit3/. And if you need Python to be involved in this process, just write out the AutoIt script from Python and then run the AutoIt script from Python, what makes you twice that happy. If you want, you can reinvent the wheel using Python ctypes and the Win32 API, but what for, if AutoIt is already there and has done it all in an excellent way? Claudio "28tommy" <28tommy at gmail.com> schrieb im Newsbeitrag news:1131881151.003036.215510 at o13g2000cwo.googlegroups.com... > Hi, > > first of all- thanks for the quick answer. > You presumed correctly, but unfortunately, I Don't have control of the > preparation process of the package, so I get it as is. I just need to > answer it's questions on each screen of the wizard... > > 10x again > tommy > From kent37 at tds.net Thu Nov 10 10:52:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Nov 2005 10:52:50 -0500 Subject: Confusion about __call__ and attribute lookup In-Reply-To: References: <43734796$1_1@newspeer2.tds.net> Message-ID: <43736a63$1_1@newspeer2.tds.net> Leif K-Brooks wrote: > New-style classes look up special methods on the class, not on the instance: For my future reference, is this documented somewhere in the standard docs? Thanks, Kent From nszabolcs at gmail.com Wed Nov 9 03:11:44 2005 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 9 Nov 2005 00:11:44 -0800 Subject: which feature of python do you like most? In-Reply-To: References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> <042dne8P_Ys9y-zenZ2dnUVZ_sadnZ2d@powergate.ca> Message-ID: <1131523904.215015.238510@g43g2000cwa.googlegroups.com> > which feature of python do you like most? i cannot chose one but here is my list: iterpreter (i can try out things at once) dir(obj) (using dir() i can learn a new library quickly) identation (code is readable, no need for {} and ;) dynamictyping (no type declaration -> less code to write) lightweight oo (no public/protected/private -> less code to write) widespread (it's easy to find a python module for any kind of task) built-in types (creating list, dict is easy, iterator protocol wins) generators (creating an iterator is easy: replace return with yield) listcomprehension (intuitive and clear way of creating lists) pyrex/swig/boostpython (easily extendible with c/c++) crossplatform (i can write code for my win/linux os) free (yes it's free and it has a reasonable license) comp.lang.python (good questions and even better answers, friendly folks:) From alanmk at hotmail.com Mon Nov 14 16:57:10 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: 14 Nov 2005 13:57:10 -0800 Subject: Making a persistent HTTP connection References: <4378e5bb$0$2103$edfadb0f@dtext02.news.tele.dk> <3tsdvaFugk4lU2@uni-berlin.de> Message-ID: <1132005430.138843.206330@f14g2000cwb.googlegroups.com> [David Rasmussen] >> I use urllib2 to do some simple HTTP communication with a web server. >> In one "session", I do maybe 10-15 requests. It seems that urllib2 >> opens op a connection every time I do a request. Can I somehow make it >> use _one_ persistent connection where I can do multiple GET->"receive >> data" passes before the connection is closed? [Diez B. Roggisch] > Are you sure HTTP supports that? Yes, HTTP 1.1 definitely supports multiple requests on the same connection. http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.1 Some HTTP 1.0 clients supported persistent connections through the use of the non-standard "keep-alive" header. > And even if it works - what is the problem with connections being created? The URL above describes the benefits of persistent connections. The primary problem of the old style of one-request-per-connection is the creation of more sockets than are necessary. To the OP: neither urllib nor urllib2 implements persistent connections, but httplib does. See the httplib documentation page for an example. http://www.python.org/doc/2.4.2/lib/httplib-examples.html However, even httplib is "synchronous", in that it cannot pipeline requests: the response to the first request must be competely read before a second request can be issued. HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From nyamatongwe+thunder at gmail.com Sun Nov 20 19:41:12 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 21 Nov 2005 00:41:12 GMT Subject: path module / class In-Reply-To: References: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> <8u6dnWEcZ6-6AuPeRVn-gg@powergate.ca> Message-ID: Peter Hansen: >> There is a cost to the change as there will be two libraries that have >> to be known to understand code. > > Could you please clarify? Which two do you mean? At that point I was thinking about os.path and path.py. Readers will encounter code that uses both of these libraries. > We've mandated use of path.py internally for all projects because we've > noticed (especially with non-expert Python programmers... i.e. junior > and intermediate types, and senior types new to Python) a decrease in > errors. A list of fault reports in this area would be useful evidence. The relative occurence of particular failures (such as incorrect path joining) is difficult to estimate which leads to the common messy handwaving over API choices. To me, one of the bigger benefits of path.py is that it automatically uses Unicode strings on Windows NT+ which will behave correctly in more cases than byte strings. Neil From fredrik at pythonware.com Fri Nov 18 13:09:49 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Nov 2005 19:09:49 +0100 Subject: Speeding up multiple regex matches References: <1132333050.519695.96370@f14g2000cwb.googlegroups.com> Message-ID: "Talin" wrote: > I've run in to this problem a couple of times. Say I have a piece of > text that I want to test against a large number of regular expressions, > where a different action is taken based on which regex successfully > matched. The naive approach is to loop through each regex, and stop > when one succeeds. However, I am finding this to be too slow for my > application -- currently 30% of the run time is being taken up in the > regex matching. > > I thought of a couple of approaches, but I am not sure how to make them > work: > > 1) Combine all of the regular expressions into one massive regex, and > let the regex state machine do all the discriminating. The problem with > this is that it gives you no way to determine which regex was the > matching one. use a capturing group for each alternative, and use lastindex to quickly find the match: http://docs.python.org/lib/match-objects.html lastindex The integer index of the last matched capturing group, or None if no group was matched at all. also see: http://effbot.org/zone/xml-scanner.htm From sybrenUSE at YOURthirdtower.com.imagination Tue Nov 1 09:13:45 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 1 Nov 2005 15:13:45 +0100 Subject: OpenSSL in Python References: <1130425810.431748.39660@g14g2000cwa.googlegroups.com> <1130847768.899376.128360@o13g2000cwo.googlegroups.com> Message-ID: dcrespo enlightened us with: > Excuse me all of you for the way I answered. Sybren, and all of you, > accept my apology. I saw the Sybren's message yersterday late night > in a bad moment. Next time, don't visit Usenet in a bad moment. 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 fakeaddress at nowhere.org Fri Nov 4 23:29:21 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 05 Nov 2005 04:29:21 GMT Subject: python gc performance in large apps In-Reply-To: References: <43594BD5.7050104@u20.org> Message-ID: Robby Dermody wrote: > [...] However, on a > simulated call center environment (constant 50 conversations, switching > every 300 seconds) the director component still consumes an average of > 1MB more per hour and the harvester is taking an average of 4MB more per > hour. With the director, 2/3 of this is resident (1/3 in swap). With the > harvester, about 88% of this is resident (~ 12% in swap). For a long-uptime server, that's obviously not going to work. Memory leaks are of course, bugs, and bugs call for debugging, but given the long history of such bugs in Python and similar projects, there's no real chance of eliminating them. You might look at how the Apache HTTP server deals with this. Apache can stay up arbitrarily long, even when it links in modules with slow memory leaks. A parent process forks off child processes as needed, and the children handle all the client services. Each child is, by default, limited to serving 10,000 connections, a number adjustable via the MaxRequestsPerChild directive. When a child reaches its connection limit, it stops listening for new connection requests; when the last of the connection closes, the child gracefully dies. > [...] I doubt we can remove all the memory > problems, but if we can get this down by another 150 - 200%, that will > be good enough for me. Down by more than 100% ? Wouldn't that require turning memory leaks into memory wells? -- --Bryan From simon at brunningonline.net Mon Nov 28 14:29:26 2005 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 28 Nov 2005 19:29:26 +0000 Subject: How to stop a linux process In-Reply-To: References: Message-ID: <8c7f10c60511281129o38b61a21vd2a4d1a76cd70b55@mail.gmail.com> On 11/28/05, Glen wrote: > When I used the following line to play a midi file in linux, > > return_value = os.system('timidity test.mid') > > I have encountered two problems. > 1. The python script halts until timidity has finished. > 2. If I had control of the script, I can't think how I would stop timidity. > > Any advice on the 'area' of python I should be looking at would be greatly > appreciated. The subprocess module might be worth a look. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From kwiordache at kriocoucke.mailexpire.com Thu Nov 3 06:41:11 2005 From: kwiordache at kriocoucke.mailexpire.com (rix) Date: 3 Nov 2005 03:41:11 -0800 Subject: problem with async_chat Message-ID: <1131018071.506820.142130@g47g2000cwa.googlegroups.com> Hi there, I am writing an application that requires a client-server interaction. Looking up on the internet and working on it I came up with something like this: a class ADFSServer that takes inbound connections and dispatches them to ADFSReceiver. The connection is always initialized by ADFSSender. here is the code: import asynchat import asyncore import socket import string class ADFSServer (asyncore.dispatcher): def __init__ (self, port): asyncore.dispatcher.__init__ (self) self.create_socket (socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() here = ('', port) self.bind (here) self.listen (1) def handle_accept (self): print ("Server is accepting connection") ADFSReceiver (self, self.accept()) class ADFSReceiver (asynchat.async_chat): channel_counter = 0 def __init__ (self, server, (conn, addr)): asynchat.async_chat.__init__ (self, conn) self.set_terminator ('\n') self.server = server self.id = self.channel_counter self.channel_counter = self.channel_counter + 1 self.buffer = '' print ("Receiver created") def collect_incoming_data (self, data): self.buffer.append(data) print ("collecting data") def found_terminator (self): data = self.buffer self.buffer = '' print '[Received Message]\n %s' % (self.id, repr(data)) self.close() return data def handle_close (self): print 'Closing receiver' self.close() class ADFSSender (asynchat.async_chat): def __init__ (self, data, address): print "creating sender" asynchat.async_chat.__init__ (self) #self.set_terminator ("\n") self.create_socket (socket.AF_INET, socket.SOCK_STREAM) self.connect (address) self.push(data) self.push ("\n") if __name__ == '__main__': work1 = ADFSServer (1234) asyncore.loop() I start the server on a shell, and from another shell I launch the ADFSSender. The problem is that if I use the push() function the code doesn't work. If I use the send() it works. As I am using the async_chat class, I would like to use the push() method, so I was wondering what was the problem with my code... thanks, rix From cito at online.de Wed Nov 23 15:19:29 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 21:19:29 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1h6fxle.14lh8381m383fhN%aleax@mail.comcast.net> References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> <1h6f39h.n2wpx91c4cc2qN%aleax@mail.comcast.net> <1h6fxle.14lh8381m383fhN%aleax@mail.comcast.net> Message-ID: >>* C++ has a Map template in the STL which is ordered (a "Sorted >>Associative Container"). Alex Martelli wrote: > Ordered *by comparisons on keys*, NOT by order of insertion -- an > utterly and completely different idea. Shame on me. I talked so much about the difference between "ordered" and "sorted" and now I wrote such a confusing sentence. You're right, C++ Maps are not an example for "ordered dictionaries", but for "sorted dictionaries". -- Christoph From peter at engcorp.com Wed Nov 30 16:41:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 30 Nov 2005 16:41:43 -0500 Subject: python speed In-Reply-To: <1133383306.218266.123210@f14g2000cwb.googlegroups.com> References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133383306.218266.123210@f14g2000cwb.googlegroups.com> Message-ID: Isaac Gouy wrote: > Peter Hansen wrote: >>Judging by the other posts in this thread, the gauntlet is down: Python >>is faster than Java. Let those who believe otherwise prove their point >>with facts, and without artificially handcuffing their opponents with >>non-real-world "purity" requirements. > That form of argument is listed as one of the principal forms of > illogical thinking in "Being Logical" D.Q.McInerny - "An Inability to > Disprove Does Not Prove" Good thing this is the form of argument *against* which I was arguing, rather than that which I choose to use myself. (Read very carefully, if you really think I was saying otherwise, and point out exactly where I made any such claims for my own part. In fact, I was referencing the arguments of others -- who *were* supporting their arguments with facts, as near as I can tell -- and I was calling on the opposition to do the same, and without changing the rules mid-discussion.) > "The fact that there is no concrete proof against a position does not > constitute an argument in favour of the position. I cannot claim to be > right simply because you can't prove me to be wrong." Isn't that what I was saying? That those who claim Python isn't faster were not supporting their arguments with actual facts? -Peter From mwm at mired.org Tue Nov 15 14:27:42 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 15 Nov 2005 14:27:42 -0500 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <86r79ji8lt.fsf@bhuda.mired.org> Message-ID: <86k6f9r9sh.fsf@bhuda.mired.org> Antoon Pardon writes: >>> Like having an assignment operator (let use @= for it) next to a >>> (re)bind operator. >>> We could then have something like the following. >>> a = 5 >>> b = a >>> a @= 7 >>> b ==> would result in 7. >> You've just overwritten the object referred to by the token "5" in the >> source code with the value 7, so you get: >> print 5 >> 7 > You have a valid point, but I think a different approach is possible. > Don't make the distinction between mutable and immutable types but > between mutable and immutable objects. So an int wouldn't be an > immutable type, but 5 would be an immutable object. > So the code above I gave would throw an exception, but the following > might work. > a @= 5 > b = a > b @= 7 > a ==> would result in 7. Which solves that issue but brings up - well, more issues. What happens if the third line is 'b @= "seven"'? Does this require an extra level of indirection in the implementation? Avoiding that kind of thing was the reason for suggesting this: >> Another approach is to have a special object type if you want to allow >> assignment to the object it refers to. That's what Python does now, it >> just doesn't have a syntax just to support that. If it did, your >> example might look like: >> a := 5 >> b = @a >> a := 7 >> @b ==> would result in 7 > Could it also work the other way? By somehow manipulating b change a? It's intended to work the other way as well. But the second line is wrong: it should have been "b = a". "b = @a" assigns b the value referenced by a, and @b would then be an error. "b = a" assigns b to the reference that is a, so that @b returns it's value. The critical thing is that this doesn't introduce any new facilities into the language, just some new syntax, so there's no implementation impact. In fact, if you're willing to put up with some notational abuse, we can do this now: class Ref(object): _unbound = object() def __new__(cls, value = _unbound): """We're an object, but need to ignore the optional argument.""" return object.__new__(cls) def __init__(self, value = _unbound): """Bind the optional value, if provided.""" if value is not self._unbound: self._value = value def __pos__(self): """Return value, if bound.""" try: return self._value except AttributeError: raise ValueError, "%s object does not have a value stored." % \ self.__class__.__name__ def __iadd__(self, value): self._value = value return self Usage: >>> x = Ref.Ref() >>> x += 23 >>> +x 23 >>> a = x >>> x += 25 >>> +a 25 >>> a += "this is a test" >>> +x 'this is a test' Since it doesn't have real lannguage support, things like +x += 25 don't work. That's the only obvious gotcha. Maybe ~ would be a better prefix. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bokr at oz.net Tue Nov 22 15:12:52 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 20:12:52 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> Message-ID: <438379e0.485300825@news.oz.net> On Tue, 22 Nov 2005 13:26:45 +0100, "Fredrik Lundh" wrote: >Duncan Booth wrote: > >> That's funny, I thought your subject line said 'list of tuples'. I'll >> answer the question in the subject rather than the question in the body: >> >> >>> aList = ['a', 1, 'b', 2, 'c', 3] >> >>> it = iter(aList) >> >>> zip(it, it) >> [('a', 1), ('b', 2), ('c', 3)] > >yesterday, we got locals()["_[1]"]. and now this ? > I don't really think those are comparable. >is "relying on undefined behaviour" perhaps the new black ? Is it really undefined? If so, IMO it should be defined to do what it apparently does. > >and people are impressed? it's like my old Z80 days, when >some folks thought it was truly amazing that call(11) printed >the raw contents of the entire memory to the screen... > You really don't think it was cool? Or could be well defined? ;-) Hm, actually, something tells me I've seen some variation of this before, but I can't think of the context off hand. Regards, Bengt Richter From lycka at carmen.se Wed Nov 23 10:07:39 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 23 Nov 2005 16:07:39 +0100 Subject: drawline In-Reply-To: References: Message-ID: Ben Bush wrote: > I had the following code and when I clicked the left mouse button one > time. I got green line and the second click got a purple line and the > green disappeared. > I was confused by two questions: It's good that these postings are archived, so that teachers can check them before grading their students. After all, the grades belong to those who solved the problems, not to those who handed them in... From bignose+hates-spam at benfinney.id.au Wed Nov 16 17:52:32 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Nov 2005 09:52:32 +1100 (EST) Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> <1132178416.518202.138740@f14g2000cwb.googlegroups.com> Message-ID: The Eternal Squire wrote: > >The legality of copying, modifying and redistributing works should be > >reformed until it matches a 6th grader's intuitions about sharing. > > A 6th grader also has intuitions regarding the ownership of an idea. > "It was MY idea!!!" "No, it's NOT!!!" "Is TOO!!!" And what should we teach those children? "Now children, it can be an idea you *both* have, and you both get the benefit. Learn to share." Or, do we instead teach them: "Excellent children! Keep on fighting over who owns ideas, and never share them. That's the sort of society we want you to live in." The more you try to teach them to stop sharing, the more we'll teach them to share. Keep your propaganda about "sharing == evil" away from children. -- \ "Those are my principles. If you don't like them I have | `\ others." -- Groucho Marx | _o__) | Ben Finney From nick.smallbone at gmail.com Sun Nov 13 17:57:37 2005 From: nick.smallbone at gmail.com (Nick Smallbone) Date: 13 Nov 2005 14:57:37 -0800 Subject: ANN: PySizer 0.1 Message-ID: <1131922657.017880.218920@z14g2000cwz.googlegroups.com> I'd like to announce the first release of PySizer, a memory usage profiler for Python code. PySizer was written as part of Google's Summer of Code. The source, documentation and so on are at http://pysizer.8325.org. The current release is at http://pysizer.8325.org/dist/sizer-0.1.tar.gz. The code is kept in a Subversion repository at http://codespeak.net/svn/user/nick8325/sizer. The idea is to take a snapshot of memory use at some time, and then use the functions of the profiler to find information about it. Features -------- * You can make a snapshot of all reachable objects at a given time, organised as a tree (well, a graph, since there are cycles). * For any given object, you can find out how much space it takes up, what objects it references and so on. With a patched version of Python, you can also find out what stack of function calls created an object, and what objects were created by each stack of calls. * You can collect objects into groups. For example, you can group each object according to the module it appears to come from. Then you can treat each module as a single object. * You can filter objects, find the amount of space used by instances of each type, find objects which appeared from one snapshot to the next, find the biggest objects/types/groups, and so on. Requirements ------------ See http://pysizer.8325.org/INSTALL. The main one is Python 2.4 - I will port it to 2.3 soon. Bugs, suggestions, comments, problems, anything else ---------------------------------------------------- You can contact me at nick.smallbone at gmail.com. I would love to know if you find a use for it, too. From steve at REMOVETHIScyber.com.au Sat Nov 19 00:56:54 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 16:56:54 +1100 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> Message-ID: On Fri, 18 Nov 2005 16:26:08 -0800, bonono at gmail.com wrote: > Personally, I would rather see the int() and float() function be > smarter to take what is used for this, i.e. : > > a = int("1,234,567") But the problem isn't just with conversion of strings. It is also with literals. n = 99999999999 Without counting, how many nines? Obviously repeated digits is an extreme case, but even different digits are easier to process if grouped. That's why we write phone numbers like 62 3 9621 2377 instead of 62396212377. Here is a thought: Python already concatenates string literals: "abc" "def" is the same as "abcdef". Perhaps Python should concatenate numeric literals at compile time: 123 456 is the same as 123456. Off the top of my head, I don't think this should break any older code, because 123 456 is not currently legal in Python. -- Steven. From fredrik at pythonware.com Tue Nov 8 07:40:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Nov 2005 13:40:25 +0100 Subject: Sending email in utf-8? References: <1131381565.320532.229310@g49g2000cwa.googlegroups.com> <1131388898.175850.301140@o13g2000cwo.googlegroups.com> Message-ID: "morphex" wrote: > """ > Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST) > Message-Id: <200511071838.jA7IcTKR095057 at thinkering.com> > To: morten at nidelven-it.no, morten at nidelven-it.no > From: morten at nidelven-it.no > Subject: Order confirmation > Content-Type: text/plain; charset="utf-8" > X-Bogosity: No, tests=bogofilter, spamicity=0.000000, version=0.92.8 > > Thank you for your order, it is copied here for your convenience, and > we will process it shortly. > > Name: ?? > Phone: ?? > Email: morten at nidelven-it.no > Comments: asdf > """ that's 0xC3 0xB8 (at least according to my mail reader), which, translated back from UTF-8, looks like a typically norsk character to me... >>> name = "\xc3\xb8".decode("utf-8") >>> print name ? >>> import unicodedata >>> unicodedata.name(name) 'LATIN SMALL LETTER O WITH STROKE' try adding a "Mime-Version: 1.0" header to your mail. a "Content-Transfer-Encoding: 8bit" might not hurt either (or run the body through quopri.encodestring() after you've encoded it, and use "Content-Transfer-Encoding: quoted-printable"). (also check the email package: http://docs.python.org/lib/module-email.html ) From against at spam.pl Wed Nov 2 05:38:59 2005 From: against at spam.pl (=?ISO-8859-2?Q?Grzegorz_=A6lusarek?=) Date: Wed, 02 Nov 2005 11:38:59 +0100 Subject: Python and Lotus Notes Message-ID: Hello everyone. I have to get data from Lotus Notes and i curious is it possible doing it with Python. I heard that Lotus Notes using COM, so the Python does so maybe it can be done? Anyone have any experiences doing that? Ane help will by apreciated Gregor From keesvanschaik at gmail.com Fri Nov 18 20:05:37 2005 From: keesvanschaik at gmail.com (KvS) Date: 18 Nov 2005 17:05:37 -0800 Subject: Confused about namespaces In-Reply-To: References: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> <1132356583.703129.241070@g47g2000cwa.googlegroups.com> <1132358984.915609.306380@g44g2000cwa.googlegroups.com> Message-ID: <1132362337.808127.248870@g14g2000cwa.googlegroups.com> > There's no reason not to just "import wx" if you want that. Yes, that's clear. But if you would make some huge application that has a large number of nested modules, each importing the former one, then avoiding the use of "from ... import *" would mean that you have to use long references like foo1.foo2.... to get to the lowest modules plus that you'd have to check each module for imports outside this tree. If you would use "from ... import *" (except at top level) you have to be aware of overriding, but you can also use this to your advantage and any foo1.attr reference would just work right, without further ado... Or would in such a case a class hierarchy be the thing to use? > No. It creates the foos within each module, but which foo you have > access to in the importing module is determined by the order of > import. Am I understanding correctly that if you have a module foo importing wx and a module main importing both foo and wx there are actually two instances of wx created, one referenced to by (at top level) foo.wx.* and one wx.*? If this is indeed the case it isn't too good for the performance doing this importing of wx multiple times right? - Kees From bokr at oz.net Tue Nov 15 17:21:45 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 15 Nov 2005 22:21:45 GMT Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <11ni1sddrhsm03d@corp.supernews.com> <1132048673.702127.307450@g47g2000cwa.googlegroups.com> Message-ID: <437a39a3.575969720@news.oz.net> On Tue, 15 Nov 2005 21:53:23 +1100, Steven D'Aprano wrote: [...] >It isn't always appropriate or necessary to define "constants" (and I >sometimes wish that Python would enforce assign-once names), but they can >help avoid some silly mistakes. (As I'm sure you know) you can have "assign-once" names if you are willing to spell them with a dot ;-) >>> N = type('',(),{'name':property(lambda _:42)})() >>> N.name 42 >>> N.name = 43 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute One could also write a more efficient write-once guarantee for function scope using a decorator that munges byte code to guarantee it. Or one could write a custom import that guarantees it for module scope. Or one could change the language ;-) Regards, Bengt Richter From daniel.dittmar at sap.corp Wed Nov 16 09:08:50 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 16 Nov 2005 15:08:50 +0100 Subject: initialising a list of lists In-Reply-To: References: Message-ID: Peter Kleiweg wrote: > This does not what I want it to do: > > >>> a = [[]] * 6 > >>> a[3].append('X') > >>> a > [['X'], ['X'], ['X'], ['X'], ['X'], ['X']] > > This does what I want: > > >>> b = [[] for _ in range(6)] > >>> b[3].append('X') > >>> b > [[], [], [], ['X'], [], []] > > The first is clear and wrong. The second is hairy and right. > Is there a way to do it clear Define a function: import copy def init_list (count, element): return [copy.copy (element) for i in xrange (count)] > and right? Test it. Daniel From xah at xahlee.org Tue Nov 1 08:49:35 2005 From: xah at xahlee.org (Xah Lee) Date: 1 Nov 2005 05:49:35 -0800 Subject: Xah's edu corner: the Journey of Foreign Characters thru Internet Message-ID: <1130852975.525590.145080@f14g2000cwb.googlegroups.com> the Journey of Foreign Characters thru Internet Xah Lee, 20051101 There's a bunch of confusions about the display of non-ascii characters such as the bullet "?". These confusions are justifiable, because the underlying stuff is technology, computing technologies, are in a laymen sense, extremely complex. In order to be able to type the bullet char, post it to a newsgroup, and receive the posted material, and have that bullet displayed as a bullet as it was intended, truly involves the availability of several technologies, on the sender's computer, on the receiver's computer, and thru the network that received the posting, and the network the post was retrieved, as well as the configuration of the sender and poster's computers. And, cross your fingers, that all things should go well, but unfortunately, because the fucking asses criminals such as Larry Wall in the computing industry, mostly likely things will not go well. [Disclaimer: all mention of real persons are opinion only.] Here's a quick rundown: ? there needs to be agreed upon a character set. (that is, the set of symbols to be used on computer) Many such character sets includes the bullet symbol. ? there needs to be a code map that maps the alphabets (and any other symbols) to numbers. There are various standard bodies that standardize these character sets and code maps. (usually, but not always, they come together as one) ? now, more technically, once each character has a associated number, this number needs to be turned into actually binary number. This is the encoding part. There are various standards of encoding a character set, that is, turning a sequence of numbers into binary. (the issue involves not just turning integers into binary, but for example marking or demarcating combined characters such as umlaut or initiate or terminate right-to-left writings) Usually but not always, the encoding business is intertwined together with the character set/code map specification, even though they are entirely separate concepts. ? now on your computer, say you are using Windows and OutlookExpress, there's a menu or option somewhere you can see that says text encoding or character set. Now, that's where you tell the computer which of these standardized character/encoding stuff set to choose from to actually represent what you type on the keyboard. (in the case of Chinese for example, you can't type directly, you need another technology Input Methods to type stuff.) ? one of these standard, is called Unicode, wich has a character set that encompasses practically all the world's language's written symbols, including all Chinese (and includes Japanese phonetics and Korean alphabets), as well as Arabic alphabets. (i.e. those hateful Islamic twists the WASPs see) ? once you typed your letter and send it thru a particular encoding in your email/newsreader software, the message went to the network ?news? servers. For a ride around internet, there needs to be more protocols. That is, a way to distinguish from a string a binary digits where does your subject actually starts, where is From, where the To address starts, where is your message content, ... among other things. ? now we are getting really complex... because in the history of software and the internet, in the beginning there's really no support of any character set or all that complex stuff except the ascii (among others), that is to say, only the characters you can see on the keyboard. There isn't much that of Standards. Things basically went on on a as they work basis. Later on these protocols improved in a patch-wise way, to allow one actually to use non-ascii characters or foreign languages, or include pictures or other files such as sound & video as attachment. ? remember that we are bypassing the whole technology of the internet transport protocols themselves. i.e. IP addresses, various layers... down to the physics of wiring, copper optical etc. ? OK, now the newserver received your message, it distribute to other newservers like a spam. ? When you wake up, you open your newsreader hungrily anticipating news. What happens is that your newsreader software (called client) contact the particular server and download the message. (all thru decoding the various many protocols) ? in order for the bullet character to display on your screen, you assume: (1) your computer supports the whole charset/encoding scheme the sender used. (2) your computer has the proper font to display it. (suppose i write chinese to you using Unicode, although your computer supports (understands) Unicode, your computer theoretically understand everything, but because you don't have Chinese fonts, your computer can't display them) (3) and most importantly, nothing has been screwed up in the message's journey on the net. ? Chances are, things did fuck up somewhere. That is why you see "E2=80=A2" (which is due to it being fucked up around the news servers) or a bunch of gibberish (due to you don't have the right font, or software didn't use the right charset/decoding) Now, many of you are actually using google to post/read. Here, google website acts as your newsreader software. Google is pretty good on the whole. It won't fuckup the encoding. However, your computer still needs to support unicode and have the font to show bullet. If you have Windows XP and using Internet Explorer, than you are all fine. If you have latest Mac OS X, you are all fine too. If you have older Windows/Mac, or linux, Solaris or other unixes, you are quite fucked and nobody can help you. Try to see in the menu if there's a encoding/charset/languages and try to see if it has one item called unicode or utf8. Use that. Hactar wrote: ?And "=E2=80=A2" is a good example of why using a bullet is a bad idea, especially when you can't control the charset (or whatever) used.? Now with all the trouble, as to why would someone use a bullet ? that requires some ?advanced? technology then resorting to the simple asterisk * ? Such basically came down to choice. If you really want massive compatibility, you go with the universally available asterisk. If you truly care, you really should write on paper with pen instead. Remember, folks, not everyone on earth has computer. But if you have advanced formality perfection obsession that the moronic grammarian idiots wont, then perhaps asterisks must be done away with by explicit itemization embedded in your writings. ?O brave new worlds, That have such people in them!? Enjoy my unicode rhapsody: http://xahlee.org/Periodic_dosage_dir/t1/ see how your computer does. -------------- This post is archived at: http://xahlee.org/Periodic_dosage_dir/t2/non-ascii_journey.html Xah xah at xahlee.org ? http://xahlee.org/ From bonono at gmail.com Wed Nov 23 23:25:07 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 20:25:07 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> <1132803762.570118.253770@o13g2000cwo.googlegroups.com> Message-ID: <1132806307.326654.12130@g14g2000cwa.googlegroups.com> Peter Hansen wrote: > bonono at gmail.com wrote: > > Which is also my initial puzzle, items() and iteritems() already gives > > you the tuples, why such gurantee or the others ? Doesn't that violate > > the general idiom that if we can do certain thing in one way, there > > better be one and only one way. > > > > Are there other usage scenarios that would be benefit from this as the > > example given is not convincing for me. > > As Jeff's reply emphasizes, the "examples" show tuples with *value* and > then *key*, not the other way around which is what .items() and > .itemitems() gives you. > > Anyway, you didn't ask for good examples of use, just "why is it > guaranteed", and that's all I was showing you. Whether it was a good > idea might be an interesting discussion, but probably not a particularly > useful one given once again that it's unlikely this particular feature > could be undone now that code exists (we can assume) which is dependent > on it. > Please don't take it as a challenge, it was not. If it was, it was about the need for the guarantee, not about you not giving me the answer I want. But it is really wondering why ? As for the (k,v) vs (v,k), I still don't think it is a good example. I can always use index to access the tuple elements and most other functions expect the first element to be the key. For example : a=d.items() do something about a b = dict(a) But using the imaginary example : a = zip(d.values(), d.keys()) do something about a b = dict(a) # probably not what I want. From bobueland at yahoo.com Sat Nov 19 12:52:20 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 19 Nov 2005 09:52:20 -0800 Subject: Can a function access its own name? Message-ID: <1132422739.994588.281770@z14g2000cwz.googlegroups.com> Look at the code below: # mystringfunctions.py def cap(s): print s print "the name of this function is " + "???" cap ("hello") Running the code above gives the following output >>> hello the name of this function is ??? >>> I would like the output to be >>> hello the name of this function is cap >>> Is that possible ? From citronelu at yahoo.com Tue Nov 22 12:37:08 2005 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 22 Nov 2005 09:37:08 -0800 Subject: Timeout for regular expression Message-ID: <1132681028.115173.201230@g47g2000cwa.googlegroups.com> Hi All, Is there a way to set a timeout interval when executing with a re.search ? Sometimes (reason being maybe a "bad" pattern), the search takes forever and beyond... From bonono at gmail.com Wed Nov 9 22:24:04 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 19:24:04 -0800 Subject: [ x for x in xrange(10) when p(x) ] Message-ID: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> Hi, I am wondering if there is such a thing, as python is moving away from FP functions like dropwhile/takewhile etc. From http Thu Nov 10 17:32:59 2005 From: http (Paul Rubin) Date: 10 Nov 2005 14:32:59 -0800 Subject: different binding behavior References: Message-ID: <7xacgcnnfo.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Imagine that ints could be changed in place. Then you could do this: > > x = 0 > x += 1 No nothing like that. Nothing stops you from having multiple int objects with the same value. Lists, for example, are mutable, but x = [0,1] x += [2,3] doesn't change what the literal [0,1] means. From nick at craig-wood.com Tue Nov 15 11:30:17 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 15 Nov 2005 10:30:17 -0600 Subject: simulating #include in python References: Message-ID: Peter Otten <__peter__ at web.de> wrote: > Nick Craig-Wood wrote: > > > I'd?really?like?to?be able to run an __import__ in the context of the file > > thats running the include() but I haven't figured that out. > > execfile()? Yes thats exactly what I was looking for - thank you very much! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mhellwig at xs4all.nl Thu Nov 24 14:23:57 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 24 Nov 2005 20:23:57 +0100 Subject: wxPython Licence vs GPL In-Reply-To: <86zmnuvsv0.fsf@bhuda.mired.org> References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> Message-ID: <43861352$0$11076$e4fe514c@news.xs4all.nl> Mike Meyer wrote: > > Is that software really unavailable, or just unavailable for free? If > the latter, then it's not unavailabe. If the former, the it didn't > become unavailable, as it was never available in the first place. > In the latter case, you could also use those examples to similarly > "prove" that non-GPL'ed software is a "good way to ensure the > availability of IP", as the developers of those IPs obviously felt > that the ability to restrict distribution in some way was needed to > make the effort of developing and distributing the software in the > first place worthwhile. > I agree that your opinions are based on a valid points, however, not available for free means it has a price tag, which means that a normal 'small' price tag for western society excludes +75% of the world population for that product (sure most of them don't want/need it anyway, what good is software without hardware). Those who can not afford the software are excluded for that end product even though they may have worked on the source where 99,99% of the restricted licensed software is based on. However I make a poor defender for the GPL because, as you can read in my previous posts, I don't really believe in it. -- mph From jmdeschamps at gmail.com Wed Nov 16 07:27:20 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 16 Nov 2005 04:27:20 -0800 Subject: How to write an API for a Python application? In-Reply-To: <437af434@news.bezeqint.net> References: <437af434@news.bezeqint.net> Message-ID: <1132144040.194283.285890@o13g2000cwo.googlegroups.com> While not sure of the behavior you are trying to achieve, XML-RPC comes to mind. But it's based on HTTP protocol in which the client puts request to the server which has to respond. The server cannot initiate interactions. XML-RPC is both widely avalaible, and very easy to implement. NOTE: in order for the server to raise events in the client, the client needs only raise periodically a *need-anything-from-me* type of request which permits the server to return its request in response to the client. Naturally this solution makes superfluous calls takes some bandwidth, so it might not be appropriate in every circumstance. From rrr at ronadam.com Wed Nov 9 20:56:38 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 10 Nov 2005 01:56:38 GMT Subject: How to convert a number to hex number? In-Reply-To: References: <1131442115.025438.326670@g49g2000cwa.googlegroups.com> <1131464101.546746.107110@g47g2000cwa.googlegroups.com> <7xmzkfrum1.fsf@ruckus.brouhaha.com> <43712759.482516031@news.oz.net> <9Cbcf.186716$xl6.130920@tornado.tampabay.rr.com> Message-ID: Klaus Alexander Seistrup wrote: > Ron Adam wrote: > > >>I just happen to have been playing around with converting bases >>the last couple of days. (idonowhy) ;-) >> >>Oh yeah, I was thinking of using base62 to generate non-repeating >>id strings and wanted to try it out. > > > Shameless plug: > > Have a look at my bconv at . While it > doesn't handle base 62, it handles bases 2..36 neatly. > > Cheers, I took a look, underneath it's pretty much the same as the routines we posted. In any case it doesn't address the issue Bengt was refering to either, for which I agree could be improved in Python. For example my hp calculator displays base two's compliment for negative binary, octs, and hex numbers, and displays -value for decimal numbers. I think this is what he wants along with a prefix to indicate the base. Cheers, Ron From sdeibel at wingware.com Wed Nov 9 22:25:48 2005 From: sdeibel at wingware.com (sdeibel) Date: Wed, 9 Nov 2005 22:25:48 -0500 (EST) Subject: ANN: Wing IDE for Python 2.0.4 released Message-ID: Hi, Wing IDE for Python 2.0.4 has been released. This is a bugfix release and is a free upgrade for Wing IDE 2.0 users. It can be downloaded from: http://wingware.com/downloads Highlights of this release include: * Preference for syntax highlighting colors in Python, C/C++, and Java files * Support for Zope 2.8 and gtk 2.8 * Modest improvements in search performance * Template panel is part of default tool set (Wing Pro only) * Over 40 bug fixes This release is available for Windows, Linux, and Mac OS X, and can be compiled from sources on *BSD, Solaris, and other Posix operating systems. A complete list of changes is available here: http://wingware.com/pub/wingide/2.0.4/CHANGELOG.txt For more information see: Product Info: http://wingware.com/products Sales: http://wingware.com/store/purchase Upgrades: http://wingware.com/store/upgrade Sincerely, Stephan Deibel -- Wingware Wing IDE for Python Advancing Software Development www.wingware.com From aleax at mail.comcast.net Thu Nov 3 00:26:37 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 2 Nov 2005 21:26:37 -0800 Subject: Nested List Question References: <1130995475_2055@spool6-east.superfeed.net> Message-ID: <1h5f4t2.1yv785h120xalfN%aleax@mail.comcast.net> Newsfeeds wrote: > Hello All, > > Could anyone tell me why this code produces the output it does? ... > gridSystemId = [[None]*columns]*rows You've made gridSystemID a list of `rows` references to the SAME "inner" list, so the behavior you observe is the only possible one. If you want copies instead, ASK for copies...: gridSystemId = [ [None]*columns for x in xrange(rows) ] Alex From kent37 at tds.net Thu Nov 3 19:09:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Nov 2005 19:09:02 -0500 Subject: Learning multiple languages (question for general discussion) In-Reply-To: References: Message-ID: <436aa45c$1_1@newspeer2.tds.net> John Salerno wrote: > I thought it might be interesting to get some opinions on when you know > when you're "done" learning a language. I've been learning C# for a few > months (albeit not intensively) and I feel I have a good grasp of the > language in general. Never? When you move on? You can become proficient in a couple of months but that is different from "expert" which is different from "knows everything there is to know". I have been using Python for several years and I still learn from the old hands in this news group. Kent From jepler at unpythonic.net Sat Nov 12 14:49:02 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 12 Nov 2005 13:49:02 -0600 Subject: Tkinter and the re/sizing of columns in a grid In-Reply-To: <87fyq1ygqt.fsf@subopt.austin.rr.com> References: <87fyq1ygqt.fsf@subopt.austin.rr.com> Message-ID: <20051112194902.GB27610@unpythonic.net> Normally, an entry widget requests horizontal space equal to the value of the width= option times the "average" character width of the font it displays. Setting it to 0 makes the entry request exactly enough width to show the string it contains. Making them sticky to the east and west sides of their areas make them grow to the size of the grid cell, if it is larger than their requested size. Making the grid column have nonzero weight means that if the user resizes the window to be wider, extra space will be given to the entry widgets. Perhaps this program does what you're looking for: #----------------------------------------------------------------------- from Tkinter import * t = Tk() l1 = Label(t, text="String 1:") l2 = Label(t, text="String 2:") e1 = Entry(t, width=0); e1.insert("end", "eggs"); e1.focus() e2 = Entry(t, width=0); e2.insert("end", "spam") l1.grid(row=0, column=0, sticky="w") l2.grid(row=1, column=0, sticky="w") e1.grid(row=0, column=1, sticky="ew") e2.grid(row=1, column=1, sticky="ew") t.grid_columnconfigure(1, weight=1, minsize=120) t.wm_title("entry width demo") t.mainloop() #----------------------------------------------------------------------- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tomkori at gmx.net Wed Nov 30 04:28:04 2005 From: tomkori at gmx.net (Thomas Korimort) Date: Wed, 30 Nov 2005 10:28:04 +0100 Subject: Debugging functionality for embedded Python Message-ID: <438d70a3$0$20777$91cee783@newsreader01.highway.telekom.at> Hi, i have embedded the Python 2.3 engine into a C++ framework. Now i want to add to the basic editing features that are provided by this C++ framework also some debug functionality. Until now i did not find any documentation on how to do this. The Python C/API manual does not say much about it. Does anyone know any literature/references regarding this topic? What i would need would be tracebacks of errors with info on line numbers, files and so on. Greets, Thomas Korimort. From blahman Fri Nov 4 03:57:03 2005 From: blahman (blah@blah.blah) Date: Fri, 04 Nov 2005 02:57:03 -0600 Subject: I Need Motivation Part 2 Message-ID: i m currently in a network (LAN). i started python because i heard that it has great ability for networking programs and/or scripts, but i m losing my motivation with python because there are sooo many modules, that i cant just learn them all, this deters from c or c++ in which there are only a limited number of header files. what loses my interest is that if i cant learn these modules, and there are lots and lots of python modules, how can i ever be a good enough programmer/scripter. -- * Posted with NewsLeecher v3.0 Beta 7 * http://www.newsleecher.com/?usenet From jmdeschamps at gmail.com Fri Nov 25 17:27:03 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 25 Nov 2005 14:27:03 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132957623.380383.239500@g47g2000cwa.googlegroups.com> It all really depends on what you wish to achieve. Results are generally in proportion to the effort involved. I don't think a "Python for Nulls" exists ! the following thread deals with documentation for beginners (and others as well) http://groups.google.ca/group/comp.lang.python/browse_frm/thread/4b7a01e1feb128fa/2b6b186a96c4fa73?hl=en#2b6b186a96c4fa73 For Tkinter the basic document is Fredrik Lundh's 'Introduction to Tkinter' (you can google to easily find this) and also one from New Mexico Tech at http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html If you're intent on doing image manipulation, I would advise that you consider the Python Imaging Library (known as PIL). Pain is a very personal concept - what can be a painful endeavor for some might be a enticing challenge for another ;-) Good luck. From robert.dowell at gmail.com Wed Nov 9 11:47:58 2005 From: robert.dowell at gmail.com (robert.dowell at gmail.com) Date: 9 Nov 2005 08:47:58 -0800 Subject: PIL-> Tkinter In-Reply-To: References: <1131551783.628602.3320@g14g2000cwa.googlegroups.com> Message-ID: <1131554878.017628.43180@g44g2000cwa.googlegroups.com> I have an app that I wrote to move images from a camera/portable media to an archive directory. It is using TKInter and PIL to display each jpg as it is transfered. I can email you the code if you would like. From timr at probo.com Fri Nov 18 00:01:50 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 18 Nov 2005 05:01:50 GMT Subject: AJAX => APAX? Or: is there support for python in browsers? References: <6qpln1hg7q5up93kder88seduphnjpebtg@4ax.com> <1h6439o.11s40bt880tllN%aleax@mail.comcast.net> Message-ID: aleax at mail.comcast.net (Alex Martelli) wrote: >Tim Roberts wrote: > ... >> Internet Explorer will allow any registered ActiveScript language to be >> used in a web page. Python qualifies. In the latest Win32 extensions, >> there is a script in win32comext/axscript/client/pyscript.py that will >> register Python as an ActiveScript language. >> >> The you can say >> >> > >Out of curiosity, how "sandboxed" is this Python? I remember a similar >solution being withdrawn once because it wasn't really safely sandboxed, >so the ``script'' could easily do any arbitrary damage to the machine... I remember this as well. I thought the holes were largely plugged, but I admit to losing track of the discussion. Is Mark Hammond in the viewing audience? One of the compromises is that the pywin32 installer does not perform this registration automatically. The script is present, but you have to run the registration script yourself. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mwm at mired.org Wed Nov 23 19:19:26 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 19:19:26 -0500 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> Message-ID: <86wtiy28z5.fsf@bhuda.mired.org> yomgui writes: > Mike Meyer wrote: >> yomgui writes: >> > is it legal to return inside a for loop >> > or am I obliged to break out of the loop before returning ? >> Try it and see: > it is not because it does work on an implementation of python > that it will work on any other platform or in the futur. That's true no matter how you arrive at your answer. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From danger90 at gmail.com Sun Nov 13 15:19:53 2005 From: danger90 at gmail.com (danger) Date: 13 Nov 2005 12:19:53 -0800 Subject: Error Message-ID: <1131913193.620415.268620@g47g2000cwa.googlegroups.com> hi everybody, i have a problem with py2exe that gives me this error: ImportError: could not import pango ImportError: could not import pango Traceback (most recent call last): File "acqua.py", line 40, in ? File "gtk\__init__.pyc", line 113, in ? AttributeError: 'module' object has no attribute 'Font' does anybody knows how to solve it? From steve at holdenweb.com Fri Nov 4 06:38:22 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Nov 2005 11:38:22 +0000 Subject: Class Variable Access and Assignment In-Reply-To: <7x3bmcemgf.fsf@ruckus.brouhaha.com> References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> <8764r8u3wr.fsf@keizer.soze.com> <7xy844vhz6.fsf@ruckus.brouhaha.com> <87wtjosoqi.fsf@keizer.soze.com> <7x3bmcemgf.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Stefan Arentz writes: > >>>Are you seriously saying there's lots of Python projects that would >>>break if this particular weirdness were fixed? >> >>I have no numbers of course. But, why is this a weirdness? > > > Do you seriously think the number is larger than zero? Do you think > that's any good way to write code? > Well it would break the Medusa asyncore/asynchat-based server software, so I can confidently predict the number would be greater than zero, yes. Several fine programmers have relied on the (documented) behavior, I suspect, as it's a convenient way to install per-instance defaults, for example. > Examples of the weirdness have already been given. My favorite is the > one where b.a is a list instead of an integer, in which case the class > variable gets updated instead of an instance variable getting created. > If you don't find the inconsistency to be weird, then ducky for you. Ho, hum. -- 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 Fri Nov 11 03:13:50 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Nov 2005 09:13:50 +0100 Subject: modify dictionary while iterating References: <1131695154.274238.113690@f14g2000cwb.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > hi > I wish to pop/del some items out of dictionary while iterating over it. > a = { 'a':1, 'b':2 } > for k, v in a.iteritems(): > if v==2: > del a[k] > > the output say RuntimeError: dictionary changed size during iteration > how can i suppress this message in an actual script and still get the > final value of the dict? > is it something like try/except/else statment? > try: > for v,k in a.iteritems(): > if v==something: > del a[k] > except RuntimeError: > < don't know what to do here> > else: > < should i include this part ? > > > what other ways can i do this ? thanks for any help. If you expect to delete only a few items: >>> a = dict(a=1, b=2, c=3, d=2) >>> delenda = [k for k, v in a.iteritems() if v == 2] >>> for k in delenda: ... del a[k] ... >>> a {'a': 1, 'c': 3} If you expect to delete most items: >>> a = dict(a=1, b=2, c=3, d=2) >>> a = dict((k, v) for k, v in a.iteritems() if v != 2) >>> a {'a': 1, 'c': 3} or (if rebinding a is not an option) >>> a = dict(a=1, b=2, c=3, d=2) >>> for k, v in a.items(): ... if v == 2: ... del a[k] ... >>> a {'a': 1, 'c': 3} Peter From erchamion.beren at gmail.com Mon Nov 21 03:35:20 2005 From: erchamion.beren at gmail.com (Sinan Nalkaya) Date: Mon, 21 Nov 2005 10:35:20 +0200 Subject: need help about time.sleep, timer In-Reply-To: <6gbtn1h9i8rvhf1gp1gg0aoludvlfhuop0@4ax.com> References: <8u6dnWAcZ69AAuPeRVn-gg@powergate.ca> <6gbtn1h9i8rvhf1gp1gg0aoludvlfhuop0@4ax.com> Message-ID: <438186C8.6020209@gmail.com> Dennis Lee Bieber wrote: >On Fri, 18 Nov 2005 22:45:37 -0500, Peter Hansen >declaimed the following in comp.lang.python: > > > >>It's quite unclear whether the last part, above, is one of your >>*requirements*, or a description of a problem you are having with your >>current approach. Do you *want* it to wait forever if you don't enter >>anthing? >> >> >> > As I understand it, he (?) wants to accumulate characters to be >passed to a certain function -- but the function is not to be invoked >until after a time period has expired; the time period resetting on each >character entered. > > Something I'd do with threads, queues, and sleep... > >PSEUDOCODE > >thread1: > while not Shutdown: > ch = getChar() > q.put(ch) > > >thread2: #or main > while not Shutdown: > chars = [] > while True: > sleep(max_interval) > if q.empty(): break #no input since start of sleep > while not q.empty(): #collect all input from sleep > chars.append(q.get()) > inp = "".join(chars) > function(inp) > > > > > i appreciate your comments and ideas. Dennis told exactly what i tried to say :), code seems to be fine but during sleep action i think the above code does not execute if q.empty(): break #no input since start of sleep while not q.empty(): chars.append(q.get()) i need something, while sleeping, executes the function that waits for input from keyboard. i imagined something like that, i have a queu, it both stores the keys that pressed and pressing times of these keys, then i`ll proccess these times. here is scenario input : 5 after 10 seconds later input 5 is being proccessed return back to main function input : 1 after 5 seconds , other input 5 after 5 more seconds , 15 is being proccessed Thanks. From mwm at mired.org Fri Nov 25 16:46:27 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 25 Nov 2005 16:46:27 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> Message-ID: <86u0e0h03w.fsf@bhuda.mired.org> Christoph Zwerschke writes: > Mike Meyer schrieb: >> Ok, how about this for dictionaries/sets: >> Any hashable object can be used as a dictionary key (set >> member). Immutable >> objects, except for tuples that contain a non-hashable object, are >> hashable. Python classes are normally hashable(1). > I would be even more simple here, like that: > The keys can be arbitrary immutable objects. Thus lists, sets or > dictionaries are not allowed as keys. Tuples are allowed if they do > not directly or indirectly contain mutable objects. More exactly, the > keys are required to be hashable (1). > And then go on and define "hashable" in the footnot. > I think that is easy and understandable and covers the basic cases. You're shifting the emphasis from hashable back to mutable, which is the problem that I'm trying to fix. The mutability - or immutability - of an object is irrelevant to the question of whether or not they can be a dictionary key/set element. The critical property is that they are hashable. *Most* immutable builtin types are hashable, and no builtin mutable types are hashable, which deserves a mention. Once you get away from the builtins, mutability simply stops mattering. Giving mutability top billing is simply wrong. >> And the footnote is: >> Instances of Python classes are hashable if they define a __hash__ >> method, or if they don't define either __cmp__ or __eq__. > I think that's not exact enough. For instance, ordinary lists also > define a __hash__ method but are not hashable since that method just > raises an exception. Ordinary lists aren't Python classes. > Also, as Martin pointed out, if both is there > (__hash__ and __cmp__/__eq__) you would also require of a "proper" > __hash__ method that equal objects hash the same. Otherwise, semantics > would suffer, you could have dicts with non-unique keys (i.e. keys > which are only distinct as objects, but not different as values). Um, actually, I pointed that out (possibly as well), and included it in one of the earlier versions. I was contemplating moving it elsewhere, and accidently left it out. It certainly deserves mention somewhere; I'm just not sure that here is the right place. Along with __hash__ seems more appropriate. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From DonQuixoteVonLaMancha at gmx.net Tue Nov 15 17:42:14 2005 From: DonQuixoteVonLaMancha at gmx.net (DonQuixoteVonLaMancha at gmx.net) Date: 15 Nov 2005 14:42:14 -0800 Subject: Is there any Iterator type example? In-Reply-To: References: Message-ID: <1132094534.005800.289330@o13g2000cwo.googlegroups.com> How about this one: import os from os.path import join def py_files(dir): for root, dirs, files in os.walk(dir): for name in files: if name.lower().endswith(".py"): yield join(root,name ) if __name__=="__main__": dir= "C:\\Python23\\" for f in py_files(dir): print f In my opinion, iterators have two advantages: 1. They can make it easier to iterate over complicated structures, like a file tree in the above example. 2. Since they store only information on how to access the next item, they need often less memory. For example, map(f, list) creates a new list [f(L) for L in list], while itertools.imap(f,list) creates an iterator object. The iterator object often needs much less memory than the new list. There was also a dicussion on this topic on the tutor list two days ago, maybe you'd like to join. Kind regards, Karsten. Thomas Moore schrieb: > Hi: > > Is there any example about how to use Iterator type? > > --Thomas From aleax at mail.comcast.net Fri Nov 11 10:52:48 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 11 Nov 2005 07:52:48 -0800 Subject: Import statements for timeit module References: <1131715618.580594.68630@z14g2000cwz.googlegroups.com> <4374b8f8$0$31636$626a14ce@news.free.fr> <1131724191.716900.314710@o13g2000cwo.googlegroups.com> Message-ID: <1h5ur6i.1ndqad11ush1ktN%aleax@mail.comcast.net> ChaosKCW wrote: > So timeit is mostly useless then ? No, it's a precious jewel, but if you want to use it you must allow it to import the code you want it to run. Alex From jepler at unpythonic.net Mon Nov 14 15:34:22 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 14 Nov 2005 14:34:22 -0600 Subject: Tix BUG? Where to submit? In-Reply-To: <9E5ef.14634$4n5.2187@dukeread01> References: <9E5ef.14634$4n5.2187@dukeread01> Message-ID: <20051114203421.GC25848@unpythonic.net> Since this is a bug in Python (Tix.py), it should be submitted to the Python Patch tracker at sf.net/projects/python You need a free "sourceforge" account to submit an item to the bug or patch tracker. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mwm at mired.org Sat Nov 19 23:44:48 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 19 Nov 2005 23:44:48 -0500 Subject: Delays getting data on sys.stdin.readline() ? References: Message-ID: <86u0e8gc73.fsf@bhuda.mired.org> Christian Convey writes: > I've got a program that (ideally) perpetually monitors sys.stdin for > lines of text. As soon as a line comes in, my program takes some > action. > The problem is, it seems like a very large amount of data must > accumulate on sys.stdin before even my first invocation of readline() > returns. This delay prevents my program from being responsive in the > way it must be. readline normally returns as soon as it sees a newline. External conditions may cause this to change, or make it impossible. Without knowing those external conditions, the best we can do is guess as to what might be the problem. > Has anyone else seen this effect? If so, is there a reasonable workaround? Yes, and maybe. Depends on what's causing the problem. Tell us more about the program, and what sys.stdin is connected to, and the platform you're running on, and someone should be able to provide explicit information. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From samrobertsmith at gmail.com Sat Nov 12 08:32:29 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 05:32:29 -0800 Subject: about array,arange In-Reply-To: References: <1d987df30511120252w3b07b187l71db482bffe35a11@mail.gmail.com> Message-ID: <1d987df30511120532w4b8a82cdi1ad54ac57926c4d7@mail.gmail.com> On 11/12/05, Robert Kern wrote: > Shi Mu wrote: > > i got confused by the use of array and arange. > > arange get array and range get list, why we need the two different types? > > When you're asking questions about a third-party module, it's a good > idea to mention the module. In this case you're asking about scipy_core > (hopefully) or else numarray or Numeric. > > The answer to your question is that sometimes we need to get largish > arrays (not lists) of consecutive numbers quickly. array(range(N)) is > wasteful of memory and time because it has to create a list of Python > ints that are simply going to be thrown away once we're done converting > to the needed array. > > -- > Robert Kern > rkern at ucsd.edu still not clear. can you give an example? Thanks! it is from numeric module (really confused by the documentation) From simon.brunning at gmail.com Wed Nov 2 14:01:01 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 2 Nov 2005 19:01:01 +0000 Subject: Python's website does a great disservice to the language In-Reply-To: References: <1130873528.812783.75600@g43g2000cwa.googlegroups.com> Message-ID: <8c7f10c60511021101j1cc6066ag@mail.gmail.com> On 02/11/05, Fredrik Lundh wrote: > a version of Paint that works on a Mac, an obstreperous mentality, > and a sense of humour. what else do you need? Biscuits. You need biscuits. Treating-this-thread-as-seriously-as-it-deserves-ly y'rs, Simon B. From spam at me.please Mon Nov 7 05:13:20 2005 From: spam at me.please (Skink) Date: Mon, 07 Nov 2005 11:13:20 +0100 Subject: strange sockets In-Reply-To: <8ft*3tU2q@news.chiark.greenend.org.uk> References: <8ft*3tU2q@news.chiark.greenend.org.uk> Message-ID: Sion Arrowsmith wrote: > > conn.sendall(struct.pack("!i", len(data)) + data) > > or after creating conn > > conn.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) > > to disable Nagle. > Sion, thank you for your help, it works but... it works when client & server is in python i tried both solutions and they work when client is client.py they both don't work when client is java client when i tried to connect python's server by java client i have the same: % java Loader server.py server.py server.py init 29 server.py reading 631 1 server.py reading 631 40 server.py reading 631 41 why? thanks, skink. From scott.daniels at acm.org Thu Nov 24 08:00:25 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 24 Nov 2005 05:00:25 -0800 Subject: Making immutable instances In-Reply-To: References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> Message-ID: <4385b7cd@nntp0.pdx.net> Ben Finney wrote: > Alex Martelli wrote: >>Ben Finney wrote: >> >>>How can a (user-defined) class ensure that its instances are >>>immutable, like an int or a tuple, without inheriting from those >>>types? >> >>You can make a good start by defining __setattr__, __delattr__ (and >>__setitem__ and __delitem__ if your class is a container) to raise >>exceptions. >>Remember that your redefined __setattr__ IS "in place" even when >>you're initializing your istance, so remember to delegate attribute >>setting to the superclass (the other special methods mentioned above >>are less likely to byte you). > > So, for a class that needs to set attributes in __init__ (but after > that, become immutable), how do I get around this? Should I make a > _FooFunctionality class, and then inherit from that to make Foo as the > immutable class that actually gets exported? Typically, constants are set up in __new__ (which happens before __init__), because by __init__ time the object is built. Remember not to complain that you have no copy operation, because there is no such thing as a copy of a constant (the original constant is good enough). --Scott David Daniels scott.daniels at acm.org From erchamion.beren at gmail.com Thu Nov 17 10:27:02 2005 From: erchamion.beren at gmail.com (Sinan Nalkaya) Date: Thu, 17 Nov 2005 17:27:02 +0200 Subject: get just one character Message-ID: <437CA146.6040801@gmail.com> hello everybody, how can i just get 1 character ? i`ve done a search but just found getch() for windows, i need same for unix and raw_input has any option that is not documented ? thanks. From bignose+hates-spam at benfinney.id.au Fri Nov 11 08:04:56 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Nov 2005 00:04:56 +1100 (EST) Subject: Needed class whose instances are many test cases References: <1131706265.113961.63370@f14g2000cwb.googlegroups.com> Message-ID: Sumit wrote: > I have scinario like I have to Create resource(in __init__()) Before > Running a set of testcases and then In Testcases resources are going > to used and then It will cleared off after Running the testcases by > destructor __del__() This is a poor design; your tests will each be starting in a different state, and will likely not run the same way if run in a different order, making them fragile. Test cases should each run individually, from a known state, and not depend on any other tests. You can define a fixture for several tests in the unittest.TestCase methods setUp() and tearDown(), to establish and clear up respectively for each test. -- \ "When I wake up in the morning, I just can't get started until | `\ I've had that first, piping hot pot of coffee. Oh, I've tried | _o__) other enemas..." -- Emo Philips | Ben Finney From robert.kern at gmail.com Sun Nov 27 22:10:15 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 27 Nov 2005 19:10:15 -0800 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: >>>Let me ask back: Do I really need to bother and justify it with a use >>>case in a case where the language can be easily made more consistent or >>>orthogonal without breaking anything? > > Robert Kern wrote: > >>Yes. If it's not going to be used, then there's not much point. >>Practicality beats purity, and all that. > > I have nothing against "practicality beats purity". But to stay with the > examples I have given, in how far is writing list(t).index(x) more > practical than t.index(x)? I'm not arguing that the things you mentioned shouldn't be changed. I'm saying that use cases really are important in making design decisions. You just provided one. Congratulations. > And by the way, if we are speaking about practicality here, are we > speaking about practicality for the Python developers or for the Python > users? This may be sometimes be in opposition. As Paul noted, it was a misuse of the phrase. I withdraw it. >>However, I will note that if you were to present us with a working patch >>with documentation and unittests, then you'll probably get responses >>along the lines of "Thank you!", instead. > > Not everybody has the time and skills to provide that. Ordinary people > from the Python user base should be given the opportunity to make > suggestions for improvement - of course not in the tone of "I > demand...", but they should not be automatically regarded as "demanding" > if they just utter their opinion or make a suggestion either. > > Even if I had the time and skills, before starting to work on a patch, > unittests etc. I still would first discuss with others whether my > suggestion is reasonable and would be appreciated by the "user base", > developers and the BDFL. Just take the example of the following patch: > https://sourceforge.net/tracker/?func=detail&atid=305470&aid=403693&group_id=5470 > > It was not rejected by reason of missing unittests or documentation, but > the very idea was rejected. And it also appears to have nothing to do with the lack of proffered use cases but (primarily) Guido's thoughts about how the different objects are supposed to be used. That's why use cases are so important. They allow developers to talk about real, concrete issues. -- 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 bignose+hates-spam at benfinney.id.au Wed Nov 16 18:02:12 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Nov 2005 10:02:12 +1100 (EST) Subject: JMS yet again References: <1132136625.101816.40520@g49g2000cwa.googlegroups.com> Message-ID: Aahz wrote: > Am I the only person who immediately thought of Babylon 5 and > wondered if I was in the wrong newsgroup? I plead guilty. -- \ "I like to reminisce with people I don't know. Granted, it | `\ takes longer." -- Steven Wright | _o__) | Ben Finney From bill.mill at gmail.com Tue Nov 8 15:46:25 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue, 8 Nov 2005 15:46:25 -0500 Subject: PYTHON LOOSING FOR JAVA??????? In-Reply-To: <436FD5D4.7010307@v.loewis.de> References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> <436FD5D4.7010307@v.loewis.de> Message-ID: <797fe3d40511081246h46169553x1f2a1289b1837864@mail.gmail.com> On 11/7/05, "Martin v. L?wis" wrote: > Fcamattti wrote: > > Hello for everybody???? > > > > So I have a doubt. I'd like to know what do you think about the joint > > of efforts of Sun Microsystems and the Google to create a office web > > based. I sincerely enjoy the idea althoug I'd like to know what will be > > the future of this wonderful language called Python?????? > > I think I know???? Although, the future is difficult to predict??? +1 QOTW Peace Bill Mill bill.mill at gmail.com From kdahlhaus at yahoo.com Mon Nov 28 10:19:07 2005 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 28 Nov 2005 07:19:07 -0800 Subject: Book: Cross-Platform GUI Programming with wxWidgets? Message-ID: <1133191147.864680.235820@g47g2000cwa.googlegroups.com> I was wondering if people using wxPython found this book useful? Is it worth the money? Thanks From lee at example.com Fri Nov 11 17:58:43 2005 From: lee at example.com (Lee Harr) Date: Fri, 11 Nov 2005 22:58:43 GMT Subject: odd behavior References: <1131737687.314760.265370@g44g2000cwa.googlegroups.com> Message-ID: On 2005-11-11, Kristian Zoerhoff wrote: > On 11 Nov 2005 11:34:47 -0800, Greg wrote: >> Forgive me, and be kind, as I am just a newby learning this language >> out of M.L. Hetland's book. The following behavior of 2.4.1 seems very >> strange >> >>> x = ['aardvark', 'abalone', 'acme', 'add', >> 'aerate'] >> >>> x.sort(key=len) >> >>> x >> ['add', 'acme', 'aerate', 'abalone', 'aardvark'] >> >>> x.sort(reverse=True) >> >>> x >> ['aerate', 'add', 'acme', 'abalone', 'aardvark'] >> The function called on line 4, at least to me, should work on x as it >> was on line 3, not the previously existing x on line 1. What gives? > > The key option defaults to an alphabetic sort *every time* you call > sort, so if you want to change this, you must call for your sort key > each time. To do what you want, roll the sorts into one step: > >>>> x.sort(key=len, reverse=True) >>>> x > ['aardvark', 'abalone', 'aerate', 'acme', 'add'] > > ... or just reverse it after: >>> x.sort(key=len) >>> x.reverse() >>> x ['aardvark', 'abalone', 'aerate', 'acme', 'add'] From dcrespo at gmail.com Fri Nov 11 10:16:21 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 11 Nov 2005 07:16:21 -0800 Subject: how to start a process and get it's pid? In-Reply-To: References: <43745C93.70907@sitasoftware.lu> <1131713940.819881.6320@g43g2000cwa.googlegroups.com> Message-ID: <1131722181.861194.179550@g49g2000cwa.googlegroups.com> > >>> import subprocess > >>> p = subprocess.Popen("c:/windows/notepad.exe") > >>> p.pid > 1948 Yes, it works. But in my case, I need to run the program totally separated from my main program. So, when I start a new program through subprocess, it doesn't unlink. I mean, if I close my main app, so does the launched program. With startfile() it does the job, but I then I have to find what pid is through win32all module, etc. it would be very good if I can use spawnl Daniel From arkanes at gmail.com Fri Nov 18 18:24:07 2005 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Nov 2005 17:24:07 -0600 Subject: Web-based client code execution In-Reply-To: <3u6q0kFvnv1qU2@individual.net> References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> <3u6q0kFvnv1qU2@individual.net> Message-ID: <4866bea60511181524o6e4f8d0bx5c0ee7fdf54b7875@mail.gmail.com> On 11/18/05, Paul Watson wrote: > Steve wrote: > > AJAX works because browsers can execute javascript. I don't know of a > > browser that can execute python. Basically your stuck with java or > > javascript because everything else really isn't cross platform. > > Well, I guess the Grail browser could run Python, but I do not think I > can go there. > > I need READ access to the users local disk storage. Can I do this in > Javascript, or should I bite the bullet and turn to ActiveX? This can only be done with scripts by disabling or bypassing browser security restrictions. It can't even be done by zone in IE, only globally, and I don't know if you can do it at all in Mozilla based browsers. A signed activex control or Java Applet (that registers for the appropriate sandbox permissions) will work. Overall, it's probably simplest not to do any of these and simply write a standard application that you have users download and run. This is the safest and most straightforward solution, and honestly what you save in configuration managment when people call you wondering why it doesn't work is probably worth the extra effort it takes them to actually run your application. > -- > http://mail.python.org/mailman/listinfo/python-list > From fdu.xiaojf at gmail.com Sat Nov 19 23:28:07 2005 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Sun, 20 Nov 2005 12:28:07 +0800 Subject: what happens when the file begin read is too big for all lines to be read with "readlines()" In-Reply-To: References: <1132399371.267088.291000@g14g2000cwa.googlegroups.com> Message-ID: <437FFB57.6010101@gmail.com> Steven D'Aprano wrote: >On Sun, 20 Nov 2005 11:05:53 +0800, Xiao Jianfeng wrote: > > > >> I have some other questions: >> >> when "fh" will be closed? >> >> > >When all references to the file are no longer in scope: > >def handle_file(name): > fp = file(name, "r") > # reference to file now in scope > do_stuff(fp) > return fp > > >f = handle_file("myfile.txt) ># reference to file is now in scope >f = None ># reference to file is no longer in scope > >At this point, Python *may* close the file. CPython currently closes the >file as soon as all references are out of scope. JPython does not -- it >will close the file eventually, but you can't guarantee when. > > > >> And what shoud I do if I want to explicitly close the file immediately >>after reading all data I want? >> >> > >That is the best practice. > >f.close() > > > > Let me introduce my problem I came across last night first. I need to read a file(which may be small or very big) and to check line by line to find a specific token, then the data on the next line will be what I want. If I use readlines(), it will be a problem when the file is too big. If I use "for line in OPENED_FILE:" to read one line each time, how can I get the next line when I find the specific token? And I think reading one line each time is less efficient, am I right? Regards, xiaojf From bonono at gmail.com Wed Nov 23 22:51:16 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 19:51:16 -0800 Subject: (newbie) N-uples from list of lists In-Reply-To: <1h6huuv.3o2ah01wodl9qN%aleax@mail.comcast.net> References: <1132776015.567869.214570@g14g2000cwa.googlegroups.com> <1132799696.603772.323700@g44g2000cwa.googlegroups.com> <1132801693.407770.215630@g43g2000cwa.googlegroups.com> <1h6huuv.3o2ah01wodl9qN%aleax@mail.comcast.net> Message-ID: <1132804276.718930.221680@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > bonono at gmail.com wrote: > > > Out of curiousity, is "recursion" the desirable way(or is it pythonic > > way) ? How would one do it in the imperative way ? > > For an inherently recursive problem (as this one appears to be), the > traditional alternative to recursion is maintaining your own LIFO stack. > If (with all the obvious refactorings) things gets messy, ah well, at > least you've broken free of the recursion limit;-). [[ Sometimes > (rarely) things don't get messy, and then you find out that the problem > wasn't really "inherently recursive";-) ]] > > An example of recursion elimination in Python can be found at > > Thanks, so it seems that it is only doing the "stacking" oneself rather than relies on the recursive calls(which does the stack for you). Or in other worlds, a way to get around the recursion limitation but seems to be harder to understand in this case. From aum at spam.me.please Sun Nov 13 06:13:00 2005 From: aum at spam.me.please (aum) Date: Mon, 14 Nov 2005 00:13:00 +1300 Subject: Want to perform unattended installation of SW using python References: <1131879424.943510.320180@g47g2000cwa.googlegroups.com> Message-ID: On Sun, 13 Nov 2005 02:57:04 -0800, 28tommy wrote: > Hi, > > I'm trying to automate an installation of some SW that is installed on > Windows (you know - 'Start' ==> 'Next' ==> 'Next' ==> 'Finish' kind of > installation). Is ther any way to perform that using python? Quick answer is yes, very much so. What /can't/ you do in python? :) I presume that by 'start -> next -> next' you're referring to 'installation wizards'. You can write those in python, using any of the available GUI programming libraries, such as Tkinter, wxPython, PyFLTK, FoxPY, PyQt or whatever appeals. PyFLTK and wxPython have Wizard widgets built in, and quite likely PyQt does as well. -- Cheers aum From steve at REMOVETHIScyber.com.au Fri Nov 11 23:33:35 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 12 Nov 2005 15:33:35 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> Message-ID: On Fri, 11 Nov 2005 11:17:43 -0500, Mike Meyer wrote: >> I'd just like to make it non-trivial to make or use additional copies. > > How do you do that without infringing my fair use rights? And that is the million dollar question. So-called "intellectual property" is a government-granted monopoly which is not based on any principle of ownership. Ideas are not something you can own in any real sense (as opposed to the legal fiction), ideas are something that you can *have* -- but having had an idea, you can't naturally prevent others from having the same idea independently, or making use of your idea if you tell them about it -- and should you tell them your idea so that now they have it as well, that does not diminish the fact that you also have that idea. Given the absolute lack of real evidence that strong "intellectual property" laws are good for either innovation or the economy, and given the absolute artificiality of treating ideas as if they were scarce goods, I don't understand why the artificial monopoly rights of copyright holders are allowed to trump the natural rights of copyright users. -- Steven. From onurb at xiludom.gro Fri Nov 18 11:31:52 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 18 Nov 2005 17:31:52 +0100 Subject: Zope vs Php In-Reply-To: <1132270188.226770.309980@g14g2000cwa.googlegroups.com> References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> Message-ID: <437e01fa$0$19890$626a54ce@news.free.fr> Steve wrote: > I am going to go the mod_python route. > > as for why a person would go route one over route 2 > > is that the number of lines of html/output vs python code are usually > 10 to 1 and it's much easier to encapsulate the python code than to > quote and escape all the html/css/xml > > > <% > #python code > %> > some title > > and > > print output(python-code) + " some title". > > are equivalent. Yes, but this was *not* what I suggested. There are a lot of HTML templating languages for Python, some being more or less PHP-like (PSP, Cheetah, ...), some being way more presentation-oriented (TAL, Kid, ...). I prefer the second category. I share your opinion about html in code, but I also dislike code in html... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gdamjan at gmail.com Fri Nov 11 14:03:36 2005 From: gdamjan at gmail.com (Damjan) Date: Fri, 11 Nov 2005 20:03:36 +0100 Subject: mod_python web-dav management system Message-ID: Apache2 comes with builtin Web-dav support, but authorization is limited to Apache's methods, which are not very flexible. Now I've been thinking that it might be pretty easy to implement a authorization layer with mod_python (but living handling of the web-dav protocol to apache)... So, has anyone already done something similar? A management web-ui would be nice too. -- damjan From peter at engcorp.com Wed Nov 23 20:52:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Nov 2005 20:52:04 -0500 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > Ok, the answer is easy: For historical reasons - built-in sets exist > only since Python 2.4. > > Anyway, I was thinking about whether it would be possible and desirable > to change the old behavior in future Python versions and let dict.keys() > and dict.values() both return sets instead of lists. Definitely not. I believe it's currently guaranteed that the order of the items in dict.keys() and dict.values() will match (i.e. the index of any key in its list will be the same as the index of the corresponding value in its list). This property is almost certainly used in some code, so it can't be broken without good reason. -Peter From sylvain.thenault at logilab.fr Mon Nov 7 10:12:05 2005 From: sylvain.thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Mon, 7 Nov 2005 16:12:05 +0100 Subject: [ANN] ASTNG 0.13.1 Message-ID: <20051107151204.GB24171@crater.logilab.fr> Hi there ! I'm pleased to announce a new bug fix release of ASTNG. This release fixes a lot of bugs detected by pylint users, the most popular application built on top of this package. What's new ? ------------ * fix bug on building from living module the same object in encountered more than once time (eg builtins.object) (close #10069) * fix bug in Class.ancestors() regarding inner classes (close #10072) * fix .self_resolve() on From and Module nodes to handle package precedence over module (close #10066) * locals dict for package contains __path__ definition (close #10065) * astng provide GenExpr and GenExprFor nodes with python >= 2.4 (close #10063) * fix python2.2 compatibility (close #9922) * link .__contains__ to .has_key on scoped node to speed up execution * remove no more necessary .module_object() method on From and Module nodes * normalize parser.ParserError to SyntaxError with python 2.2 What is ASTNG ------------- The aim of this module is to provide a common base representation of python source code for projects such as pychecker, pyreverse, pylint... Well, actually the development of this library is essentialy governed by pylint's needs. It extends class defined in the compiler.ast [1] module with some additional methods and attributes. Instance attributes are added by a builder object, which can either generate extended ast (let's call them astng ;) by visiting an existant ast tree or by inspecting living object. Methods are added by monkey patching ast classes. Home page --------- http://www.logilab.org/projects/astng Download -------- ftp://ftp.logilab.org/pub/astng 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! -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From petantik.fool at gmail.com Wed Nov 9 13:16:43 2005 From: petantik.fool at gmail.com (petantik) Date: 9 Nov 2005 10:16:43 -0800 Subject: Python obfuscation Message-ID: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> Are there any commercial, or otherwise obfuscators for python source code or byte code and what are their relative advantages or disadvantages. I wonder because there are some byte code protection available for java and .NET, although from what i've read these seem to be not comprehensive as protection schemes http://petantik.blogsome.com - Telling it like it is From robert.h.boyd at gmail.com Tue Nov 1 15:54:58 2005 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Tue, 1 Nov 2005 15:54:58 -0500 Subject: Object-Relational Mapping API for Python In-Reply-To: <1130872943.306455.129550@g47g2000cwa.googlegroups.com> References: <1130872943.306455.129550@g47g2000cwa.googlegroups.com> Message-ID: On 1 Nov 2005 11:22:23 -0800, Aquarius wrote: > > I explored Java's Hibernate a bit and I was intrigued by how you can > map entity objects to database tables, preserving all the relations and > constraits. I am interested if there is something like this for Python > - I noticed some APIs in the "Cheeseshop", but most of them were alpha, > better, or seemed to be forsaken a long time ago. Can you recommend me > anything? > In addition to SQLObject, there is Modeling, axiom, whatever Django is using, and more. Can't comment on any, though, as I have not used them. Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Sun Nov 20 21:40:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Nov 2005 21:40:19 -0500 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132531775.399671.93120@o13g2000cwo.googlegroups.com> References: <1132531775.399671.93120@o13g2000cwo.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Using the same logic, we don't need types other than string in a DBMS > as we can always convert a string field into some other types when it > is needed. You mean, like SQLite does? (http://www.sqlite.org/datatypes.html) -Peter From aleax at mail.comcast.net Tue Nov 8 22:28:36 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 8 Nov 2005 19:28:36 -0800 Subject: Storing empties References: <1130539752.667045.183460@g14g2000cwa.googlegroups.com> <1130638902.048806.183580@g43g2000cwa.googlegroups.com> <1130647542.669549.300360@g43g2000cwa.googlegroups.com> <1h57spy.bpig8y1g0rvzfN%aleaxit@yahoo.com> <1130650215.537552.231990@g49g2000cwa.googlegroups.com> <1h58k4p.12xd7rj1t5peh0N%aleaxit@yahoo.com> <1h5bepj.q0sqsnbqqgjrN%aleax@mail.comcast.net> <1h5d3k0.32mnkz17x2xh6N%aleax@mail.comcast.net> Message-ID: <1h5q338.dzx76si94rwcN%aleax@mail.comcast.net> Aahz wrote: ... > >For pickling, object() as a unique "nothing here, NOT EVEN a None" > >marker (AKA sentinel) works fine. > > How does that work? Maybe I'm missing something obvious. > > sentinel = object() > class C: > def __init__(self, foo=sentinel): > self.foo = foo > def process(self): > if self.foo is not sentinel: > .... > > Now, the way I understand this, when your application restarts and an > instance of C is read from a pickle, your sentinel is going to be a > different instance of object() and process() will no longer work > correctly. Are you suggesting that you need to pickle the sentinel with > the instance? Or is there some other trick I'm missing? Yes, I'd set self.sentinel=sentinel (and test wrt that) -- while in the abstract it would be better to set sentinel at class level, since classes are only pickled "by name" that wouldn't work. If you don't need the absolute ability to pass ANY argument to C(), there are of course all sorts of workaround to save some small amount of memory -- any object that's unique and you never need to pass can play the same role as a sentinel, obviously. Alex From fredrik at pythonware.com Fri Nov 11 17:23:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 23:23:34 +0100 Subject: about widget construction kit References: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com> <1d987df30511111400m19f02d25had206df638c1bc0a@mail.gmail.com> Message-ID: Shi Mu wrote: > > > I tried to install WCK(Widget Construction Kit (WCK)): > > > > > > C:\Python23>python tkinter3000-1.0-20031212\setup.py install > > > Traceback (most recent call last): > > > File "tkinter3000-1.0-20031212\setup.py", line 23, in ? > > > WCK_VERSION = setuplib.find_version("WCK/__init__.py") > > > File "C:\wget2\tkinter3000-1.0-20031212\setuplib.py", line 74, in find_version > > > for line in open(filename).readlines(): > > > IOError: [Errno 2] No such file or directory: 'WCK/__init__.py' > > > > > > I checked my files and found there is a __init__.py and got confused > > > why the error came out? > > > > if you're using windows, please use a prebuilt version of the WCK. > > > > I also recommend using the 1.1b1 release; it's a lot better than 1.0. > > > > if you really want to build it yourself, and you have the right compilers > > and all Tcl/Tk build files in the right places, change to the source directory > > before running the setup script. > if I run python command, I need to go > to the directory where python is installed, so how can I change to the > source directory at the same time? you're 100% sure that you have a working compiler and the right Tcl/Tk build files in the right place, but you don't know how to run an executable from another directory? hmm. here are three ways: 1. pass in the full path to the executable: cd tkinter3000-1.0-20031212 c:\python23\python setup.py install 2. add the python installation directory to the path. random google link: http://www.computerhope.com/issues/ch000549.htm when you've updated the environment, open up a new command window, and do cd tkinter3000-1.0-20031212 python setup.py install 3. if you used a python.org installer, it's likely that you can run the setup.py file directly: cd tkinter3000-1.0-20031212 setup.py install From who2guess at xs4all.nl Thu Nov 3 03:46:26 2005 From: who2guess at xs4all.nl (W.H.Offenbach) Date: Thu, 3 Nov 2005 09:46:26 +0100 Subject: Microsoft Hatred FAQ In-Reply-To: References: <1129826863.422951.146970@g49g2000cwa.googlegroups.com> <5l1rl1dt2vj6lanvbfue4pglv1kkgl1qn9@4ax.com> <11lsopl4qpg9gc2@corp.supernews.com> Message-ID: <2c3d0cb82096c974bac5b056aebe0f67@xs4all.nl> John W. Kennedy wrote: > IBM was genuinely innovative, and did their best to provide value for > money. Microsoft hasn't been able to produce anything but me-too > products since the 80's. (Multiplan, Word for DOS, the QBASIC engine, > early sponsorship of mouses, and the gutsy decision to morph MS-DOS > 1.0, > a CP/M quasi-clone, into DOS 2.0, a Unix quasi-clone, are about all I > can give them credit for.) You're suggesting MS stands for 'Mimick or Steal', right? From pinard at iro.umontreal.ca Fri Nov 11 09:41:40 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 11 Nov 2005 09:41:40 -0500 Subject: modify dictionary while iterating In-Reply-To: <1131695154.274238.113690@f14g2000cwb.googlegroups.com> References: <1131695154.274238.113690@f14g2000cwb.googlegroups.com> Message-ID: <20051111144140.GA7238@phenix.sram.qc.ca> [s99999999s2003 at yahoo.com] >I wish to pop/del some items out of dictionary while iterating over it. >a = { 'a':1, 'b':2 } >for k, v in a.iteritems(): > if v==2: > del a[k] A simple change would be using "items()" instead of "iteritems()". Or else, you may prefer to loop over keys, and retrieve values, either: for k in a.keys(): if a[k] == 2: del a[k] or: for k in set(a): if a[k] == 2: del a[k] But in no way, you may directly iterate over the original dictionary while altering its keys, this is explicitly forbidden in Python. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From petr at tpc.cz Sat Nov 12 09:10:35 2005 From: petr at tpc.cz (Petr Jakes) Date: 12 Nov 2005 06:10:35 -0800 Subject: convert string to the "escaped string" In-Reply-To: <1131804252.578525.312490@g43g2000cwa.googlegroups.com> References: <1131804252.578525.312490@g43g2000cwa.googlegroups.com> Message-ID: <1131804635.225141.57380@g49g2000cwa.googlegroups.com> small mistake in my previous posting, sorry!!!! from "0xf" I need "\xf" of course and mentioned code gives me "\0xf" of course. Thanks for your postings Petr Jakes From y.glodt at sitasoftware.lu Wed Nov 9 10:00:18 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 09 Nov 2005 16:00:18 +0100 Subject: append to non-existing list In-Reply-To: <1131544961.869354.70080@g49g2000cwa.googlegroups.com> References: <1131544961.869354.70080@g49g2000cwa.googlegroups.com> Message-ID: <43720F02.2090300@sitasoftware.lu> bonono at gmail.com wrote: > Thomas Bellman wrote: >> The next time you go shopping at your local super-market, do >> *not* get a shopping-cart (or shopping-basket, or any similar >> container). As you pick up the things you want to buy, try >> to put them into the non-existing cart. Perhaps you will then >> become enlightened. > > But in PHP(and I believe Perl), it is more like : > > "oops, I need a cart. Hello, I need a cart here, please" and > magically, someone wheel you a cart which you can put your stuff in. > The "@" is the magic calls for service. So as a customer, this sounds > like better service but that will create problems to the super market > as it need extra staff for this service and the environment is noiser, > that is another story. > :-) I will never mention any p-language except python in this list anymore... From mwm at mired.org Thu Nov 17 23:48:24 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Nov 2005 23:48:24 -0500 Subject: Zope vs Php References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> <86br0in877.fsf@bhuda.mired.org> <87hdaa3brc.fsf@jupiter.g2ctech> <86oe4iljz4.fsf@bhuda.mired.org> <878xvm39mt.fsf@jupiter.g2ctech> Message-ID: <867jb6lfxj.fsf@bhuda.mired.org> Jorge Godoy writes: >> While I'm at it - how does KID do for things that aren't HTML? >> Cheetah integrates with web servers, but can be used to generate >> nearly anything. I've found that using Cheetah scripts to build >> Makefiles that run Cheetah scripts to build a dynamically determinedj >> set of pages to be pretty handy. > Kid is for XML output. It won't work with non-HTML output... >> And finally - got a URL? > http://kid.lesscode.org/ ;-) Thanks. It looks pretty spiffy. I like the idea of incorporating the templating system into the document via the py:* attributes. Unfortunately, my tools don't - which is another one of the things I like about Cheetah: it doesn't interfere with my X/HTML tools. For instance, I edit attributes by asking the editor to let me edit the current tags attributes. It opens window with a list of valid attributes, along with type information about those attributes. I edit the list, close the window, and it inserts the required attributes, appropriately quoted, into the tag. I couldn't use that for py:* attributes without tweaking the DTD for each language I wanted to edit. Similar problems crop up with the other features that depend on information from the DTD. Thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From timr at probo.com Tue Nov 29 02:52:39 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 29 Nov 2005 07:52:39 GMT Subject: Newbie question: Tab key giving different output References: <1133155539.865554.216610@g14g2000cwa.googlegroups.com> Message-ID: getkaizer at gmail.com wrote: > >While in the interactive mode, i need to use the tab key to indent my >code. However, i get a message "List all 174 possibilities? (Y/N)" >instead of an indent. So i use spaces. > >How do i tell python to give me indents? You know, the number of spaces you use is not important. You can use one space for your indentation, which is the same number of keystrokes as a tab. Good looking code is not of prime importance when you're typing at the Python prompt. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From falcon3166 at hotmail.com Tue Nov 15 19:16:14 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 15 Nov 2005 17:16:14 -0700 Subject: Can anyone tell me if pygame and Tkinter can work together? Message-ID: <437a718e$0$20301$88260bb3@news.atlantisnews.com> Hi, Can anyone tell me if pygame and Tkinter can work together in the same application? I thought I'd better ask before trying it, since both use widgets. Thanks, Nathan Pinno -- For great sites go to: http://www.the-web-surfers-store.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty -- ............................................................. > Posted thru AtlantisNews - Explore EVERY Newsgroup < > http://www.AtlantisNews.com -- Lightning Fast!!! < > Access the Most Content * No Limits * Best Service < From carsten at uniqsys.com Mon Nov 21 00:33:53 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 21 Nov 2005 00:33:53 -0500 Subject: [ANN] Python API InformixDB-2.1 released Message-ID: <20051121051235.M439@uniqsys.com> Hi everybody: I am proud to announce a new release of InformixDB, the IBM Informix implementation of the Python DB API. This release adds the following new features: * Scroll cursors and cursors with hold * Support for INTERVAL types * Support for Smart Large Objects * Support for User Defined Types Downloads and more info at http://informixdb.sourceforge.net/ Enjoy, Carsten Haese. From fuzzyman at gmail.com Fri Nov 25 03:41:36 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Nov 2005 00:41:36 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <1132838525.174480.93550@g47g2000cwa.googlegroups.com> Message-ID: <1132908096.814076.109200@z14g2000cwz.googlegroups.com> Sure - that was just an example of mutating the keys list without having direct access to it. If keys was implemented as an object (with a ``__call__`` method) then we could also implement sequence methods on it - making it easier to mutate the keys/values/items directly. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From robert.kern at gmail.com Wed Nov 9 17:39:31 2005 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 Nov 2005 14:39:31 -0800 Subject: overloading *something In-Reply-To: <200511091251.37022.jstroud@mbi.ucla.edu> References: <200511082138.12495.jstroud@mbi.ucla.edu> <200511091251.37022.jstroud@mbi.ucla.edu> Message-ID: James Stroud wrote: > That **kwargs insists on using the C-side interface is precisely the annoyance > to which I am referring. I should be able to write a dictionary-like > interface in python and **kwargs should in turn be able to use it. If the > retort is that the C-side interface is used for performance, my retort to the > retort is that an isinstance() is already being called somewhere, so no > additional tests would need to be made to make **kwargs more generalized. Well, the test is in Python/ceval.c (grep for the error message) and the function that needs a bona fide dictionary is PyObject_Call in Objects/abstract.c . If you can work up a patch, Guido will probably consider it although I would suggest searching python-dev for previous discussions first. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From eric.nieuwland at xs4all.nl Thu Nov 3 11:55:54 2005 From: eric.nieuwland at xs4all.nl (Eric Nieuwland) Date: Thu, 3 Nov 2005 17:55:54 +0100 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: Steven D'Aprano wrote: > On Thu, 03 Nov 2005 15:13:52 +0100, Eric Nieuwland wrote: >> 2 When an instance of the class is created, what effectively happens >> is >> that a shallow copy of the class object is made. >> Simple values and object references are copied. > > No. > > py> class Parrot: > ... var = 0 > ... > py> p = Parrot() > py> Parrot.var is p.var > True > py> Parrot.var = {"Hello world": [0, 1, 2]} > py> Parrot.var is p.var > True > > It all boils down to inheritance. When Python does a look up of an > attribute, it looks for an instance attribute first (effectively trying > instance.__dict__['name']). If that fails, it looks up the class second > with instance.__class__.__dict__['name'], and if that fails it goes > into a > more complex search path looking up any superclasses (if any). Note my use of "effectively" and "shallow copy". Your example demonstrates how Python postpones the shallow copy until you tell the object to differ from the class/ The examples used only use a class an an instance thereof. They are valid without inheritance. >> This explains: >> - why methods and complex objects (e.g. lists) are shared among >> instances of a class and the class itself >> - simple values are not shared > > No. it is all about the inheritance, and mutable/immutable objects. NO. You're referring to the implemented mechanism. Other implementations with the same semantics are possible. From robert.kern at gmail.com Fri Nov 11 22:57:27 2005 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 11 Nov 2005 19:57:27 -0800 Subject: Hash map with multiple keys per value ? In-Reply-To: References: Message-ID: Chris Stiles wrote: > Hi -- > > I'm working on something that includes the concept of multiple aliases for a > particular object, where a lookup for any of the aliases has to return all the > others. The hack way of doing this was to have a dictionary where each > entry consisted of a list of all the aliases - with multiple references to the > same list from the various dictionary entries corresponding to each alias. > > Is there an easier and cleaner way of doing this ? Is there example code > floating around that I might have a look at ? It's what everybody else does. You may want to use sets instead of lists, but otherwise I think your approach is pretty standard. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bokr at oz.net Sat Nov 12 17:41:19 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 12 Nov 2005 22:41:19 GMT Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> Message-ID: <43766e46.327300252@news.oz.net> On Sat, 12 Nov 2005 16:52:12 -0500, Mike Meyer wrote: [...] >Personally, I think that the LISP quote mechanism would be a better >addition as a new syntax, as it would handle needs that have caused a >number of different proposals to be raised. It would require that >symbol know about the internals of the implementation so that ?name >and symbol("name") return the same object, and possibly exposing said >object to the programmer. And this is why the distinction about how >LISP acts is important. I wonder if the backquote could be deprecated and repurposed. It could typographically serve nicely as a lisp quote then. But in python, how would 'whatever be different from lambda:whatever ? (where of course whatever could be any expression parenthesized as necessary) Regards, Bengt Richter From lycka at carmen.se Mon Nov 7 12:44:46 2005 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 07 Nov 2005 18:44:46 +0100 Subject: how to present Python's OO feature in design? In-Reply-To: <1131332809.044523.169900@o13g2000cwo.googlegroups.com> References: <1131332809.044523.169900@o13g2000cwo.googlegroups.com> Message-ID: pcmanlin wrote: > As I know java has many UML tools to design for its OO feature, is > there any tools or good concept for Python project Modeling? My favourite is whiteboard and digital camera. I don't generate any code from that though... ;) It's the approach suggested in Scott Ambler's "Agile Modeling", and I think it's just just the right approach. Don't forget a good set of automated tests. We use TextTest, but ymmv. It fits our type of applications. From greg at cosc.canterbury.ac.nz Tue Nov 29 18:13:14 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 30 Nov 2005 12:13:14 +1300 Subject: ncurses' Dark Devilry In-Reply-To: References: <*firstname*nlsnews-8F0080.15501829112005@news.verizon.net> Message-ID: <3v45kcF13nn20U1@individual.net> Christopher Subich wrote: > Why not wrap your 1-3 in a function of your own? It sounds like the OP is concerned about the visual effect of the cursor moving on the screen while characters are written. I doubt whether curses provides any way of controlling that. Curses was designed for glass ttys, on most of which it is physically impossible to write characters without the cursor moving. The best you can do is move it back to where you want it afterwards. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aleax at mail.comcast.net Thu Nov 3 10:24:14 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 07:24:14 -0800 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> Message-ID: <1h5fvt8.13txob319lth9aN%aleax@mail.comcast.net> Stuart Turner wrote: ... > "Python is a scripting language like Perl, awk, tcl, Java etc... it is > not quite a fully developed OO language, but does support some OO that Perl > doesn't. To be clear, these scripting languages have their place in our > environment, but they are not full replacements for C#, Java, C, etc... Java is not a full replacement for Java? Note that Java was placed in both lists. It makes sense in the first one because the typical implementations of Java and Python are very similar: compilation to bytecode, execution of the bytecode by a virtual machine (Python is slightly handier because it does the compilation automatically for you if you haven't done it beforehand, but that's a secondary issue). There are also many direct similarities between the languages' semantics (immutable strings, assignment by "object reference"), as well, of course, as many differences. I suspect there's a meaning-changing typo here and what was meant was not Java but Javascript, in the first sentence. > because they do not come with the full range of libraries e.g GDI This assertion is simply absurd. The archetypal example of a language which does emphatically NOT "COME WITH" a full range of libraries is C, which only comes with a pitifully weak "standard library" -- that doesn't matter much because you can easily download and use lots of libraries that do not "come with" the language as such. For example, GDI is a library that comes with Windows, and you can easily use it from C -- and, of course, Python (for one of many ways to do the latter, see http://jotsite.com/blogArchives/cat_python_programming.php under entry "Using Ctypes to access Windows API"). > Perl. Python is object orientated, but I do not know what implementation? There are many implementations of the Python language. If you like Java's implementation best, for example, you can download Jython and run it on a JVM: then, the implementation will be whatever the JVM supplies (Jython compiles Python sources into .class files, using JVM bytecode). > Essentially any language with a pointer can claim to be OO, although Python > does market itself on OO capabilities. Do you know what implementation > they have used? The best abstract description, funny enough, can be found in a book written quite independently from Python -- "Putting Metaclasses to Work" -- shorn of the static-typing aspects. Python developed a very similar (but dynamically typed) object model quite independenty from that book's authors; lately, some metaclass characteristics were inspired by it (but Python values simplicity, so for example it doesn't autoresolve metaclass conflicts -- you'll find a recipe to do that easily as the very last one of the 2nd edition of O'Reilly's Python Cookbook). > Lets discuss, as I am not a great fan of Perl and if Python is more > structured then it is possibly worth promoting." For completeness, one should probably also consider Ruby as "more thoroughly object-oriented"; unfortunately, the implementation may be more problematic there -- the standard one is slower and there are fewer choices. Ruby's object model is much more similar to Smalltalk's or Objective C's (shorn of static typing in the latter case, again). Another variant worth looking at is Boo -- only implemented for dotNet (but then, if C# is also being considered, that apparently doesn't matter) and based on type inference, with several similarities to Python (I have no experience of Boo since Mono's installations on MacOSX haven't worked well for me, but on paper it looks nice). Alex From mwm at mired.org Thu Nov 17 22:21:03 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Nov 2005 22:21:03 -0500 Subject: Zope vs Php References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> <86br0in877.fsf@bhuda.mired.org> <87hdaa3brc.fsf@jupiter.g2ctech> Message-ID: <86oe4iljz4.fsf@bhuda.mired.org> Jorge Godoy writes: > Mike Meyer writes: >> That said, I have to confess that lately I've been using Cheetah >> templates, because the syntax for inserting values is simpler, and the >> way Cheetah templates work naturally in the Python inheritance >> hierarchy. > KID is also nice and can be used as he wants and in a cleaner way as well. ;-) Since you didn't provide a URL, and KID is a pretty generic term to google for, I'll just ask: One of the things I really like about Cheetah - at least compared to other templating systems I've looked at - is that it's fully cooperative with the Python inheritance sydstem. A cheetah template can inherit from a python class, or a cheetah template, and a Python class can inherit from a cheetah template. This brings the full power of OO programming facilities to the templating system, and is simply blows away other templating systems, or trying to build that kind of flexibilty using "pure python". Does KID have have that kind of facility? While I'm at it - how does KID do for things that aren't HTML? Cheetah integrates with web servers, but can be used to generate nearly anything. I've found that using Cheetah scripts to build Makefiles that run Cheetah scripts to build a dynamically determinedj set of pages to be pretty handy. And finally - got a URL? thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From correia_jREMOVECAPS at hotmail.com Mon Nov 14 20:22:31 2005 From: correia_jREMOVECAPS at hotmail.com (J Correia) Date: Tue, 15 Nov 2005 01:22:31 GMT Subject: how to start a process and get it's pid? References: <43745C93.70907@sitasoftware.lu> <1131713940.819881.6320@g43g2000cwa.googlegroups.com> Message-ID: "Peter Hansen" wrote in message news:rfSdnS_tldxq1-jeRVn-jA at powergate.ca... > Fredrik Lundh wrote: > > Daniel Crespo wrote: > >>>>>>os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") > >>>1944 > >> > >>I don't get the correct PID. > >> > >>When I do os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") > >>I get 168 (for example), while in the tasklist appears notepad.exe with > >>the 2476 PID. > > > > not sure, but the return value looks like a PID, so maybe you're seeing the > > PID for the cmd.exe instance used to run the program. or something. > > I believe it's documented here > http://docs.python.org/lib/os-process.html that the return value is not > the PID but the "process handle". I believe this can be converted to > the PID with a convenient pywin32 call though at the moment I can't > recall which. Googling quickly suggests that > win32process.GetWindowThreadProcessId(handle) will do the trick (the > second item returned is the PID), but I'm fairly sure there's a simpler > approach if you keep looking. I recall there being a Cookbook recipe > related to this too.... > > -Peter Yep... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462 From eternalsquire at comcast.net Thu Nov 10 12:34:18 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 10 Nov 2005 09:34:18 -0800 Subject: Python obfuscation In-Reply-To: References: <1131564878.074210.74640@z14g2000cwz.googlegroups.com> <1131600579.626993.146040@g47g2000cwa.googlegroups.com> Message-ID: <1131644058.218095.47740@o13g2000cwo.googlegroups.com> Come on! I was only just trying to accomodate the OP with a plausible method to fit his business model, based on techniques passed on to me by my various teachers at school and my senseis at workplaces.. Please don't judge me for attempting to pass on experience. It's his choice. While I'd like to figure out myself a nice software package to write and market and earn a good living now that I've walked away from the rat race, I can also see myself having humanity as my client (the FOSS model). The Eternal Squire From dsiroky at email.cz Wed Nov 30 04:23:00 2005 From: dsiroky at email.cz (David Siroky) Date: Wed, 30 Nov 2005 10:23:00 +0100 Subject: unicode speed References: <6SVif.6506$ea6.3923@news-server.bigpond.net.au> Message-ID: V Tue, 29 Nov 2005 10:14:26 +0000, Neil Hodgson napsal(a): > David Siroky: > >> output = '' > > I suspect you really want "output = u''" here. > >> for c in line: >> if not unicodedata.combining(c): >> output += c > > This is creating as many as 50000 new string objects of increasing > size. To build large strings, some common faster techniques are to > either create a list of characters and then use join on the list or use > a cStringIO to accumulate the characters. That is the answer I wanted, now I'm finally enlightened! :-) > > This is about 10 times faster for me: > > def no_diacritics(line): > if type(line) != unicode: > line = unicode(line, 'utf-8') > > line = unicodedata.normalize('NFKD', line) > > output = [] > for c in line: > if not unicodedata.combining(c): > output.append(c) > return u''.join(output) > > Neil Thanx! David From fredrik at pythonware.com Tue Nov 1 15:08:30 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 1 Nov 2005 21:08:30 +0100 Subject: Python's website does a great disservice to the language References: <1130873528.812783.75600@g43g2000cwa.googlegroups.com> Message-ID: svenn.are at bjerkem.de wrote: > So the first thing you do when you go to a web page is to google if > they are going to redesign it? the first thing he did was to go to the page, the next thing he did was to post a "can we round up a couple of designers?" message with an in- flammatory subject line. that algorithm is rather simplistic, and can be greatly improved by inserting a "let's check google" clause at the right place. (and yes, making your boss look stupid is never a good idea) From codecraig at gmail.com Tue Nov 8 10:25:10 2005 From: codecraig at gmail.com (py) Date: 8 Nov 2005 07:25:10 -0800 Subject: XML GUI In-Reply-To: <1131463371.733530.105870@o13g2000cwo.googlegroups.com> References: <1131457704.275657.237970@g49g2000cwa.googlegroups.com> <1131461186.068052.81270@g14g2000cwa.googlegroups.com> <1131461562.995828.141580@g49g2000cwa.googlegroups.com> <1131461919.243378.231750@g43g2000cwa.googlegroups.com> <1131463371.733530.105870@o13g2000cwo.googlegroups.com> Message-ID: <1131463510.102041.258910@g49g2000cwa.googlegroups.com> wxPython sounds like it might be the ticket...especially with the XRC files. I plan on defining the GUI via XML, and actions in my python app. Thanks From godoy at ieee.org Thu Nov 17 21:55:51 2005 From: godoy at ieee.org (Jorge Godoy) Date: 18 Nov 2005 00:55:51 -0200 Subject: Zope vs Php References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> <86br0in877.fsf@bhuda.mired.org> Message-ID: <87hdaa3brc.fsf@jupiter.g2ctech> Mike Meyer writes: > That said, I have to confess that lately I've been using Cheetah > templates, because the syntax for inserting values is simpler, and the > way Cheetah templates work naturally in the Python inheritance > hierarchy. KID is also nice and can be used as he wants and in a cleaner way as well. ;-) It suits both worlds. -- Jorge Godoy From kylotan at gmail.com Wed Nov 16 05:34:23 2005 From: kylotan at gmail.com (Ben Sizer) Date: 16 Nov 2005 02:34:23 -0800 Subject: Proposal for adding symbols within Python In-Reply-To: <11njtue1d4kdi06@corp.supernews.com> References: <43762d68$0$4335$626a54ce@news.free.fr> <11ni1sddrhsm03d@corp.supernews.com> <1132048673.702127.307450@g47g2000cwa.googlegroups.com> <11njtue1d4kdi06@corp.supernews.com> Message-ID: <1132137263.612545.155970@z14g2000cwz.googlegroups.com> Grant Edwards wrote: > On 2005-11-15, Ben Sizer wrote: > > > > myObject.value = 'value1' > > > > #... 100 lines of code elided... > > > > if myObject.value == 'Value1': > > do_right_thing() > > else: > > do_wrong_thing() > > > > I don't actually think string use is 'untenable', but it is > > definitely more error-prone. With some sort of named object on > > the right hand side you will at least get a helpful NameError. > > I don't see how that's an argument in favor of the proposal > being discussed. Aren't $Value1 and $value1 both legal and > distinct symbols in the proposed syntax? Won't you have the > exact same issue that you do with mis-typing strings? I think the idea is that if the symbol hasn't been instantiated locally in an assignment operation, then it will not exist, and "if foo == $symbolName" will either raise a NameError or flag some error during compilation. It cannot do this with string comparisons. I expect this would require a 2-pass compilation process, the first pass spotting all references to symbols and instantiating them appropriately, the second pass resolving these references and noting any that did not match up. -- Ben Sizer From mwm at mired.org Thu Nov 17 23:34:22 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Nov 2005 23:34:22 -0500 Subject: install python2.4 on FreeBSD and keep using python2.3 References: <130df1930511170322n6b001072j@mail.gmail.com> <437D0840.3090004@bullseye.apana.org.au> Message-ID: <86br0ilgkx.fsf@bhuda.mired.org> Xiao Jianfeng writes: > Can I install python2.4.2 and keep using python2.4.1 on IRIX? Yes, but you'll have to install it with a different prefix. Use the --prefix flag to configure when you install it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From oren.tirosh at gmail.com Mon Nov 14 10:00:20 2005 From: oren.tirosh at gmail.com (Oren Tirosh) Date: 14 Nov 2005 07:00:20 -0800 Subject: Inserting Records into SQL Server - is there a faster interface than ADO References: <1131724751.606322.162110@g44g2000cwa.googlegroups.com> <1131976921.982178.210260@g43g2000cwa.googlegroups.com> Message-ID: <1131980420.412584.68750@g47g2000cwa.googlegroups.com> > We are using the stored procedure to do a If Exist, update, else Insert processing for > each record. Consider loading the data in batches into a temporary table and then use a single insert statement to insert new records and a single update statement to update existing ones. This way, you are not forcing the database to do it one by one and give it a chance to aggressively optimize your queries and update the indexes in bulk. You'd be surprized at the difference this can make! From bonono at gmail.com Tue Nov 29 02:04:24 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 28 Nov 2005 23:04:24 -0800 Subject: Death to tuples! In-Reply-To: References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> Message-ID: <1133247864.898833.244180@g49g2000cwa.googlegroups.com> Rikard Bosnjakovic wrote: > Steven Bethard wrote: > > > [1]http://www.python.org/dev/summary/2005-09-01_2005-09-15.html#string-formatting-in-python-3-0 > > Reading this link, I find this: > > "Currently, using % for string formatting has a number of inconvenient > consequences: > > * precedence issues: "a%sa" % "b"*4 produces 'abaabaabaaba', not > 'abbbba' " [...] > > > Testing it locally: > > >>> "a%sa" % "b"*4 > 'abaabaabaaba' > > But "b"*4 is not a tuple, as the formatting arguments are supposed to be, > so why blame its erronious behaviour? > > Works fine this way: > > >>> "a%sa" % ("b"*4,) > 'abbbba' > > So I really do not see the problem. For my own format-strings, I always > add a final comma to make sure it's a tuple I'm using. > > Just my $0.02. > this doesn't look like a tuple issue, but precedence of the operator. "a%sa" % ("b"*4) also gives the expected answer. "abbbba" From t.liesner at creativ-consulting.de Tue Nov 29 12:40:08 2005 From: t.liesner at creativ-consulting.de (Thomas Liesner) Date: Tue, 29 Nov 2005 17:40:08 GMT Subject: newbie question concerning formatted output Message-ID: Hello all, i am having some hard time to format the output of my small script. I am opening a file which containes just a very long string of hexdata seperated by spaces. Using split() i can split this string into single words and print them on stdout. So far so good. But i want to print always three of them in a single line and after that a linebreak. So instead of: 3905 3009 0000 4508 f504 0000 3707 5a07 0000 etc... i'd like to have: 3905 3009 0000 4508 f504 0000 3707 5a07 0000 etc... This is the codesnippet i am using: #!/usr/bin/python import string inp = open("xyplan.nobreaks","r") data = inp.read() for words in data.split(): print words inp.close() Any hints? TIA, ./Tom From vida00 at gmail.com Wed Nov 23 17:18:06 2005 From: vida00 at gmail.com (vida00 at gmail.com) Date: 23 Nov 2005 14:18:06 -0800 Subject: newbie class question In-Reply-To: <1132783589.533488.51460@g44g2000cwa.googlegroups.com> References: <1132783589.533488.51460@g44g2000cwa.googlegroups.com> Message-ID: <1132784286.143394.15740@f14g2000cwb.googlegroups.com> vida00 at gmail.com wrote: > Hi, > I scouted the ng for someone w/ a similar problem and couldn't find > one, so I might be thinking about this probable non-issue in a wrong > way. > > What I am trying to accomplish should be pretty self explanatory when > looking at the following: > > >>> class heh(object): > ... def __init__(self): > ... self.foo='hello' > ... def change(self): > ... self.foo+=' world' > ... def show(self): > ... return self.foo > ... > ... class hih(object): > ... def __init(self): > ... self.foo=heh.foo() > ... def show(self): > ... return self.foo > ... > >>> x=heh() > >>> x.show() > 'hello' > >>> x.change() > >>> x.show() > 'hello world' > >>> y=x.hih() > >>> y.show() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 13, in show > AttributeError: 'hih' object has no attribute 'foo' > > so, how do I reference heh.foo in its current state (i.e. 'hello > world', not 'hello') from hih? > > Thanks, > > -Josh. Sorry folks, this is what I meant: >>> class heh(object): ... def __init__(self): ... self.foo='hello' ... def change(self): ... self.foo+=' world' ... def show(self): ... return self.foo ... ... class hih(object): ... def show(self): ... return heh().foo ... >>> x=heh() >>> print x.hih().show() hello >>> x.change() >>> print x.show() hello world >>> print x.hih().show() hello I want that last one to print 'hello world' Thanks, and sorry for the confusion. From peter at engcorp.com Sun Nov 20 21:35:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 20 Nov 2005 21:35:23 -0500 Subject: path module / class In-Reply-To: References: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> <8u6dnWEcZ6-6AuPeRVn-gg@powergate.ca> Message-ID: Neil Hodgson wrote: >>> There is a cost to the change as there will be two libraries that >>> have to be known to understand code. ... > At that point I was thinking about os.path and path.py. Readers will > encounter code that uses both of these libraries. Okay, granted. I guess this is the same as in any other case of deprecation (e.g. some people still have to work with code that uses apply() or string module methods). > Peter Hansen: >> We've mandated use of path.py internally for all projects because >> we've noticed (especially with non-expert Python programmers... i.e. >> junior and intermediate types, and senior types new to Python) a >> decrease in errors. > > A list of fault reports in this area would be useful evidence. Unfortunately, in an agile group such reports tend not to exist, and in many cases the errors are caught by a partner even as they are created, or by someone refactoring the code a day later. I have only anecdotal evidence, I'm afraid, unless I start digging through past subversion revisions in several projects. -Peter From linuxlah at gmail.com Wed Nov 23 20:36:41 2005 From: linuxlah at gmail.com (Mohammad Jeffry) Date: Thu, 24 Nov 2005 09:36:41 +0800 Subject: Would cgi be the only option if my webhosting doesn't have psp, zpt, cheetah or mod_python? Message-ID: If an webhosting doen't have these feature. Can I install them ? Any experiences on this? I'm assuming that asking the webhosting system admin. to install these framworks in not an option for now. -- And whoever does an atom's weight of evil will see it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Thu Nov 3 15:12:38 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 Nov 2005 12:12:38 -0800 Subject: Burrows-Wheeler (BWT) Algorithm in Python In-Reply-To: References: <1130919309.381711.305450@f14g2000cwb.googlegroups.com> Message-ID: <1131048758.719582.204090@g43g2000cwa.googlegroups.com> Michael J. Fromberger: > I can send you > a Python implementation I wrote, if you like; but if you're interested > in better understanding how the transform works, I would recommend you > try writing your own implementation. I'd like to see it, if you want you can put it somewhere or send it directly. Bye and thank you, bearophile From steve at REMOVETHIScyber.com.au Thu Nov 3 10:59:35 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 02:59:35 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: On Thu, 03 Nov 2005 14:13:13 +0000, Antoon Pardon wrote: > Fine, we have the code: > > b.a += 2 > > We found the class variable, because there is no instance variable, > then why is the class variable not incremented by two now? Because b.a += 2 expands to b.a = b.a + 2. Why would you want b.a = to correspond to b.__class__.a = ? I'm not saying that it couldn't, if that was the model for inheritance you decided to use. I'm asking why would you want it? What is your usage case that demonstrates that your preferred inheritance model is useful? -- Steven. From laurent.pointal at limsi.fr Mon Nov 28 07:34:30 2005 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 28 Nov 2005 13:34:30 +0100 Subject: Writing big XML files where beginning depends on end. In-Reply-To: References: Message-ID: Magnus Lycka wrote: > We're using DOM to create XML files that describes fairly > complex calculations. The XML is structured as a big tree, > where elements in the beginning have values that depend on > other values further down in the tree. Imagine something > like below, but much bigger and much more complex: > > > > 7 > > 2 > 1 > > > > 5 > > > > We have to stick with this XML structure for now. > > In some cases, building up a DOM tree in memory takes up > several GB of RAM, which is a real showstopper. The actual > file is maybe a magnitute smaller than the DOM tree. The > app is using libxml2. It's actually written in C++. Some > library that used much less memory overhead could be > sufficient. > > We've thought of writing a file that looks like this... > > > > 7 > > 2 > 1 > > > > 5 > > > > ...and store {"#": "15", "#1.1", "10" ... } in a map > and then read in a piece at a time and performs some > simple change and replace to get the correct values in. > Then we need something that allows parts of the XML file > to be written to file and purged from RAM to avoid the > memory problem. > > Suggestions for solutions are appreciated. An idea. Put spaces in your names Store { "#1": }. When you have collected all your final data, go throught your stored #, seek at their position in the file, and replace the data (writting same amount of chars than reserved). A kind of direct access to nodes in an XML document file. A+ Laurent. From mwm at mired.org Mon Nov 28 12:05:03 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 28 Nov 2005 12:05:03 -0500 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: <86lkz8vh34.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Mon, 28 Nov 2005 10:02:19 +0100, Sybren Stuvel wrote: >> Duncan Booth enlightened us with: >>> I would have thought that no matter how elaborate the checking it is >>> guaranteed there exist programs which are correct but your verifier >>> cannot prove that they are. >> Yep, that's correct. I thought the argument was similar to the proof >> that no program (read: Turing machine) can determine whether a program >> will terminate or not. > No, that is not right -- it is easy to create a program to determine > whether *some* programs will terminate, but it is impossible to create a > program which will determine whether *all* programs will terminate. Which means you can't create a verifier which will verify all programs. Is there a reason to believe that you can't have a verifier with three possible outcomes: Correct, Incorrect, and I don't know, and it is always correct in doing so? Note that "I don't know" could be "I ran longer than I think is reasonable and gave up trying." http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Fri Nov 18 23:22:11 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 15:22:11 +1100 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 18 Nov 2005 11:17:17 -0800, David Wahler wrote: > Daniel Crespo wrote: >> I would like to know how can I do the PHP ternary operator/statement >> (... ? ... : ...) in Python... >> >> I want to something like: >> >> a = {'Huge': (quantity>90) ? True : False} > > Well, in your example the '>' operator already returns a boolean value > so you can just use it directly. Hoewver, I agree that there are > situations in which a ternary operator would be nice. Unfortunately, > Python doesn't support this directly; the closest approximation I've > found is: > >>>> (value_if_false, value_if_true)[boolean_value] Which doesn't short-circuit: both value_if_false and value_if_true are evaluated. WHY WHY WHY the obsession with one-liners? What is wrong with the good old fashioned way? if cond: x = true_value else: x = false_value It is easy to read, easy to understand, only one of true_value and false_value is evaluated. It isn't a one-liner. Big deal. Anyone would think that newlines cost money or that ever time you used one God killed a kitten. -- Steven. From fredrik at pythonware.com Wed Nov 23 06:15:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 12:15:06 +0100 Subject: Missing /usr/lib/python2.3/config References: <3uj0jiF118p56U1@individual.net> Message-ID: Tin Gherdanarra wrote: > when trying to run the script ez_setup.py, I fail > with > > unable to open /usr/lib/python2.3/config/Makefile > > This is true. There is no /usr/lib/python2.3/config > directory. A check on groups.google revealed that > this is a bug in my debian distro or something. Is > this true? to build Python extensions, you need the developer extensions: http://packages.debian.org/stable/python/python-dev > Is there a work-around? I can't reinstall debian because it is > not my server. have you looked for prebuilt versions of whatever package it is you're trying to install? From bonono at gmail.com Thu Nov 10 04:05:41 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 01:05:41 -0800 Subject: getting results into one variable In-Reply-To: <1131611798.561119.48770@g43g2000cwa.googlegroups.com> References: <1131611798.561119.48770@g43g2000cwa.googlegroups.com> Message-ID: <1131613541.369720.192180@z14g2000cwz.googlegroups.com> s99999999s2... at yahoo.com wrote: > a = db.execute(stmt) and then expand variable 'a' > > instead of doing > (a,b) = db.execute(stmt) for return of 2 > (a,b,c) = for return of 3 > (a,b,c,d) for return of 4 What do you intend to do with a, b, c,d ? a = f(x) always work. You can later then do a : if len(a) == 1: single value elif len(a) == 2: double value ... From luca.tavoletti at gmail.com Tue Nov 29 16:04:37 2005 From: luca.tavoletti at gmail.com (lux) Date: 29 Nov 2005 13:04:37 -0800 Subject: wxGrid and Focus Event In-Reply-To: References: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> <438CACF1.1020909@ulmcnett.com> <1133294056.952406.108890@g44g2000cwa.googlegroups.com> Message-ID: <1133298277.358823.184670@f14g2000cwb.googlegroups.com> TANKS!!! Now it work!!! Luca From bonono at gmail.com Sat Nov 19 09:29:32 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 19 Nov 2005 06:29:32 -0800 Subject: Obtaining an member function by name In-Reply-To: References: Message-ID: <1132410572.816607.162820@g44g2000cwa.googlegroups.com> f = getattr(obj,"bar") f() guy lateur wrote: > Hi all, > > Suppose you have this class: > > class foo: > def bar(): > > Suppose you also have the strings "foo" and "bar". How can you obtain the > function foo.bar()? > > Surely somebody knows.. > > TIA, > g From bonono at gmail.com Sat Nov 19 04:55:12 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 19 Nov 2005 01:55:12 -0800 Subject: Underscores in Python numbers In-Reply-To: References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> Message-ID: <1132394112.653132.15020@z14g2000cwz.googlegroups.com> Stefan Rank wrote: > The other idea of teaching int() about separator characters has > internationalis/zation issues: > In many European countries, one would naturally try:: > > int('500.000,23') > > instead of:: > > int('500,000.23') That is why I said "Of course, also support the locale variant where the meaning of "," and "." is swapped in most European countries. " We are seeing the same about base 2, 8, 10, 16. May be : int("E500.000,23") as we are using : 0xffff already for hex number From gustav at gmail.com Mon Nov 7 21:02:09 2005 From: gustav at gmail.com (=?iso-8859-1?q?Gustav_H=E5llberg?=) Date: 7 Nov 2005 18:02:09 -0800 Subject: Underscores in Python numbers Message-ID: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> I tried finding a discussion around adding the possibility to have optional underscores inside numbers in Python. This is a popular option available in several "competing" scripting langauges, that I would love to see in Python. Examples: 1_234_567 0xdead_beef 3.141_592 Would appreciate if someone could find a pointer to a previous discussion on this topic, or add it to a Python-feature-wishlist. - Gustav From mwm at mired.org Tue Nov 1 17:39:08 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 01 Nov 2005 17:39:08 -0500 Subject: If Statement Error (Tic Tac Toe) References: <1130878530.389205.179640@g43g2000cwa.googlegroups.com> <86wtjsyrcy.fsf@bhuda.mired.org> <1130882880.696770.8600@g47g2000cwa.googlegroups.com> Message-ID: <86oe54yovn.fsf@bhuda.mired.org> ale.of.ginger at gmail.com writes: > Thank you. It seems I didn't understand logic statements as much as I > thought I did! > > The one remaining question I have deals with this: > > if gameboard[cell] not in 'OX': > gameboard[cell] = 'O' > else: > print "This cell is already filled." > turnnumber -= 1 > > (gameboard[cell] not in 'OX' is the gameboard[cell] != 'OX' text I sort > of used in my code, right?) > > I am confused about "OX": what exactly *is* it? After that, I plan to > rewrite all the code... :) "OX" is a string. Saying "shortstring in longstring" is one way of asking if shortstring is contained in longstring. In your case, shortstring is one character long, but that's a string to Python. Python doesn't have a distinct character data type. While I'm at it, don't be confused by single quotes vs. double quotes. Unlike other languages, in Python they have the same meaning. The only difference is what you have to do to get a single (double) quote in the string. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVEMEcyber.com.au Thu Nov 24 02:27:59 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 24 Nov 2005 18:27:59 +1100 Subject: Why is dictionary.keys() a list and not a set? References: Message-ID: <43856B7F.1060808@REMOVEMEcyber.com.au> Peter Hansen wrote: > Definitely not. I believe it's currently guaranteed that the order of > the items in dict.keys() and dict.values() will match (i.e. the index of > any key in its list will be the same as the index of the corresponding > value in its list). This property is almost certainly used in some > code, so it can't be broken without good reason. As I recall, that guarantee is only if the dict is not modified between retrieving the keys and retrieving the values. -- Steven. From pythonnew at gmail.com Tue Nov 15 02:35:21 2005 From: pythonnew at gmail.com (Ben Bush) Date: Mon, 14 Nov 2005 23:35:21 -0800 Subject: compare list In-Reply-To: <8c11e4350511142142p67bccb05sf169fcec4d6edf1b@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <1h614v2.p5duok1vr3rjqN%aleax@mail.comcast.net> <8c11e4350511142142p67bccb05sf169fcec4d6edf1b@mail.gmail.com> Message-ID: <8c11e4350511142335u407d9b34sf44fb91f01a4baff@mail.gmail.com> On 11/14/05, Ben Bush wrote: > > > > > > Hijacking Brian's response since my newsserver never god Ben's original > > request...: > > > > I would program this at a reasonably high abstraction level, based on > > sets -- since you say order doesn't matter, sets are more appropriate > > than lists anyway. For example: > > > > def two_cont_in_common(x, y): > > common = set(x).intersection(y) > > return bool(common.intersection (z+1 for z in common)) > > > > i.e., given two lists or whatever, first build the set of all elements > > they have in common, then check if that set contains two continuous > > elements. Then, as Brian suggests, you can use this dyadic function on > > a reference list and as many others as you wish: > > > > def bens_task(reference, others): > > return [two_cont_in_common(alist, reference) for alist in others] > > > > The call bens_task(lisA, lisB, lisC, lisD) will give you essentially > > what you require, except it uses True and False rather than 1 and 0; if > > you need to fix this last issue, you can add an int(...) call around > > these booleans in either of the functions in question. > > > > > > Alex > > I got invalid syntax error when i run Alex's code. do not know why. > > Alex, I use PythonWin to run: def two_cont_in_common(x, y): common = set(x).intersection(y) return bool(common.intersection(z+1 for z in common)) def bens_task(reference, others): return [two_cont_in_common(alist, reference) for alist in others] I got invalid syntax error and the mouse's cursor stay on the 'for' in the statement of return bool(common.intersection(z+1 for z in common)) -- Thanks! Ben Bush -------------- next part -------------- An HTML attachment was scrubbed... URL: From bonono at gmail.com Sat Nov 19 20:40:42 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 19 Nov 2005 17:40:42 -0800 Subject: Underscores in Python numbers In-Reply-To: References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132394112.653132.15020@z14g2000cwz.googlegroups.com> <1132430536.514884.302550@g44g2000cwa.googlegroups.com> Message-ID: <1132450842.773190.265670@o13g2000cwo.googlegroups.com> Steve Holden wrote: > Being European myself I am well aware of the notational differences of > the different locales, and I am perfectly happy that users can enter > numbers in their preferred format when they execute a program. > > However, I am not happy about the idea that a program source would need > to be edited before it would work after being moved to another locale. > Huh ? Up to now, all I am talking about is making the three init function(int/float/decimal) to be smarter on coverting string to their type. It doesn't affect the code in anyway if you don't need it or want to use it. It is more like a helper function for the issue of people are so concern about the seperators in big numbers. It introduce no new syntax to the language at all. And should you say use the imaginary format "E500.000,23", it still works no matter where your program is running or what the hosting locale is. Don't understand what changes you are referring to. We are facing similar issue today. A typical case is MM/DD/YYYY date format. Or may be I need to import text file(csv for example) which may already contain numbers in this format. From james at colannino.org Wed Nov 9 13:24:45 2005 From: james at colannino.org (James Colannino) Date: Wed, 09 Nov 2005 10:24:45 -0800 Subject: PYTHON LOOSING FOR JAVA??????? In-Reply-To: <797fe3d40511081246h46169553x1f2a1289b1837864@mail.gmail.com> References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> <436FD5D4.7010307@v.loewis.de> <797fe3d40511081246h46169553x1f2a1289b1837864@mail.gmail.com> Message-ID: <43723EED.90109@colannino.org> Bill Mill wrote: >+1 QOTW > > My ignorance shows here. What does that mean? :-P James -- My blog: http://www.crazydrclaw.com/ My homepage: http://james.colannino.org/ "If Carpenters made houses the way programmers design programs, the first woodpecker to come along would destroy all of civilization." --Computer Proverb From sjdevnull at yahoo.com Thu Nov 17 01:24:19 2005 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 Nov 2005 22:24:19 -0800 Subject: best way to discover this process's current memory usage, cross-platform? In-Reply-To: <1h64n58.dew0mo1pu14zmN%aleax@mail.comcast.net> References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132080864.280909.51540@g44g2000cwa.googlegroups.com> <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> <1132121442.019702.66620@g47g2000cwa.googlegroups.com> <1132166050.888977.101350@g44g2000cwa.googlegroups.com> <1h64n58.dew0mo1pu14zmN%aleax@mail.comcast.net> Message-ID: <1132208659.537907.254540@g47g2000cwa.googlegroups.com> Alex Martelli wrote: > > Considering that the main purpose is adding regression tests to confirm > that a hopefully-fixed memory leak does not recur, I'm not sure why > shared memory should be a problem. What scenarios would "leak shared > memory"? Apache leaks SHM segments in some scenarios. SysV SHM segments aren't freed explicitly when the process exits. They're easy enough to clean up by hand, but it's nicer to avoid that. From pmartin at snakecard.com Tue Nov 1 13:44:33 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Tue, 01 Nov 2005 18:44:33 +0000 Subject: scweb pre-release 0.1 Message-ID: Dear all, referring to www.snakecard.com/WordPress: As I am _very_ much struggling with xpcom and pyxpcom, I have put on www.snakecard.com/SCWEB: 1) the cgi scripts 2) a firefox plugin which simulates the xpcom (ie: access to the external device ... smart card) and talks to the cgi scripts The project will also soon be hosted on: http://scwebxpcom.mozdev.org Any info on xpcom/pyxpcom is quite welcome: the current xpcom component (c++ which does not register properly (sigh) is also on the site) ... any help welcome. Regards, Philippe From jes at nl.demon.net Fri Nov 4 14:24:58 2005 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 04 Nov 2005 19:24:58 -0000 Subject: Tkinter- New Window References: <1131126422.958411.66860@f14g2000cwb.googlegroups.com> Message-ID: <11mndcaj2vefgf6@corp.supernews.com> In article <1131126422.958411.66860 at f14g2000cwb.googlegroups.com>, Tuvas wrote: >Is there a way to make a new window pop up using Tkinter? I have some >functions that require more data in my interface than I have space for, >and would like to be able to pop up a new window to request this >information. Thanks! Dialogue boxes pop up new windows for gathering information. If you want a more permanent second window, then the Toplevel() widget is like a frame, but is a separte window with window manager decorations, can be sparately iconfied etc. from Tkinter import * root = Tk() root.title('Root') rootlabel = Label(root, text = 'This is the root window', relief = RIDGE) rootlabel.pack(side = TOP, fill = BOTH, expand = YES) other = Toplevel() other.title('Second Window') otherlabel = Label(other, text = 'This is the other window', relief = RIDGE) otherlabel.pack(side = TOP, fill = BOTH, expand = YES) root.mainloop() -- Jim Segrave (jes at jes-2.demon.nl) From aleax at mail.comcast.net Thu Nov 3 21:42:33 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 18:42:33 -0800 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> <1131023021.643251.113330@f14g2000cwb.googlegroups.com> <1h5fwpi.1wjmgm417fbm8dN%aleax@mail.comcast.net> <1131033712.535402.193520@z14g2000cwz.googlegroups.com> Message-ID: <1h5grc5.1f520xizhqvucN%aleax@mail.comcast.net> bonono at gmail.com wrote: > But when we talk about organisation(and convincing sometimes not on > merit sake), banner name helps. I was once in organisation where The > MS/Intel/IBM combination is a sure thing because even if there is > anything went wrong, it wouldn't be the reason for scrutiny comparing > with say using a machine with AMD inside. The good old "nobody ever got fired for [X]", hm? You may be a shrewder judge of human nature (or, at least, "human nature as evidenced by CYAing behavior of humans within suitably disfunctional organizations") than I was by my implied assertion that successes _within a certain broad area of software development_ may be more relevant than successes by "prestigiously named firm" in somewhat-unrelated fields. It would still be easier to respond to your posts if you didn't top-post, though (i.e., if you didn't put your comments BEFORE what you're commenting on -- that puts the "conversation" in a weirdly distorted order, unless one give up on quoting what you're commenting on, or invests a lot of time and energy in editing...;-). Alex From y.glodt at sitasoftware.lu Wed Nov 9 08:34:57 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 09 Nov 2005 14:34:57 +0100 Subject: append to non-existing list In-Reply-To: <1131541405.947990.296750@g47g2000cwa.googlegroups.com> References: <1131541405.947990.296750@g47g2000cwa.googlegroups.com> Message-ID: <4371FB01.5030900@sitasoftware.lu> bonono at gmail.com wrote: > I am afraid you have to either go back to php or whatever programming > language that fits your style or change your style to fit python. sorry for offending... I just asked a question, and now I know one more thing about python... And btw I really am surprised by the amount of answers that my question rose, in so little time! thanks all! > There is a lot I don't like about python but if you have to use it, you > have to cope with it. > > Yves Glodt wrote: >> My question is: Is there no way to append to a non existing list? >> >> I am lazy for declaring it first, IMHO it bloats the code, and (don't >> know if it's good to say that here) where I come from (php) I was used >> to not-needing it... >> >> >> regards, >> Yves > From g.tagliaretti at gmail.com Mon Nov 28 15:05:11 2005 From: g.tagliaretti at gmail.com (GIan Mario Tagliaretti) Date: Mon, 28 Nov 2005 21:05:11 +0100 Subject: pcm format to wav... References: Message-ID: On Mon, 28 Nov 2005 18:15:25 +0100, durumdara at mailpont.hu wrote: > I have WinXP. Bad for you :) > I want to convert my PySonic recorded (raw) pcm format files to wav > files. How can I do it ? You can use -> http://www.pymedia.org/ cheers -- Tagliaretti Gian Mario PyGTK GUI programming http://www.parafernalia.org/pygtk/ From alanmk at hotmail.com Wed Nov 2 10:27:37 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 02 Nov 2005 15:27:37 +0000 Subject: WTF? In-Reply-To: References: Message-ID: [James Stroud] > Why do my posts get held for suspcious headers You're probably trying to post through the python-list email address, which has had SPAM problems in the past, because the email address has been used by spammers as a forged from address, meaning the bounces would go to everyone, including being gateway'ed to comp.lang.python, which is the NNTP group in which many people read this "list". Have you tried using an NNTP client instead, or using a web interface such as Google Groups? http://groups.google.com/group/comp.lang.python?gvc=2 > and troll Xha Lee gets to post > all sorts of profanity and ranting without any problem? Take a look at the source of XL's messages: he posts through Google Groups, thus completely avoiding the SPAM filter on python.org. http://groups.google.com/group/comp.lang.python/msg/762c8dad1928ecc2?dmode=source -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From gdamjan at gmail.com Wed Nov 30 17:58:34 2005 From: gdamjan at gmail.com (Damjan) Date: 30 Nov 2005 14:58:34 -0800 Subject: Oracle 9i client for Linux In-Reply-To: References: Message-ID: <1133391514.680881.59860@o13g2000cwo.googlegroups.com> This is a list of files I use to compile cx_Oracle, php-oci amd perl DB::OCI on Linux. I set ORACLE_HOME to /usr/lib/oracle and symlink the *.so files in /usr/lib so that I don't need to set LD_LIBRARY_PATH. I guess this list can be reduced some more... but I got tired of experimenting And the instant client 10.0 will work with a 9i database, but will not work with some 8.0 and 8.1 databases. /usr/lib/oracle/lib/classes12.jar /usr/lib/oracle/lib/libclntsh.so.10.1 /usr/lib/oracle/lib/libnnz10.so /usr/lib/oracle/lib/libocci.so.10.1 /usr/lib/oracle/lib/libociei.so /usr/lib/oracle/lib/libocijdbc10.so /usr/lib/oracle/lib/ojdbc14.jar /usr/lib/oracle/lib/libclntsh.so /usr/lib/oracle/lib/libocci.so /usr/lib/oracle/rdbms/ /usr/lib/oracle/rdbms/public/ /usr/lib/oracle/rdbms/public/nzerror.h /usr/lib/oracle/rdbms/public/nzt.h /usr/lib/oracle/rdbms/public/occi.h /usr/lib/oracle/rdbms/public/occiAQ.h /usr/lib/oracle/rdbms/public/occiCommon.h /usr/lib/oracle/rdbms/public/occiControl.h /usr/lib/oracle/rdbms/public/occiData.h /usr/lib/oracle/rdbms/public/occiObjects.h /usr/lib/oracle/rdbms/public/oci.h /usr/lib/oracle/rdbms/public/oci1.h /usr/lib/oracle/rdbms/public/oci8dp.h /usr/lib/oracle/rdbms/public/ociap.h /usr/lib/oracle/rdbms/public/ociapr.h /usr/lib/oracle/rdbms/public/ocidef.h /usr/lib/oracle/rdbms/public/ocidem.h /usr/lib/oracle/rdbms/public/ocidfn.h /usr/lib/oracle/rdbms/public/ociextp.h /usr/lib/oracle/rdbms/public/ocikpr.h /usr/lib/oracle/rdbms/public/ocixmldb.h /usr/lib/oracle/rdbms/public/odci.h /usr/lib/oracle/rdbms/public/oratypes.h /usr/lib/oracle/rdbms/public/ori.h /usr/lib/oracle/rdbms/public/orid.h /usr/lib/oracle/rdbms/public/orl.h /usr/lib/oracle/rdbms/public/oro.h /usr/lib/oracle/rdbms/public/ort.h /usr/lib/oracle/rdbms/public/xa.h /usr/lib/oracle/rdbms/demo/ /usr/lib/oracle/rdbms/demo/cdemo81.c /usr/lib/oracle/rdbms/demo/demo.mk /usr/lib/oracle/rdbms/demo/occidemo.sql /usr/lib/oracle/rdbms/demo/occidemod.sql /usr/lib/oracle/rdbms/demo/occidml.cpp From pythonnew at gmail.com Tue Nov 22 09:06:46 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 22 Nov 2005 06:06:46 -0800 Subject: Tkinter's coordinates setting In-Reply-To: <56190b6c0511211530n23d81555l9937e7b32dec6703@mail.gmail.com> References: <8c11e4350511171233t5c984a13ua88fd71634fdaeff@mail.gmail.com> <56190b6c0511171432y578a6d88qe6b5ff69b4b19443@mail.gmail.com> <1d987df30511171610l7942831cs7f76a690329e91a8@mail.gmail.com> <56190b6c0511211530n23d81555l9937e7b32dec6703@mail.gmail.com> Message-ID: <8c11e4350511220606l3af2b5bfo2aa9194a25579fb4@mail.gmail.com> On 11/21/05, Steve Juranich wrote: > > On 11/17/05, Shi Mu wrote: > > why subtract 1 from max_y - original_y? > > Because in the computer science world we like starting to count at 0. > > image_size = 1000 > original_y = 25 # Really the 26th pixel line. > new_y = 1000 - 25 - 1 # 26 pixels from the bottom of the screen. > > -- > Steve Juranich > Tucson, AZ > USA > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From s_david_rose at hotmail.com Fri Nov 25 10:47:16 2005 From: s_david_rose at hotmail.com (Dave Rose) Date: Fri, 25 Nov 2005 10:47:16 -0500 Subject: Dynamic classes Message-ID: Hello all. I was wondering if creating classes could be dynamic. I want to know if I can make a class Person, then read in a list of names (say people's names) so then I can have a class instance created for each name in the list? Why do I want to do this? I was just thinking if I had a name on the list, Dave, I could then be able to read the name in the list, and assign Maria.birthday = <> and all the other attributes I would want to use a class for, except this is dynamic. I don't know how to iterate thru the list to assign the different attributes yet, but this seemed reasonable to want to do, and thought I could learn from this. Thanks! Dave From tuvas21 at gmail.com Fri Nov 11 13:06:17 2005 From: tuvas21 at gmail.com (Tuvas) Date: 11 Nov 2005 10:06:17 -0800 Subject: PIL- error message- cannot open libtiff.so.3 Message-ID: <1131732377.111363.249560@f14g2000cwb.googlegroups.com> Okay, so I've been getting this error message when trying to use PIL to open a JPEG, that there isn't a library by the name of libtiff.so.3 . I've been searching the documentation, there isn't any reference to this library. Also, I don't know why it's doing this as I'm trying to open a JPEG, and not a tiff. I tried with a .bmp with similar results. Any ideas? Thanks! From mwm at mired.org Thu Nov 17 18:52:28 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Nov 2005 18:52:28 -0500 Subject: Zope vs Php References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> Message-ID: <86br0in877.fsf@bhuda.mired.org> "Steve" writes: > I am going to go the mod_python route. > > as for why a person would go route one over route 2 > > is that the number of lines of html/output vs python code are usually > 10 to 1 and it's much easier to encapsulate the python code than to > quote and escape all the html/css/xml It is? When doing that, I tend to write things like: html_data = """ Lots of HTML text here, with the random %(name)s thrown in to insert values. """ # Python code to put values in html_dictionary print html_data % html_dictionary The only quoting of the HTML is the two sets of triple-quotes to wrap the whole thing. The escaping is done in the python, to make sure the values in the dictionary are properly escaped. Usually, multiple such pieces get pasted together at the end of the function. That said, I have to confess that lately I've been using Cheetah templates, because the syntax for inserting values is simpler, and the way Cheetah templates work naturally in the Python inheritance hierarchy. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From http Mon Nov 28 18:20:53 2005 From: http (Paul Rubin) Date: 28 Nov 2005 15:20:53 -0800 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> <86lkz8vh34.fsf@bhuda.mired.org> Message-ID: <7x7jasgy0a.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I don't know what the state of the art is, but I suspect it > will be a long, long time before it is as easy as running "import > mymodule; verify(mymodule)". Some pretty significant pieces of software have been formally verified to meet their formal specifications. The trouble with "verify(mymodule)" is that usually means something closer to "verify that mymodule does what I hope it does". The computer does not yet have a telepathy peripheral that can read your mind and figure out what you are hoping, and people's attempts to express formally what they are hoping are easily wrong just like programs are often wrong. From seddharth at adanispices.com Fri Nov 25 22:15:06 2005 From: seddharth at adanispices.com (seddharth at adanispices.com) Date: Sat, 26 Nov 2005 08:45:06 +0530 Subject: Mail Delivery System Message-ID: <200511260255.jAQ2tnY07677@localagri.com> ------------------ Virus Warning Message (on moms.localagri.com) Found virus WORM_MYTOB.V in file message.pif (in message.zip) The uncleanable file message.zip is moved to /etc/iscan/virus/virgp7pVn. --------------------------------------------------------- -------------- next part -------------- The message contains Unicode characters and has been sent as a binary attachment. -------------- next part -------------- ------------------ Virus Warning Message (on moms.localagri.com) message.zip is removed from here because it contains a virus. --------------------------------------------------------- From bonono at gmail.com Wed Nov 30 01:51:07 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 29 Nov 2005 22:51:07 -0800 Subject: Making immutable instances In-Reply-To: <86u0duodzl.fsf@bhuda.mired.org> References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> <86u0duodzl.fsf@bhuda.mired.org> Message-ID: <1133333467.677454.134110@g49g2000cwa.googlegroups.com> Mike Meyer wrote: > The thing is, the need for an extra attribute doesn't come from your > class, it comes from the client of your class. You can't know if the > client code will need that facility or not, so the only choice you > know won't be wrong sometime is to always add the mixin. In which > case, you should follow the Python "the less boilerplate, the better" > practice, and leave it off. Which is what we have. > > Letting the class author declare whether or not the client can add > attributes is wrong for the same reasons - and in the same places - > that letting the class author declare that the client shouldn't be > allowed to access specific attributes, and so on, is wrong. Of > course, it's also *right* for the same reasons and in the same places > as those things. I just don't think those places happen in Python > programs. > I am puzzled, and could have read what you want wrong. Are you saying you want something like this : a={} a.something = "I want to hang my stuff here, outside the intended use of dict" From fredrik at pythonware-dot-com.no-spam.invalid Tue Nov 22 06:33:40 2005 From: fredrik at pythonware-dot-com.no-spam.invalid (Fredrik Lundh) Date: 22 Nov 2005 11:33:40 GMT Subject: about sort and dictionary References: Message-ID: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> bonono at gmail.com wrote: > so what would an entry-level Python programmer expect from this > piece of code? > > for item in a.reverse(): > print item > for item in a.reverse(): > print item > > I would expect it to first print a in reverse then a as it was. > > a=[1,2,3] > > I expect it to print > > 3 > 2 > 1 > 1 > 2 > 3 > really? wouldn't 3 2 1 3 2 1 make a lot more sense ? From deets at nospam.web.de Mon Nov 21 13:47:45 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Nov 2005 19:47:45 +0100 Subject: Aproximative string matching In-Reply-To: <438149D6.5090403@REMOVEMEcyber.com.au> References: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> <1132543801.861940.146530@g43g2000cwa.googlegroups.com> <438149D6.5090403@REMOVEMEcyber.com.au> Message-ID: <3uej2eF11506mU1@uni-berlin.de> Steven D'Aprano wrote: > elbertlev at hotmail.com wrote: > >> This algorithm is called soundex. Here is one implementation example. >> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52213 >> >> here is another: >> http://effbot.org/librarybook/soundex.htm > > > Soundex is *one* particular algorithm for approximate string matching. > It is optimised for matching Anglo-American names (like Smith/Smythe), > and is considered to be quite old and obsolete for all but the most > trivial applications -- or so I'm told. > > Soundex will not match arbitrary changes -- it will match both cat and > cet, but it won't match cat and mat. > > A more sophisticated approximate string matching algorithm will use the > Levenshtein distance. You can find a Useless implementation here: > > http://www.uselesspython.com/download.php?script_id=108 > > > Given a function levenshtein(s1, s2) that returns the distance between > two strings, you could use it for approximate matching like this: > > def approx_matching(strlist, target, dist=1): > """Matches approximately strings in strlist to > a target string. > > Returns a list of strings, where each string > matched is no further than an edit distance of > dist from the target. > """ > found = [] > for s in strlist: > if levenshtein(s, target) <= dist: > found.append(s) > return s I compute a relative metric based on th every same implementation like this: def relative(a, b): """ Computes a relative distance between two strings. Its in the range (0-1] where 1 means total equality. @type a: string @param a: arg one @type b: string @param b: arg two @rtype: float @return: the distance """ d = levensthein(a,b) longer = float(max((len(a), len(b)))) shorter = float(min((len(a), len(b)))) r = ((longer - d) / longer) * (shorter / longer) return r The idea is that otherwise e.g. "cat" and "hippopothamus" have a l-distance of only 3, which one would consider good at the first look. Regards, Diez From mwm at mired.org Sat Nov 26 05:05:42 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 05:05:42 -0500 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: <86fypjg1vt.fsf@bhuda.mired.org> Steve Holden writes: > Simply assuming that because you have developed the code "in your own > time" you have sole rights to it, or even a right to redistribute, is > likely to lead to trouble and I would recommend against that course of > action. The employment agreement may state specifically that the company owns such properties. There have been companies that explicitly claim all software/inventions/etc that you produce while in their employee, even if they had nothing to do with said IP. Some jurisdictions make this illegal - but that doesn't stop the company from trying to convince you they can do that. But this cuts both ways - if you get them to agree in writing as part of the employment agreement that the code isn't there, which Steve suggested, then laws about "work for hire" are pretty much irrelevant. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From skip at pobox.com Wed Nov 9 08:15:31 2005 From: skip at pobox.com (skip at pobox.com) Date: Wed, 9 Nov 2005 07:15:31 -0600 Subject: append to non-existing list In-Reply-To: <4371EFBC.1030502@sitasoftware.lu> References: <4371EFBC.1030502@sitasoftware.lu> Message-ID: <17265.63091.388847.972049@montanaro.dyndns.org> Yves> My question is: Is there no way to append to a non existing list? My question in return is: How is Python supposed to know that pkcolumns is supposed to be a list instead of some other type of object that happens to define an append() method? For example, my code might contain this class definition before the suspect pkcolumns.append() call: class MaxLengthList: def __init__(self, maxsize=0): self.data = [] self.maxsize = maxsize def append(self, item): if self.maxsize and len(self.data) == self.maxsize: del self.data[0] self.data.append(item) def __getattr__(self, attr): return getattr(self.data, attr) I think it would be perfectly reasonable for Python to choose to instantiate my MaxLengthList instead of a plain old list. Yves> I am lazy for declaring it first, IMHO it bloats the code, and Yves> (don't know if it's good to say that here) where I come from (php) Yves> I was used to not-needing it... I don't know php, but would also have to wonder how it knows to create a list instead of an integer (for example). Finally, from the Zen of Python (try "import this" at an interpreter prompt): In the face of ambiguity, refuse the temptation to guess. Skip From cito at online.de Mon Nov 28 18:05:18 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 29 Nov 2005 00:05:18 +0100 Subject: New docs for set elements/dictionary keys In-Reply-To: <863blhwcnc.fsf@bhuda.mired.org> References: <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> <863bljf1o8.fsf@bhuda.mired.org> <4388f6ce$0$22897$9b622d9e@news.freenet.de> <86mzjqew8l.fsf_-_@bhuda.mired.org> <43896474$0$22007$9b622d9e@news.freenet.de> <86k6etd8p2.fsf@bhuda.mired.org> <438A3896.7020501@v.loewis.de> <86wtitbiom.fsf@bhuda.mired.org> <863blhwcnc.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Christoph Zwerschke wrote: >>I think that is not so bad. How about this simplification: >> >>Any hashable object(1) can be used as a dictionary key/set >>element. Lists, sets and dicts are not hashable, and can not be >>used. Tuples can be used if all the things they contain are >>hashable. Instances of all other built-in types and most user-defined >>classes are hashable. >> >>(1) Objects for which the hash() function returns an appropriate >>(proper?) value. See the __hash__ documentation for details. > > I think that will do quite nicely, as the information about __hash__, > __cmp__ and __eq__ are all in the __hash__ documentation. You wrote it > - why don't you submit a PR with it? Actually you wrote it ;-) Do suggestions like this one go to the normal Python sf bug tracker? -- Christoph From noway at sorry.com Wed Nov 23 18:36:59 2005 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 23 Nov 2005 23:36:59 GMT Subject: Making immutable instances References: Message-ID: Ben Finney wrote: > How can a (user-defined) class ensure that its instances are > immutable, like an int or a tuple, without inheriting from those > types? > > What caveats should be observed in making immutable instances? In short, you can't. I usually try harder to derive from tuple to achieve this (defining a few read-only properties to access item through attributes). Using __slots__ is then required to avoid people adding attributes to the instance. In fact, I don't know the rationale. I would think it would be a great addition to be able to say __immutable__ = True or something like that. Or at least, I'd be grateful if someone explained me why this can't or shouldn't be done. -- Giovanni Bajo From richard at nospam.com Sat Nov 5 18:04:05 2005 From: richard at nospam.com (Richard Townsend) Date: Sat, 5 Nov 2005 23:04:05 +0000 Subject: starting an X11 session from Python References: <848bf.3759$HB.1191@dukeread12> Message-ID: <1apos7kq1fn89$.z1ofrxbxlmxj.dlg@40tude.net> On Sat, 05 Nov 2005 19:51:40 +0000, Philippe C. Martin wrote: > Hi, > > Have there been any attempt to do so, and is there any source out there that > could help me get started ? > > Regards, > > Philippe Have you tried: http://python-xlib.sourceforge.net/ http://sourceforge.net/projects/python-xlib -- Richard From fredrik at pythonware.com Tue Nov 8 07:26:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Nov 2005 13:26:44 +0100 Subject: Writing Win32 shell extensions in python? References: <1131449233.808643.76040@g49g2000cwa.googlegroups.com> Message-ID: "Thomas W" wrote: > Well, is it possible to write Win32 shell extension in python? I want > to create a virtual folder ( like gmailfs ) to serve files from a > http-server ( and no, I cannot use webdav ) so that users can access > them like normal files in Windows Explorer. > > Any hints or info about this would be highly appreciated. typing your subject into a google search box brings up plenty of hits, including http://mail.python.org/pipermail/python-list/2005-March/271141.html From: Roger Upole Date: Tue Mar 15 12:39:43 CET 2005 There's an example shell extension in the Pywin32 demos that creates a pseudo-folder whose contents are determined by python code. Take a look at \win32comext\shell\demos\servers\shell_view.py. However, I don't think it qualifies as 'simple' ;) (alright, that one was two clicks away from the search result, not one, but that's close enough) here's a direct pointer to an on-line copy of that script, btw: http://tinyurl.com/babct (that copy may be outdated; you may want to get the latest version from the pywin package before you start hacking on this) From kent37 at tds.net Mon Nov 7 20:31:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 20:31:40 -0500 Subject: Regular expression question -- exclude substring In-Reply-To: References: <1131405834.093144.206510@g43g2000cwa.googlegroups.com> <1131409094.240352.67240@g43g2000cwa.googlegroups.com> Message-ID: <436ffd9b$1_1@newspeer2.tds.net> James Stroud wrote: > On Monday 07 November 2005 16:18, google at fatherfrost.com wrote: > >>Ya, for some reason your non-greedy "?" doesn't seem to be taking. >>This works: >> >>re.sub('(.*)(00.*?01) target_mark', r'\2', your_string) > > > The non-greedy is actually acting as expected. This is because non-greedy > operators are "forward looking", not "backward looking". So the non-greedy > finds the start of the first start-of-the-match it comes accross and then > finds the first occurrence of '01' that makes the complete match, otherwise > the greedy operator would match .* as much as it could, gobbling up all '01's > before the last because these match '.*'. For example: > > py> rgx = re.compile(r"(00.*01) target_mark") > py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') > ['00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01'] > py> rgx = re.compile(r"(00.*?01) target_mark") > py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') > ['00 noise1 01 noise2 00 target 01', '00 dowhat 01'] ??? not in my Python: >>> rgx = re.compile(r"(00.*01) target_mark") >>> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') ['00 noise1 01 noise2 00 target 01'] >>> rgx = re.compile(r"(00.*?01) target_mark") >>> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') ['00 noise1 01 noise2 00 target 01'] Since target_mark only occurs once in the string the greedy and non-greedy match is the same in this case. Kent From broek at cc.umanitoba.ca Sun Nov 13 05:24:48 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 13 Nov 2005 04:24:48 -0600 Subject: how to think like a computer scientist In-Reply-To: <20051112042519.2673.qmail@web35913.mail.mud.yahoo.com> References: <20051112042519.2673.qmail@web35913.mail.mud.yahoo.com> Message-ID: <43771470.5070404@cc.umanitoba.ca> john boy said unto the world upon 2005-11-11 22:25: > Question for the following program: sec 5.5 > > def factorial (n): > if n == 0: > return 1 > else: > recurse = factorial (n-1) > result = n * recurse > return result > > How come whenever I state the function with "n" given a value it prints no results in the interpreter for EX: > > So instead I have to give a "print" command to make the result appear in the interpreter > for EX: > Is this correct....should I have to give a print command?? Hey, I assume you mean when you run it as a script; when I run it as the interactive prompt, I get output: IDLE 1.1.2 >>> def factorial (n): if n == 0: return 1 else: recurse = factorial (n-1) result = n * recurse return result >>> factorial(3) 6 In general, it would be bad if the interpreter decided to print everything you asked it to compute. The function returns the result of the factorial(n) call, and it is up to your code to decide what to do with it. If the only use is to print it, then print factorial(3) might be what you want. But it is also possible you'd want to store the result for further computation, and would find the print an unwanted 'feature'. So, important_for_later = factorial(some_num) Best, Brian vdB From fakeaddress at nowhere.org Wed Nov 2 19:54:46 2005 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 03 Nov 2005 00:54:46 GMT Subject: PEP submission broken? Message-ID: <43695FE5.1080803@nowhere.org> Though I tried to submit a (pre-) PEP in the proper form through the proper channels, it has disappeared into the ether. In building a class that supports Python's slicing interface, http://groups.google.com/group/comp.lang.python/msg/8f35464483aa7d7b I encountered a Python bug, which, upon further discussion, seemed to be a combination of a wart and a documentation error. http://groups.google.com/group/comp.lang.python/browse_frm/thread/402d770b6f503c27 I submitted the bug report via SourceForge; the resolution was to document the actual behavior. Next I worked out what behavior I think would eliminate the wart, wrote it up as a pre-PEP, and sent it peps at python.org on 27 Aug of this year. I promptly received an automated response from Barry Warsaw, saying, in part, "I get so much email that I can't promise a personal response." I gathered that he is a PEP editor. I did not infer from his reply that PEP's are simply ignored, but this automated reply was the only response I ever received. I subscribed to the Python-dev list, and watched, and waited; nothing on my concern appeared. One response on the comp.lang.python newsgroup noted that a popular extention module would have difficulty maintaining consistency with my proposed PEP. My proposal does not break how the extension currently works, but still, that's a valid point. There are variations which do not have that problem, and I think I can see a course that will serve the entire Python community. From what I can tell, We need to address fixing the PEP process before there is any point in working on PEP's, -- --Bryan From luismgz at gmail.com Wed Nov 23 10:21:18 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 23 Nov 2005 07:21:18 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: <1132384787.420064.163300@g14g2000cwa.googlegroups.com> References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132376750.855932.45470@g47g2000cwa.googlegroups.com> <1132384787.420064.163300@g14g2000cwa.googlegroups.com> Message-ID: <1132759278.796200.137120@f14g2000cwb.googlegroups.com> This could be done easier this way: L = [('even','odd')[n%2] for n in range(8)] From python at hope.cz Fri Nov 4 10:27:32 2005 From: python at hope.cz (Lad) Date: 4 Nov 2005 07:27:32 -0800 Subject: How can I do this in Python? Message-ID: <1131118052.827738.235590@f14g2000cwb.googlegroups.com> Hi, I have a web program and a user can have access to a page only after he logged in. So, the program comes with a Login form and the user logins.But I do not know how to return the user back to where he came from, after a successful login. Something like this: PageWhereUserMustBeLogin -------->UserSigned----->- ^------<---------------------------------------------------<----| Thank you for help L. From scott.daniels at acm.org Fri Nov 11 11:59:33 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 11 Nov 2005 08:59:33 -0800 Subject: Inserting Records into SQL Server - is there a faster interfacethan ADO In-Reply-To: References: <1131724751.606322.162110@g44g2000cwa.googlegroups.com> Message-ID: <4374ccb5$1@nntp0.pdx.net> Alan Kennedy wrote: > [geskerrett at hotmail.com] > >> I have a program that reads records from a binary file and loads them >> into an MS-SQL Server database. It is using a stored proc, passing the >> parameters. > >> So my questions is .... >> Is there a "faster" method I can use to connect to the SQL server ? >> Or does anyone have any "optimization" tips the can offer ? > > Is there a reason why you need to use a stored procedure? > > Do you need to process the data in some way in order to maintain > referential integrity of the database? > > If the answer to both these questions is "no", then you can use the > "bcp" (Bulk CoPy) utility to transfer data into SQLServer *very* quickly. > > http://msdn.microsoft.com/library/en-us/coprompt/cp_bcp_61et.asp > http://www.sql-server-performance.com/bcp.asp > > thought-it-was-worth-mentioning-ly y'rs, > If the answer to some of the earlier questions is "yes," I have found "bcp" can be a great tool to fill up a new table of data "on its way in." SQL can then move it to where it should really go with nice transaction-protected SQL, proper index-building and so on. After distributing the data, you can drop the table of pending data. I agree this is off-topic, but it is too close to my experience. --Scott David Daniels scott.daniels at acm.org From onurb at xiludom.gro Wed Nov 9 14:45:52 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 09 Nov 2005 20:45:52 +0100 Subject: append to non-existing list In-Reply-To: References: <4371fb5a$0$18086$626a14ce@news.free.fr> Message-ID: <437251f4$0$25824$626a14ce@news.free.fr> Yves Glodt wrote: (snip) > > ok I see your point, and python's... > > (just FYI, and not to start a flamewar ;-): > In php, the [] means "append to an array object". yes, I know this. > If the array does not exist yet, it's created. Which is what I don't like. It should crash. > [] *is* explicit for > arrays, IIRC, you can also use it to sbscript strings, but I wouldn't bet my life on this. > thus for php it's clear what you want.) Nope. You may be in the case where you think the array already exists, and then you (well, I at least...) would prefer that PHP don't try to second-guess you... If and when I want to create an object, I tell it. If I dont tell "create me an array", I don't want one to come in existence. (snip) > an "undefined" notice, yes, not a warning... ;-) > (snip) > > Ok... I thank you for all the explanations. > > It helps me to see more far. I (and will continue to) use php for web, > and wanna standardize on python for all non-web stuff we are doing, You might discover that Python is just great for web programming too !-) > so I > might be a frequent guest on this list... You're welcome !-) And if you're a french speaker, there's also french-speaking mailing list and newsgroups. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bonono at gmail.com Wed Nov 9 10:13:16 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 07:13:16 -0800 Subject: append to non-existing list In-Reply-To: References: <4371EFBC.1030502@sitasoftware.lu><4371FA57.40206@sitasoftware.lu> Message-ID: <1131549196.831764.104480@g47g2000cwa.googlegroups.com> Fredrik Lundh wrote: > x = "10" + 20 # should this be 30 or 1020 or "1020" or ...? > I think Perl handles this case pretty well and sane. In fact, this strict but dynamic type checking is quite painful to work with, especially the new decimal class. I can do a : decimal + int but not decimal + float But then when I use some built-in math functions, it can convert decimal to float and return a float which then cannot be operate with another decimal. From bonono at gmail.com Thu Nov 24 02:01:23 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 23:01:23 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: <86y83ezn3t.fsf@bhuda.mired.org> Message-ID: <1132815683.602078.216760@g14g2000cwa.googlegroups.com> Fredrik Lundh wrote: > performance is of course another aspect; if you *need* two parallel > lists, creating a list full of tuples just to pull them apart and throw > them all away isn't exactly the most efficient way to do things. > > (if performance didn't matter at all, we could get rid most dictionary > methods; "iterkeys", "in", and locking should be enough, right?) If I need two parallel list(one key, one value), I can still use the same [(k,v)] tuple, just access it as x[0], x[1]. But the history alone explains it anyway. From avail4one at gmail.com Sun Nov 6 15:58:18 2005 From: avail4one at gmail.com (Waitman Gobble) Date: 6 Nov 2005 12:58:18 -0800 Subject: zipfile.py, fp.seek(-22,2) error In-Reply-To: <1131308902.758034.9270@g44g2000cwa.googlegroups.com> References: <1131308902.758034.9270@g44g2000cwa.googlegroups.com> Message-ID: <1131310698.588660.307210@g47g2000cwa.googlegroups.com> ok, i figured it out. the file i was trying to read on the linux machine was 0b. lol. i guess the "invalid argument" error was throwing me off. From jstroud at mbi.ucla.edu Tue Nov 1 17:56:35 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 1 Nov 2005 15:56:35 -0700 Subject: WTF? In-Reply-To: <11mfqsibenjoqff@corp.supernews.com> References: <11mfqsibenjoqff@corp.supernews.com> Message-ID: <200511011456.35872.jstroud@mbi.ucla.edu> On Tuesday 01 November 2005 14:26, Grant Edwards wrote: > On 2005-11-01, James Stroud wrote: > > Why do my posts get held for suspcious headers ... > Held? It's not a moderated group... And I quoteth (that's King James for "cuteth-and-pasteth"): > Your mail to 'Python-list' with the subject > > ? ? Re: Python's website does a great disservice to the language > > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > ? ? Message has a suspicious header James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mde at micah.elliott.name Wed Nov 9 16:28:25 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Wed, 9 Nov 2005 13:28:25 -0800 Subject: Pythonising the vim (e.g. syntax popups) In-Reply-To: <200511091609.09613.email@christoph-haas.de> References: <200511091609.09613.email@christoph-haas.de> Message-ID: <20051109212825.GA18475@kitchen.client.attbi.com> On Nov 09, Christoph Haas wrote: > I'm an addicted vim user and don't really use the IDLE for anything > more than calculations where I'm too lazy to start KCalc. But one > feature is very pretty: the built-in help for function calls while > you type. Like you enter... > > var1,var2=mystring.split( > ...and the IDLE shows me a popup saying... > "S.split([sep [,maxsplit]]) -> list of strings The PIDA IDE claims to be able to do something like this. I have not used PIDA, but I too am a vim zealot and I think wrapping vim with extra functionality is a great idea, and I'll try it out when I get a chance. > Is there a decent way to get that help into vim? Or like showing > docstrings or help that I get through pydoc on request? You can set 'keywordprg' to something like "pydoc" to enable "K" to pull up the help. Its default setting is to open manpages for words under the cursor. I don't use it since I've got an interpreter shell sitting in the corner of most virtual desktops -- doesn't everyone? And ctags features are excessively prevalent in vim, and ctags works fine with python IME. You can create a tags file of your whole python installation. > I've been working myself through a pile of vim macros/plugins but > couldn't find even one which simplifies programming in Python. Matchit is a good one for %-matching: http://www.vim.org/scripts/script.php?script_id=39 > Further issues would be handling the indentation Eric McSween wrote a python indenter: http://www.vim.org/scripts/script.php?script_id=974 > - maybe a plugin which syntax colors Sure, that's builtin. But Dmitry Vasiliev wrote some useful enhancements: http://www.vim.org/scripts/script.php?script_id=790 Note that you'll have to enable some variables in the macro. > syntax colors different levels of indentation so I don't have to use > my plastic ruler on the screen. That's kind of a nice idea, and it should be an easy one to write (but I'm not volunteering). You could write it (:h syntax-highlighting) or maybe post a request to the vim mailing list . Otherwise, folding would be useful for this. Pyfold might be helpful, though I haven't tried it: http://www.vim.org/scripts/script.php?script_id=781 I like the ruler idea! Usually when I find myself straining to figure out what level I'm at it means it's time to refactor. -- _ _ ___ |V|icah |- lliott http://micah.elliott.name mde at micah.elliott.name " " """ From bonono at gmail.com Sun Nov 20 09:11:53 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 06:11:53 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> Message-ID: <1132495913.393884.178020@f14g2000cwb.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > > I am writing a web applications(simple forms) which has a number of > > fields. Each field naturally has a name and a number of > > attributes(formatting etc.), like this : > > > > d = {'a':{...}, 'b':{....}} > > > > This dict would be passed to the Kid template system which would lay it > > out into a HTML form. For quick and dirty forms, I don't want to code > > each field individually in the HTML template but just from top to > > bottom(or left to right for a table) with a for loop. > > > > However, I still want to group certain fields together. This is my need > > of an ordered dict. > > huh? if you want a list, use a list. > > d = [('a', {...}), ('b', {....})] > Didn't I say that for quick and dirty form(usually first draft), I want a list ? But the same template, it would(may) be further enhanced by graphic designers in which case, I need direct access to the field names, thus the dict property. In this way, I don't have to change the python code just because I change the presentation in the template. From http Wed Nov 23 17:18:58 2005 From: http (Paul Rubin) Date: 23 Nov 2005 14:18:58 -0800 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132756197.635519.114180@g47g2000cwa.googlegroups.com> Message-ID: <7xlkzfatyl.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > dNewDataFields['CODE'] = dOldDataFields['CODEDATA'] > dNewDataFields['DATE'] = dOldDataFields['DATE'] > if dOldDataFields['CONTACTTYPE'] == 2: > dNewDataFields['CONTACT'] = dOldDataFields['FIRSTCONTACT'] > else: > dNewDataFields['CONTACT'] = dOldDataFields['SECONDCONTACT'] > > There. The world didn't end. It gets messy for a more complicated structure: d = {'x': x1() if x_is_old else x2(), 'y': y1() if y_is_old else y2(), 'z': z1() if z_is_old else z2() } etc. From roy at panix.com Tue Nov 1 10:31:59 2005 From: roy at panix.com (Roy Smith) Date: 1 Nov 2005 10:31:59 -0500 Subject: String Identity Test References: Message-ID: Duncan Booth wrote: > If 'a!=b' then it will also be the case that 'a is not b' That's true for strings, and (as far as I know), all pre-defined types, but it's certainly possible to define a class which violates that. class isButNotEqual: def __ne__ (self, other): return True a = isButNotEqual() b = a print "a != b:", a != b print "a is not b:", a is not b frame:play$ ./eq.py a != b: True a is not b: False On the other hand, I can't imagine any reason why you would want to define such a class, other than as a demonstration (or part of an obfuscated Python contest). From fredrik at pythonware.com Mon Nov 21 02:33:49 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Nov 2005 08:33:49 +0100 Subject: ownership problem? References: Message-ID: Jeffrey Schwab wrote: > > the problem isn't determining who owns it, the problem is determining > > who's supposed to release it. that's not a very common problem in a > > garbage-collected language... > > Yes it is. Memory is only one type of resource. Python's garbage collector deals with objects, not memory. > I am not a Python Guru from the sound of it, you haven't written serious programs in any of the languages you mention. From cfbolz at gmx.de Tue Nov 15 14:46:29 2005 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Tue, 15 Nov 2005 20:46:29 +0100 Subject: is parameter an iterable? In-Reply-To: <1132082783.353359.69900@g49g2000cwa.googlegroups.com> References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: <437A3B15.4010007@gmx.de> Hi! py wrote: > Dan Sommers wrote: > >>Just do it. If one of foo's callers passes in a non-iterable, foo will >>raise an exception, and you'll catch it during testing > > > That's exactly what I don't want. I don't want an exception, instead I > want to check to see if it's an iterable....if it is continue, if not > return an error code. I can't catch it during testing since this is > going to be used by other people. Note that using error codes is usually quite "unpythonic", the way to signal that something is exceptional (not necessarily wrong) is, well, an exception. Anyway, one way to solve this is the following: def foo(input_val): try: iterator = iter(input_val) except TypeError: # do non-iterable stuff else: for val in iterator: # do loop stuff Cheers, Carl Friedrich Bolz From michaelschneider at fuse.net Thu Nov 3 09:55:06 2005 From: michaelschneider at fuse.net (Michael Schneider) Date: Thu, 03 Nov 2005 09:55:06 -0500 Subject: weakrefs to functions for observer pattern In-Reply-To: <1h5f4p9.1ttt5sz13qi83uN%aleax@mail.comcast.net> References: <90265$436995f5$d8c4f6e6$28290@FUSE.NET> <1h5f4p9.1ttt5sz13qi83uN%aleax@mail.comcast.net> Message-ID: <436A24CA.9050202@fuse.net> Alex Martelli wrote: > Michael Schneider wrote: > > >>I would like to use weak refs in an observer pattern implementation. >>The problme that I have seems to be that weakrefs can't manage functions. > > > They can manage just fine functions written in *Python*, just not > "builtin functions*, i.e., ones written in *C*. Just wrap any builtin > function you need to register as observer into a tiny Python-coded > wrapper and live happily ever after. > ... > >>Not all objects can be weakly referenced; those objects which can >>include class instances, functions written in Python (but not in C), > > > > Alex Alex, Thank you, I mis-read the docs. The mistake I made was having was using a weak reference as a key in the dictionary. Weak references will be very useful for me. I really enjoy python. So many good things have been added to the language without taking the fun away :-) Mike -- The greatest performance improvement occurs on the transition of from the non-working state to the working state. From mhellwig at xs4all.nl Fri Nov 4 02:19:42 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Fri, 04 Nov 2005 08:19:42 +0100 Subject: I need Motivation In-Reply-To: References: Message-ID: <436b0b9b$0$11068$e4fe514c@news.xs4all.nl> blah at blah.blah wrote: > I m not a python Expert or anythin > i need help, i m losin my motivation to continue with python > can anyone inspire me again.??? Ooh that is easy, start learning other programming languages, you'll go back continuing with python very soon after that! ;-) -- mph From steve at holdenweb.com Sat Nov 19 23:36:30 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 20 Nov 2005 04:36:30 +0000 Subject: Delays getting data on sys.stdin.readline() ? In-Reply-To: <6addebae0511192016u7e2c75bl713ad5fcc1553b82@mail.gmail.com> References: <6addebae0511192016u7e2c75bl713ad5fcc1553b82@mail.gmail.com> Message-ID: Christian Convey wrote: > Hello, > > I've got a program that (ideally) perpetually monitors sys.stdin for > lines of text. As soon as a line comes in, my program takes some > action. > > The problem is, it seems like a very large amount of data must > accumulate on sys.stdin before even my first invocation of readline() > returns. This delay prevents my program from being responsive in the > way it must be. > > Has anyone else seen this effect? If so, is there a reasonable workaround? > Generally speaking there will be buffering of the output process that's feeding your standard input. You can try to set sys.stdin to be unbuffered (look at the interpreter's -u option), but depending on how the feeding process is organized it might hold data in its buffers before it appears on your process's stdin. You may have noticed the same thing in Unix-like operating systems when running tail -f on a file being fed by an active process: the output appears in chunks ending in partial lines because the feeding process's output buffer has been filled and the operating system has passed it to the tail process. 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 theboringdays at gmail.com Wed Nov 2 19:34:27 2005 From: theboringdays at gmail.com (theboringdays at gmail.com) Date: 2 Nov 2005 16:34:27 -0800 Subject: How to print random strings Message-ID: <1130978067.685487.194530@g44g2000cwa.googlegroups.com> Im at the end of chapter 3 of "Python Programming For The Absolute Beginner, Michael Dawson " and he asks to make a fortune program that displays a fortune each time its ran, and to have 5 unique fortunes. Whats confusing is that, he never discussed how to do this. The only thing he talked about was using random.randrange() and I tried that with text but it seems like its only for integers as it complains when I put text in the argument. So how would I go about have 5 strings, and running a program that will randomly pick one of those to print? I think he may have forgot to cover something? From mhellwig at xs4all.nl Thu Nov 24 03:51:52 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 24 Nov 2005 09:51:52 +0100 Subject: wxPython Licence vs GPL In-Reply-To: <43856594.40300@REMOVEMEcyber.com.au> References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> Message-ID: <43857f2c$0$11076$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > I'm FREE to use the software, FREE to redistribute it, FREE to give it > away, FREE to make derivative works, FREE to transfer the licence, *and* > I got it FREE of cost as well, but that doesn't make it free. > Indeed, when I explain GPL to non-techies and what their (RMS) interpretation of free software is I usually ask first if they know what IP (Intellectual Property not Internet Protocol) is and what the difference is between that and other legals stuff like Copyright and Trademarks. Then I make sure we have the same definition about Software and what I mean with the word Public in the context of software. After that I define GPL as: Obligatory Public Intellectual Property Software If the non-techie is still interested, I'll rave on about that I understand why GPL is a good way to ensure availability of IP especially if the software is a collaborated effort in the academic scene. And that I probably use that if I made software for my employer (a Foundation founded by multiple High-Schools) but that deeply personal I'll stick to the beerware license, because I fully agree on PHK license vision. -- mph From JHoover at fbi.gov Mon Nov 7 20:24:47 2005 From: JHoover at fbi.gov (Gordon Airporte) Date: Mon, 07 Nov 2005 20:24:47 -0500 Subject: Returning a value from a Tk dialog Message-ID: <0qqdnfVlLqpIYPLenZ2dnUVZ_tudnZ2d@comcast.com> The dialogs in tkColorChooser, tkFileDialog, etc. return useful values from their creation somehow, so I can do stuff like this: filename = tkFileDialog.askopenfilename( master=self ) I would like to make a Yes/No/Cancel dialog that can be used the same way (returning 1/0/-1), but I just cannot figure out how to do it. At best I've been able to get some kind of instance id from the object. How does this work? From NtOrSoPzAzMo at arcor.de Thu Nov 10 11:48:11 2005 From: NtOrSoPzAzMo at arcor.de (Mike T.) Date: Thu, 10 Nov 2005 17:48:11 +0100 Subject: PySol --> SuSE 10.0 Message-ID: <437379cd$0$7419$9b4e6d93@newsread4.arcor-online.net> Hi, I'm trying to install PySol on 10.0. I've tried two routes: the RPM and building from source. First, from RPM. I su'd to root and run the following: linuxdell:/home/mike # rpm -i pysol-4.82-1.noarch.rpm error: Failed dependencies: tkinter >= 2.2 is needed by pysol-4.82-1 Checking in Yast, it appears that tkinter is provided by python-tk (although I could be wrong): pyth_tk python_tkinter_lib pyth_tkl python-tkinter _tkinter.so _tkinter.so python-tk = 2.4.1-3 I also have python-devel and tk-devel installed. Trying from source, I was told I first needed to install pysol-sound-server3.01. I did that, and then attempted to install pysol: linuxdell:/home/mike/pysol-4.82/src # python pysol.py Traceback (most recent call last): File "pysol.py", line 121, in ? sys.exit(main(sys.argv)) File "/home/mike/pysol-4.82/src/main.py", line 424, in main r = pysol_main(args) File "/home/mike/pysol-4.82/src/main.py", line 367, in pysol_main r = pysol_init(app, args) File "/home/mike/pysol-4.82/src/main.py", line 91, in pysol_init app.dataloader = DataLoader(args[0], f) File "/home/mike/pysol-4.82/src/util.py", line 186, in __init__ raise os.error, str(argv0) + ": DataLoader could not find " + str(filenames) OSError: pysol.py: DataLoader could not find ('html/license.html',) Nowhere in the extracted files were there html files. I also downloaded pysol-4.80, which supposedly didn't need to be compiled. Checking these extracted files, html/license.html did indeed exist. So, attempting to install 4.80: linuxdell:/home/mike/pysol-4.80 # ll total 51 drwxrwxrwx 3 mike users 240 2001-11-28 03:36 . drwxr-xr-x 44 mike users 2360 2005-11-07 23:54 .. -rw-r--r-- 1 mike users 18094 1998-09-07 11:00 COPYING drwxr-xr-x 17 mike users 712 2001-11-28 03:36 data -rw-r--r-- 1 mike users 262 2000-08-02 21:23 INSTALL -rw-r--r-- 1 mike users 1276 2001-11-28 03:31 Makefile -rw-r--r-- 1 mike users 254 2000-08-02 21:23 NEWS -rwxr-xr-x 1 mike users 2624 2001-06-22 17:02 pysol -rw-r--r-- 1 mike users 6808 2001-11-28 03:36 pysol.6 -rw-r--r-- 1 mike users 1241 2001-09-10 12:07 README linuxdell:/home/mike/pysol-4.80 # ./pysol ./pysol: could not find the file 'pysol_24.pyc' ! Has anyone run across this sort of problem or could please advise me as to how I can get this to work? Thanks, Mike username=trozzo domain=arcor(dot)de From eternalsquire at comcast.net Thu Nov 10 00:29:39 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 9 Nov 2005 21:29:39 -0800 Subject: Python obfuscation In-Reply-To: References: <1131564878.074210.74640@z14g2000cwz.googlegroups.com> Message-ID: <1131600579.626993.146040@g47g2000cwa.googlegroups.com> Two things: 1) The decrypted modules should only reside in RAM, never in virtual memory. Those RAM locations should be rendered inaccessible to Python code. 2) Only sell to an honest customer willing to be locked into nondisclosure agreements. This goes back to the maxim of good salesmanship: Know Your Customer. By definition, a lock keeps honest people out. The object of a lock is to make it too expensive for all but the most dishonest, desperate, or nihilistic to get into the house, because they can always smash a window or a door open. IMHO, I have never encountered a dishonest developer or business owner who at the same time possessed anything remotely resembling a rational business model. A person who cannot afford to get tools honestly is seldom able to accomplish anything significant or constructive from a business point of view with tools obtained dishonestly. Consider EDA software like Cadence, Matlab, or BEACON that is guarded by network license servers. The temptation is very strong for an individual to rip it off, but then consider all the user technical support and bug fixes that go into the package. Most relatively honest people see a strong lock and get the message not to try. The others who may rip off a locked package, but then the package becomes worthless not because it doesn't work, but because the thief has to work completely outside the knowledge base that an honest copy has access to. I have heard of the warez culture, but it seems to be nihilistic in the extreme. I don't search for warez, I don't touch warez, and I do not recommend anyone else to do so, because using it is simply bad business practice and will get one ostracised by the very people one wants to sell to. But at the end of the day it seems to serve as an unauthorized marketing and sales channel to whet the appetites for people to try the real thing. The Eternal Squire From zach at in.tu-clausthal.de Thu Nov 10 16:43:53 2005 From: zach at in.tu-clausthal.de (Gabriel Zachmann) Date: Thu, 10 Nov 2005 22:43:53 +0100 Subject: different binding behavior Message-ID: It seems to me that the following behavior of python (2.4.1) is inconsistent: >>> a=1 >>> b=a >>> a+=1 >>> b 1 >>> a 2 >>> a=[1,2] >>> b=a >>> b+=[3] >>> a [1, 2, 3] >>> b [1, 2, 3] Why was it implemented like this?? Best regards, Gabriel. -- /-----------------------------------------------------------------------\ | Any intelligent fool can make things bigger, more complex, | | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \-----------------------------------------------------------------------/ From gdamjan at gmail.com Wed Nov 23 22:56:42 2005 From: gdamjan at gmail.com (Damjan) Date: Thu, 24 Nov 2005 04:56:42 +0100 Subject: ANNOUNCE: Mod_python 3.2.5 Beta References: <20051123102324.A63699@grisha.dyndns.org> Message-ID: > The Apache Software Foundation and The Apache HTTP Server Project are > pleased to announce the 3.2.5 Beta release mod_python. http://www.modpython.org/live/mod_python-3.2.5b/doc-html/hand-pub-alg-auth.html says "Since functions cannot be assigned attributes,..." But that's not true (at least in 2.3 and 2.4): >>> def f(): ... return 'a' ... >>> f.__auth__ = {1:'one'} -- damjan From bokr at oz.net Tue Nov 22 22:51:37 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 23 Nov 2005 03:51:37 GMT Subject: Anyway to clarify this code? (dictionaries) References: <1132711108.860281.59900@g49g2000cwa.googlegroups.com> Message-ID: <4383e5be.512914622@news.oz.net> On 22 Nov 2005 17:58:28 -0800, "javuchi" wrote: >I've been searching thru the library documentation, and this is the >best code I can produce for this alogorithm: > >I'd like to return a dictionary which is a copy of 'another' dictionary >whoes values are bigger than 'x' and has the keys 'keys': > >def my_search (another, keys, x): > temp = another.fromkeys(keys) > return dict([[k,v] for k in temp.keys() for v in temp.values() >if v>=x]) > >Is there any way to improve this code? >I want to avoid converting the dictionary to a list and then to a >dictionay. Are there speed penalties for such a conversion? > >Bye. > >>> another = dict(zip('abcd', iter(random.random, 2))) >>> import random >>> another = dict(zip('abcd', iter(random.random, 2))) >>> for k,v in another.items(): print k,v ... a 0.606494662034 c 0.273998760342 b 0.358066029098 d 0.774406432218 If keys are few compared to the number of keys in another, this may be prefereable: >>> def my_search(another, keys, x): return dict((k,another[k]) for k in keys if another[k]>x) ... >>> my_search(another, 'cb', .3) {'b': 0.35806602909756235} >>> my_search(another, 'abcd', .4) {'a': 0.60649466203365532, 'd': 0.77440643221840166} This sounds like homework though ... ? Regards, Bengt Richter From aleax at mail.comcast.net Sun Nov 6 16:24:09 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 6 Nov 2005 13:24:09 -0800 Subject: Learning multiple languages (question for general discussion) References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> <1h5hs5y.19u42x51mo5hupN%aleax@mail.comcast.net> <7xvez5wvgc.fsf@ruckus.brouhaha.com> Message-ID: <1h5lwip.5hvbkr1ehtjydN%aleax@mail.comcast.net> Paul Rubin wrote: > aleax at mail.comcast.net (Alex Martelli) writes: > > I can't imagine NOT getting enthusiastic and stimulated by reading Van > > Roy and Hariri's book -- it IS quite as good and readable as SICP. > > It's been on my want-to-read list for a long time. I have the > downloaded draft edition (from before the print edition came out) and > it looks quite good. The Oz language has some interesting approaches. Yep. In particular, it's designed to support a wide variety of programming paradigms, and the book gradually explains, uses and compares and contrasts them all. > > Ruby's also blessed with good books (and the excellent Rails, too). > > I haven't been terribly interested in Ruby; it may have a more > rigorous OO approach than Python, but Smalltalk already did that > decades ago. So Ruby seems like yet another Perl-like language. Am I > missing something? I don't think Ruby is all that perl-like, despite some legacy things that work like Perl (e.g., the global $_) but are mostly starting to get deprecated in today's Ruby. Compared to Smalltalk, Ruby has much more Python-like syntax, the rough equivalent of Python's property, and the same ability as Python or Perl to "infiltrate niches" versus Smalltalk's typical insistence that "It is the world" (workspaces &c). Oh, and a reasonable approach to 'mixin' multi-inheritance which, as far as I recall, Smalltalk didn't have (at least not back when I studied it). If I had to nominate one Ruby feature that is particularly interesting, it would be the way in which any method (==function) can take a block of code and 'yield' values to it. Besides supporting uses similar to today Python's generators (whose 'yield' sort of "goes the other way"...), that also affords the functionality of stuff that will be introduced only with Python 2.5 ('with' statement, 'yield' returning a value...). While Ruby and Python essentially overlap on all dimensions, doing just about the same things with often very similar code, I think there are enough differences in detail to make studying Ruby interesting. > Do you have any opinion of "Types and Programming Languages" by > Pierce? Autrijus Tang (the guy who started PUGS, the Perl 6 Sorry, no opinion there. Alex From carsten at uniqsys.com Tue Nov 22 14:51:45 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 22 Nov 2005 14:51:45 -0500 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: <1132689105.7399.60.camel@dot.uniqsys.com> On Tue, 2005-11-22 at 14:37, Christoph Zwerschke wrote: > In Foord/Larosa's odict, the keys are exposed as a public member which > also seems to be a bad idea ("If you alter the sequence list so that it > no longer reflects the contents of the dictionary, you have broken your > OrderedDict"). That could easily be fixed by making the sequence a "managed property" whose setter raises a ValueError if you try to set it to something that's not a permutation of what it was. > d1[0] + d1[2] ==> OrderedDict( (1, 11), (3, 13) ) What do you think you're doing here? -Carsten From http Fri Nov 4 19:06:45 2005 From: http (Paul Rubin) Date: 04 Nov 2005 16:06:45 -0800 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> <7xk6fovb1t.fsf@ruckus.brouhaha.com> Message-ID: <7xpspgvtyi.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > A basic usage case: > > class Paper: > size = A4 > def __init__(self, contents): > # it makes no sense to have class contents, > # so contents go straight into the instance > self.contents = contents So add: self.size = Paper.size and you've removed the weirdness. What do you gain here by inheriting? From pink at odahoda.de Mon Nov 14 16:36:55 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 14 Nov 2005 22:36:55 +0100 Subject: Making a persistent HTTP connection References: <4378e5bb$0$2103$edfadb0f@dtext02.news.tele.dk> <3tsdvaFugk4lU2@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > David Rasmussen wrote: >> I use urllib2 to do some simple HTTP communication with a web server. In >> one "session", I do maybe 10-15 requests. It seems that urllib2 opens op >> a connection every time I do a request. Can I somehow make it use _one_ >> persistent connection where I can do multiple GET->"receive data" passes >> before the connection is closed? > > Are you sure HTTP supports that? This would be news to me - which > doesn't mean much :) It does (HTTP/1.1 at least) and it's called 'keep-alive'. > And even if it works - what is the problem with connections being created? Performance, network load... -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From kent37 at tds.net Mon Nov 21 18:07:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Nov 2005 18:07:39 -0500 Subject: Web-based client code execution In-Reply-To: <43813CB6.4030209@redlinepy.com> References: <3u6ngeFvh3v1U1@individual.net> <43813CB6.4030209@redlinepy.com> Message-ID: <43825093$1_3@newspeer2.tds.net> Paul Watson wrote: > My desire to have the code distributed through a web page is just to > ensure that the user is running the correct version and has not hacked > it in any way. I suppose I can checksum the local client application > and compare it with what is on the server. Then, make a way to > update... ARGH! I have used Java Web Start to distribute Jython applications from a web page. There are a few glitches getting it set up but then it works well. Solves 'ensure that the user is running the correct version' nicely. Not sure if it protects against hacking. My Jython and Web Start recipe is here: http://personalpages.tds.net/~kent37/Python/JythonWebStart.html Kent From fredrik at pythonware.com Wed Nov 30 13:23:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 30 Nov 2005 19:23:36 +0100 Subject: Computer Language Shootout References: <1133298307.938958.186070@f14g2000cwb.googlegroups.com><438d1bfd.271765047@news.oz.net> <1133371620.645281.73590@g43g2000cwa.googlegroups.com> Message-ID: igouy at yahoo.com wrote: > "Be Nice!" *is* one of paragraph headings in the FAQ section "How can I > help?" yeah, we've noticed that it's not one of the headings in the FAQ section "How can we encourage you to contribute". From jwkenne at attglobal.net Wed Nov 2 22:20:05 2005 From: jwkenne at attglobal.net (John W. Kennedy) Date: Wed, 02 Nov 2005 22:20:05 -0500 Subject: Microsoft Hatred FAQ In-Reply-To: References: <1129826863.422951.146970@g49g2000cwa.googlegroups.com> <5l1rl1dt2vj6lanvbfue4pglv1kkgl1qn9@4ax.com> <11lsopl4qpg9gc2@corp.supernews.com> Message-ID: entropy wrote: > steve at REMOVETHIScyber.com.au wrote... > >>On Tue, 25 Oct 2005 16:54:13 +0000, John Wingate wrote: >> >> >>>Steven D'Aprano wrote: >>> >>>>That would be a good guess, except that Microsoft's predatory and illegal >>>>behaviour began long before OS/2 was even planned. It began in the mid >>>>1970s, with MS DOS. >>> >>>Nitpick: MS-DOS first appeared in 1981. >> >>[slaps head] >> >>Of course it did. > > > The first thing I ever bought of Microsoft's, in 1982 or so, was a > CP/M board for my Apple IIe. > > CP/M, whose programmers to this day defend sticking with 8-bit CPUs > because 'they can't find a 4-bit chip they like'. Yeah, there's some > desktop innovation for you. > > OS/2 1.0 was released in 1987, but the "selling" of it started in > 1985 or so by IBM and Microsoft. It was a 286 OS. Only to the extent that IBM promised a protected-mode operating system in 1984, when the PC-AT came out. > IBM seems to have had a history of squeezing out competition in the > same way Microsoft has, if I recall correctly. IBM was genuinely innovative, and did their best to provide value for money. Microsoft hasn't been able to produce anything but me-too products since the 80's. (Multiplan, Word for DOS, the QBASIC engine, early sponsorship of mouses, and the gutsy decision to morph MS-DOS 1.0, a CP/M quasi-clone, into DOS 2.0, a Unix quasi-clone, are about all I can give them credit for.) -- John W. Kennedy "Those in the seat of power oft forget their failings and seek only the obeisance of others! Thus is bad government born! Hold in your heart that you and the people are one, human beings all, and good government shall arise of its own accord! Such is the path of virtue!" -- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis) From amhoov at gmail.com Wed Nov 23 20:25:57 2005 From: amhoov at gmail.com (amhoov@yahoo.com) Date: 23 Nov 2005 17:25:57 -0800 Subject: wxPython installation issues on Debian Message-ID: <1132795557.301034.92000@o13g2000cwo.googlegroups.com> Hi all, I'm trying to install wxPython on Debian using 'apt-get install python-wxgtk2.4.' I've got both Python 2.3 and 2.4 installed with 2.4 set as my default. For whatever reason, wxPython always installs under /usr/lib/python2.3/site-packages. Does anyone know how I can force it to install in 2.4's site-packages directory? Thanks, Aaron From steve at REMOVETHIScyber.com.au Wed Nov 9 11:37:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 10 Nov 2005 03:37:26 +1100 Subject: how to modify code while debugging it without having to stop and then restart debugger References: Message-ID: On Tue, 08 Nov 2005 13:38:28 -0500, python wrote: > thanks for all that have replied so far. > i still find it __very__ hard to believe that i cannot edit code inside a function while debugging it. You write a function: def myfunct(s): # input arg s is a string foo = s*3 bar = s.upper() + foo # LINE 2 blob = foo.lower() + bar return blob You enter the debugger and single-step to the marked line LINE 2. Then you edit the code to this: def myfunct(n): # input arg n is an int foo = n + 1 bar = foo*2 # LINE 2 blob = foo**bar return blob What should Python do when you step the debugger, and why is it useful? > as i mentioned even micro$soft can do this using statically type languages like visual basic and csharp. > also, both visualbasic and csharp have goto statements, which i do to not use in final code but can be real handy when > used with the ability to change debugged code on the fly while inside the function being debugged. Better and better. Yes, I can see how the ability to jump around a function on the fly would really help you understand how the function is supposed to work when you take the gotos out. > for example, > if i am inside a function and there is some an error on a line and that is where the debugger is currently pointing at, > i simple copy and paste the bad code line just below the actual code line. > i fix this copied code line. > then i just turn the bad line into a comment line and the debugger will move the current focus to the next time, which > is the fixed code. > > how can such a dynamic language like python not be able to do this. Do you try to ignore the syntax and grammar of the programming language you are coding in too, or only English? [snip] >> there are several applications that can do this. >> in fact, the free version of the visual studio 2005, which is free, have this ability. Just out of curiosity, how much is the free version of Visual Studio 2005? -- Steven. From bonono at gmail.com Tue Nov 8 00:02:11 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 7 Nov 2005 21:02:11 -0800 Subject: problem generating rows in table In-Reply-To: <1131424393.303923.263380@g43g2000cwa.googlegroups.com> References: <1131424393.303923.263380@g43g2000cwa.googlegroups.com> Message-ID: <1131426131.137849.320690@o13g2000cwo.googlegroups.com> len(toprint) -1 seems to be 0 so it seems that the loops are skipped ? why not just : for x in toprint: for y in x: print "%s" % y these suffix things are very prone to error. s99999999s2003 at yahoo.com wrote: > hi > i wish to generate a table using cgi > toprint = [('nickname', 'justme', 'someplace')] > print ''' > > > > > > > ''' > > for i in range(0,len(toprint)-1): > for j in range(0,len(toprint[0])-1): > print "" % toprint[i][j] > > print ''' >
UserNameAddress
%s
''' > > but it only prints out a table with "User | Name | address" > it didn't print out the values of toprint > > is there mistake in code? please advise > thanks From aleax at mail.comcast.net Wed Nov 16 19:25:10 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 16 Nov 2005 16:25:10 -0800 Subject: best way to discover this process's current memory usage, cross-platform? References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132080864.280909.51540@g44g2000cwa.googlegroups.com> <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> <1132121442.019702.66620@g47g2000cwa.googlegroups.com> <1132166050.888977.101350@g44g2000cwa.googlegroups.com> Message-ID: <1h64n58.dew0mo1pu14zmN%aleax@mail.comcast.net> sjdevnull at yahoo.com wrote: ... > Neal Norwitz wrote: > > Here's a really screwy thought that I think should be portable to all > > Unixes which have dynamic linking. LD_PRELOAD. > > > > You can create your own version of malloc (and friends) and free. You > > intercept each call to malloc and free (by making use of LD_PRELOAD), > > keep track of the info (pointers and size) and pass the call along to > > the real malloc/free. You then have all information you should need. > > That'll only get you memory usage from malloc/free calls, which could > be vastly less than the process' memory usage in plausible scenarios > (e.g. a media player that uses mmap() to read the file, or anything > that uses large shared memory segments generated with mmap() or SysV > IPC, etc). True. But hopefully a cross-platform program's memory leaks will mostly be based on malloc (it couldn't use SysV's IPC and still be cross-platform, for example; and while mmap might be a possibility, perhaps it might be tracked by a similar trick as malloc might). > In the real world, malloc() and mmap() are probably sufficient to get a > good picture of process usage for most processes. But I guess defining > exactly what counts as the process' current memory would be a starting > place (specifically how to deal with shared memory). Considering that the main purpose is adding regression tests to confirm that a hopefully-fixed memory leak does not recur, I'm not sure why shared memory should be a problem. What scenarios would "leak shared memory"? If some shared library gets loaded once and stays in memory that doesn't appear to me as something that would normally be called "a memory leak" -- unless I'm failing to see some cross-platform scenario that would erroneously re-load the same library over and over again, taking up growing amounts of shared memory with time? Alex From fredrik at pythonware.com Thu Nov 3 01:52:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Nov 2005 07:52:15 +0100 Subject: Nested List Question References: <1130995475_2055@spool6-east.superfeed.net> Message-ID: "Newsfeeds" wrote: > Could anyone tell me why this code produces the output it does? http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list has the full story. From steve at REMOVETHIScyber.com.au Mon Nov 28 17:12:22 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 29 Nov 2005 09:12:22 +1100 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> <86lkz8vh34.fsf@bhuda.mired.org> Message-ID: On Mon, 28 Nov 2005 12:05:03 -0500, Mike Meyer wrote: > Steven D'Aprano writes: >> On Mon, 28 Nov 2005 10:02:19 +0100, Sybren Stuvel wrote: >>> Duncan Booth enlightened us with: >>>> I would have thought that no matter how elaborate the checking it is >>>> guaranteed there exist programs which are correct but your verifier >>>> cannot prove that they are. >>> Yep, that's correct. I thought the argument was similar to the proof >>> that no program (read: Turing machine) can determine whether a program >>> will terminate or not. >> No, that is not right -- it is easy to create a program to determine >> whether *some* programs will terminate, but it is impossible to create a >> program which will determine whether *all* programs will terminate. > > Which means you can't create a verifier which will verify all > programs. I thought that's what I said originally *wink* > Is there a reason to believe that you can't have a verifier > with three possible outcomes: Correct, Incorrect, and I don't know, > and it is always correct in doing so? Note that "I don't know" could > be "I ran longer than I think is reasonable and gave up trying." That seems perfectly reasonable to me. I don't know about anyone else in this discussion, but I'm talking about *theoretical* source code verification of formal correctness. In *practice*, I don't know what the state of the art is, but I suspect it will be a long, long time before it is as easy as running "import mymodule; verify(mymodule)". -- Steven. From rnd at onego.ru Wed Nov 2 16:30:21 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 2 Nov 2005 23:30:21 +0200 (EET) Subject: reading internet data to generate random numbers. In-Reply-To: <11mi8n2t39q2534@corp.supernews.com> References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> Message-ID: On Wed, 2 Nov 2005, Grant Edwards wrote: > On 2005-11-02, Levi Campbell wrote: > >> Hi, I'm working on a random number generator using the internet as a >> way to gather entropy, I have two questions. So far interesting. >> 1. is there a way to capture the internet stream? Most news sites provide RSS and/or ATOM feeds these days. Or maybe you mean video/audio stream from Internet stations? (not sure how much entropy such a stream could contain: probably depends on the genre ;-) Or perhaps you mean low-level Ethernet/TCP/IP "stream"? Then it is not original and I already saw answers with recomendations. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From bdesth.quelquechose at free.quelquepart.fr Sat Nov 12 21:00:02 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 Nov 2005 03:00:02 +0100 Subject: Multikey Dict? In-Reply-To: <437682b5$0$2108$edfadb0f@dtext02.news.tele.dk> References: <437682b5$0$2108$edfadb0f@dtext02.news.tele.dk> Message-ID: <437693de$0$21678$626a54ce@news.free.fr> David Rasmussen a ?crit : > If I have a collection of dicts like: > > john = {'id': 1, 'name': "John Cleese", 'year': 1939} > graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} > > I could store all of them in a list. But for easy lookup, I might store > all these in a dict instead, like > > people = {'1': john, '2': graham} > or maybe > > people = {'John Cleese': john, 'Graham Chapman': graham} You can use integers as keys in a dict. And building an index is not that difficult: peoples = [ {'id': 1, 'name': "John Cleese", 'year': 1939}, {id': 2, 'name': "Graham Chapman", 'year': 1941}, ] peoples_name_idx = dict((p['name'], p) for p in peoples) peoples_id_idx = dict((p['id'], p) for p in peoples) which generalize to: def mk_index(index_field, records): return dict((rec[index_field], rec) for rec in records) (snip) > would like to be able to say: > people['1'].year > > in some case and in other cases I want to say > people['John Cleese'].year This should be: people['John Cleese']['year'] (If you want transform your dicts to objects so you use dotted notation, there are recipes for this in the Python Cookbook.) > If I could just say to Python: john and graham (and ...) are all a part > of a "superdict" and either their id or their name can be used as keys. > > Can I do that somehow? Writing a dict-like object is quite easy. Look for UserDict, or directly subclass Dict. Now, how could the "superdict" implementation decide which key to use ? Here, you have a numeric 'id' and a string 'name', so you could test on it in __getitem__, but what if you want to use 2 different string keys? Computers are usually very bad at guessing, that's why we are programming them. My 2 cents From steve at REMOVETHIScyber.com.au Wed Nov 16 06:09:21 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 16 Nov 2005 22:09:21 +1100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <437A9596.6020006@REMOVEMEcyber.com.au> Message-ID: On Tue, 15 Nov 2005 21:59:44 -0500, Roy Smith wrote: > In article <437A9596.6020006 at REMOVEMEcyber.com.au>, > Steven D'Aprano wrote: > >> try: >> for item in obj: >> do_stuff(item) >> except TypeError, msg: >> if msg == "iteration over non-sequence": >> handle_non_iterator() >> else: >> # re-raise the exception >> raise > > That's the obvious solution, but it's a poor one because it depends on an > undocumented feature of the language. What's documented is that TypeError > is raised; it's not documented what the text of the message will be. It would be nice if The Powers That Be would document the specific error messages, so that we could rely on them in total safety. But even without that, the consequences aren't especially dire. What happens if the error message changes in some future version of Python? Then the error won't be caught, the exception will be re-raised, and your testing will catch it immediately. It isn't the ideal solution, but it is a solution. -- Steven. From tim.golden at viacom-outdoor.co.uk Tue Nov 8 08:28:01 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 8 Nov 2005 13:28:01 -0000 Subject: Pywin32: How to import data into Excel? Message-ID: <9A28C052FF32734DACB0A288A3533991044D22FE@vogbs009.gb.vo.local> [Tim Golden] > + When trying to automate anything in Excel, it's > usually illuminating to record a macro which does > what you want, and then to translate that VBA code > into Python. > [Duncan Booth] > Another suggestion: when automating Excel, turn off the automatic > recalculation (set Application.Calculation=xlManual) and then turn it back > on again when you have finished. > If you don't do this, Excel will attempt to recalculate the sheet after > every update to a cell. Even if you don't have any formulae referencing the > cells you change it still makes a big difference. Thanks. Didn't know that. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tony.meyer at gmail.com Mon Nov 21 00:18:28 2005 From: tony.meyer at gmail.com (Tony Meyer) Date: Mon, 21 Nov 2005 18:18:28 +1300 Subject: python-dev Summary for 2005-10-16 through 2005-10-31 Message-ID: <6c63de570511202118t7747899y9eec468be48d2cac@mail.gmail.com> [The HTML version of this Summary will be available at http://www.python.org/dev/summary/2005-10-16_2005-10-31.html] ============= Announcements ============= -------------- AST for Python -------------- As of October 21st, Python's compiler now uses a real Abstract Syntax Tree (AST)! This should make experimenting with new syntax much easier, as well as allowing some optimizations that were difficult with the previous Concrete Syntax Tree (CST). While there is no Python interface to the AST yet, one is intended for the not-so-distant future. Thanks again to all who contributed, most notably: Armin Rigo, Brett Cannon, Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Neil Schemenauer, Nick Coghlan and Tim Peters. Contributing threads: - `AST branch merge status < http://mail.python.org/pipermail/python-dev/2005-October/057347.html>`__ - `AST branch update < http://mail.python.org/pipermail/python-dev/2005-October/057387.html>`__ - `AST branch is in? < http://mail.python.org/pipermail/python-dev/2005-October/057483.html>`__ - `Questionable AST wibbles < http://mail.python.org/pipermail/python-dev/2005-October/057489.html>`__ - `[Jython-dev] Re: AST branch is in? < http://mail.python.org/pipermail/python-dev/2005-October/057642.html>`__ [SJB] -------------------- Python on Subversion -------------------- As of October 27th, Python is now on Subversion! The new repository is http://svn.python.org/projects/. Check the `Developers FAQ`_ for information on how to get yourself setup with Subversion. Thanks again to Martin v. L?wis for making this possible! .. _Developers FAQ: http://www.python.org/dev/devfaq.html#subversion-svn Contributing threads: - `Migrating to subversion < http://mail.python.org/pipermail/python-dev/2005-October/057424.html>`__ - `Freezing the CVS on Oct 26 for SVN switchover < http://mail.python.org/pipermail/python-dev/2005-October/057537.html>`__ - `CVS is read-only < http://mail.python.org/pipermail/python-dev/2005-October/057679.html>`__ - `Conversion to Subversion is complete < http://mail.python.org/pipermail/python-dev/2005-October/057690.html>`__ [SJB] --------------- Faster decoding --------------- M.-A. Lemburg checked in Walter D?rwald's patches that improve decoding speeds by using a character map. These should make decoding into mac-roman or iso8859-1 nearly as fast as decoding into utf-8. Thanks again guys! Contributing threads: - `Unicode charmap decoders slow < http://mail.python.org/pipermail/python-dev/2005-October/057341.html>`__ - `New codecs checked in < http://mail.python.org/pipermail/python-dev/2005-October/057505.html>`__ - `KOI8_U (New codecs checked in) < http://mail.python.org/pipermail/python-dev/2005-October/057576.html>`__ [SJB] ========= Summaries ========= --------------------- Strings in Python 3.0 --------------------- Guido proposed that in Python 3.0, all character strings would be unicode, possibly with multiple internal representations. Some of the issues: - Multiple implementations could make the C API difficult. If utf-8, utf-16 and utf-32 are all possible, what types should the C API pass around? - Windows expects utf-16, so using any other encoding will mean that calls to Windows will have to convert to and from utf-16. However, even in current Python, all strings passed to Windows system calls have to undergo 8 bit to utf-16 conversion. - Surrogates (two code units encoding one code point) can slow indexing down because the number of bytes per character isn't constant. Note that even though utf-32 doesn't need surrogates, they may still be used (and must be interpreted correctly) in utf-32 data. Also, in utf-32, "graphemes" (which correspond better to the traditional concept of a "character" than code points do) may still be composed of multiple code points, e.g. "?" (e with a accent) can be written as "e" + "'". This last issue was particularly vexing -- Guido thinks "it's a bad idea to offer an indexing operation that isn't O(1)". A number of proposals were put forward, including: - Adding a flag to strings to indicate whether or not they have any surrogates in them. This makes indexing O(1) when no surrogates are in a string, but O(N) otherwise. - Using a B-tree instead of an array for storage. This would make all indexing O(log N). - Discouraging using the indexing operations by providing an alternate API for strings. This would require creating iterator-like objects that keep track of position in the unicode object. Coming up with an API that's as usable as the slicing API seemed difficult though. Contributing thread: - `Divorcing str and unicode (no more implicit conversions). < http://mail.python.org/pipermail/python-dev/2005-October/057362.html>`__ [SJB] ------------------- Unicode identifiers ------------------- Martin v. L?wis suggested lifting the restriction that identifiers be ASCII. There was some concern about confusability, with the contention that confusions like "O" (uppercase O) for "0" (zero) and "1" (one) for "l" (lowercase L) would only multiply if larger character sets were allowed. Guido seemed less concerned about this problem than about about how easy it would be to share code across languages. Neil Hodgson pointed out that even though a transliteration into English exists for Japanese, the coders he knew preferred to use relatively meaningless names, and Oren Tirosh indicated that Israeli programmers often preferred transliterations for local business terminology. In either case, with or without unicode identifiers the code would already be hard to share. In the end, people seemed mostly in favor of the idea, though there was some suggestion that it should wait until Python 3.0. Contributing threads: - `Divorcing str and unicode (no more implicit conversions). < http://mail.python.org/pipermail/python-dev/2005-October/057362.html>`__ - `i18n identifiers (was: Divorcing str and unicode (no more implicit conversions). < http://mail.python.org/pipermail/python-dev/2005-October/057812.html>`__ - `i18n identifiers < http://mail.python.org/pipermail/python-dev/2005-October/057813.html>`__ [SJB] ----------------- Property variants ----------------- People still seem not quite pleased with properties, both in the syntax, and in how they interact with inheritance. Guido proposed changing the property() builtin to accept strings for fget, fset and fdel in addition to functions (as it currently does). If strings were passed, the property() object would have late-binding behavior, that is, the function to call wouldn't be looked-up until the attribute was accessed. Properties whose fget, fset and fdel functions can be overridden in subclasses might then look like:: class C(object): foo = property('getFoo', 'setFoo', None, 'the foo property') def getFoo(self): return self._foo def setFoo(self, foo): self._foo = foo There were mixed reactions to this proposal. People liked getting the expected behavior in subclasses, but it does violate DRY (Don't Repeat Yourself). I posted an `alternative solution`_ using metaclasses that would allow you to write properties like:: class C(object): class foo(Property): """The foo property""" def get(self): return self._foo def set(self, foo): self._foo = foo which operates correctly with subclasses and follows DRY, but introduces a confusion about the referrent of "self". There were also a few suggestions of introducing a new syntax for properties (see `Generalizing the class declaration syntax`_) which would have produced things like:: class C(object): Property foo(): """The foo property""" def get(self): return self._foo def set(self, foo): self._foo = foo At the moment at least, it looks like we'll be sticking with the status quo. .. _alternative solution: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418 Contributing threads: - `Definining properties - a use case for class decorators? < http://mail.python.org/pipermail/python-dev/2005-October/057350.html>`__ - `Defining properties - a use case for class decorators? < http://mail.python.org/pipermail/python-dev/2005-October/057407.html>`__ - `properties and block statement < http://mail.python.org/pipermail/python-dev/2005-October/057419.html>`__ - `Property syntax for Py3k (properties and block statement) < http://mail.python.org/pipermail/python-dev/2005-October/057427.html>`__ [SJB] ------------------- PEP 343 resolutions ------------------- After Guido accepted the idea of adding a __with__() method to the context protocol, `PEP 343`_ was reverted to "Proposed" until the remaining details could be ironed out. The end results were: - The slot name "__context__" will be used instead of "__with__". - The builtin name "context" is currently offlimits due to its ambiguity. - Generator-iterators do NOT have a native context. - The builtin function "contextmanager" will convert a generator-function into a context manager. - The "__context__" slot will NOT be special cased. If it defines a generator, the __context__() function should be decorated with @contextmanager. - When the result of a __context__() call returns an object that lacks an __enter__() or __exit__() method, an AttributeError will be raised. - Only locks, files and decimal.Context objects will gain __context__() methods in Python 2.5. Guido seemed to agree with all of these, but has not yet pronounced on the revised `PEP 343`_. .. _PEP 343: http://www.python.org/peps/pep-0343.html Contributing threads: - `PEP 343 updated < http://mail.python.org/pipermail/python-dev/2005-October/057349.html>`__ - `Proposed resolutions for open PEP 343 issues < http://mail.python.org/pipermail/python-dev/2005-October/057516.html>`__ - `PEP 343 - multiple context managers in one statement < http://mail.python.org/pipermail/python-dev/2005-October/057637.html>`__ - `PEP 343 updated with outcome of recent discussions < http://mail.python.org/pipermail/python-dev/2005-October/057769.html>`__ [SJB] --------------- Freeze protocol --------------- Barry Warsaw propsed `PEP 351`_, which suggests a freeze() builtin which would call the __freeze__() method on an object if that object was not hashable. This would allow dicts to automatically make frozen copies of mutable objects when they were used as dict keys. It could reduce the need for "x" and "frozenx" builtin pairs, since the frozen versions could be automatically derived when needed. Raymond Hettinger indicated some problems with the proposal: - sets.Set supported something similar, but found that it was not really helpful in practice. - Freezing a list into a tuple is not appropriate since they do not have all the same methods. - Errors can arise when the mutable object gets out of sync with its frozen copy. - Manually freezing things when necessary is relatively simple. Noam Raphael proposed a copy-on-change mechanism which would essentially give frozen copies of an object a reference to that object. When the object is about to be modified, a copy would be made, and all frozen copies would be pointed at this. Thus an object that was mutable but never changed could have lightweight frozen copies, while an object that did change would have to pay the usual copying costs. Noam and Josiah Carlson then had a rather heated debate about how feasible such a copy-on-change mechanism would be for Python. .. _PEP 351: http://www.python.org/peps/pep-0351.html Contributing thread: - `PEP 351, the freeze protocol < http://mail.python.org/pipermail/python-dev/2005-October/057543.html>`__ [SJB] ---------------------------------- Required superclass for Exceptions ---------------------------------- Guido and Brett Cannon introduced `PEP 352`_ which proposes that all Exceptions be required to derive from a new exception class, BaseException. The chidren of BaseException would be KeyboardInterrupt, SystemExit and Exception (which would contain the remainder of the current hierarchy). The goal here is to make the following code do the right thing:: try: ... except Exception: ... Currently, this code fails to catch string exceptions and other exceptions that do not derive from Exception, and it (probably) inappropriately catches KeyboardInterrupt and SystemExit which are supposed to indicate that Python is shutting down. The current plan is to introduce BaseException and have KeyboardInterrupt and SystemExit multiply inherit from Exception and BaseException. The PEP lists the roadplan for deprecating the various other types of exceptions. The PEP also attempts to standardize on the arguments to Exception objects, so that by Python 3.0, all Exceptions will support a single argument which will be stored as their "message" attribute. Guido was ready to accept it on October 31st, but it has not been marked as Accepted yet. .. _PEP 352: http://www.python.org/peps/pep-0352.html Contributing threads: - `PEP 352: Required Superclass for Exceptions < http://mail.python.org/pipermail/python-dev/2005-October/057736.html>`__ - `PEP 352 Transition Plan < http://mail.python.org/pipermail/python-dev/2005-October/057750.html>`__ [SJB] ----------------------------------------- Generalizing the class declaration syntax ----------------------------------------- Michele Simionato suggested a generalization of the class declaration syntax, so that:: : would be translated into:: = ("", , ) Where is simply the namespace that results from executing . This would actually remove the need for the class keyword, as classes could be declared as:: type : There were a few requests for a PEP, but nothing has been made available yet. Contributing thread: - `Definining properties - a use case for class decorators? < http://mail.python.org/pipermail/python-dev/2005-October/057435.html>`__ [SJB] -------------------- Task-local variables -------------------- Phillip J. Eby introduced a pre-PEP proposing a mechanism similar to thread-local variables, to help co-routine schedulers to swap state between tasks. Essentially, the scheduler would be required to take a snapshot of a coroutine's variables before a swap, and restore that snapshot when the coroutine is swapped back. Guido asked people to hold off on more PEP 343-related proposals until with-blocks have been out in the wild for at least a release or two. Contributing thread: - `Pre-PEP: Task-local variables < http://mail.python.org/pipermail/python-dev/2005-October/057464.html>`__ [SJB] ----------------------------------------- Attribute-style access for all namespaces ----------------------------------------- Eyal Lotem proposed replacing the globals() and locals() dicts with "module" and "frame" objects that would have attribute-style access instead of __getitem__-style access. Josiah Carlson noted that the first is already available by doing ``module = __import__(__name__)``, and suggested that monkeying around with function locals is never a good idea, so adding additional support for doing so is not useful. Contributing threads: - `Early PEP draft (For Python 3000?) < http://mail.python.org/pipermail/python-dev/2005-October/057251.html>`__ [SJB] --------------------------------- Yielding all items of an iterator --------------------------------- Gustavo J. A. M. Carneiro was looking for a nicer way of indicating that all items of an iterable should be yielded. Currently, you probably want to use a for-loop to express this, e.g.:: for step in animate(win, xrange(10)): # slide down yield step Andrew Koenig suggested that the syntax:: yield from be equivalent to:: for i in x: yield i People seemed uncertain as to whether or not there were enough use cases to merit the additional syntax. Contributing thread: - `Coroutines, generators, function calling < http://mail.python.org/pipermail/python-dev/2005-October/057405.html>`__ [SJB] ----------------------------------------- Getting an AST without the Python runtime ----------------------------------------- Thanks to the merging of the AST branch, Evan Jones was able to fully divorce the Python parse from the Python runtime so that you can get AST objects without having to have Python running. He made the divorced AST parser available on `his site`_. .. _his site: http://evanjones.ca/software/pyparser.html Contributing thread: - `Parser and Runtime: Divorced! < http://mail.python.org/pipermail/python-dev/2005-October/057684.html>`__ [SJB] =============== Skipped Threads =============== - `Pythonic concurrency - offtopic < http://mail.python.org/pipermail/python-dev/2005-October/057294.html>`__ - `Sourceforge CVS access < http://mail.python.org/pipermail/python-dev/2005-October/057342.html>`__ - `Weekly Python Patch/Bug Summary < http://mail.python.org/pipermail/python-dev/2005-October/057343.html>`__ - `Guido v. Python, Round 1 < http://mail.python.org/pipermail/python-dev/2005-October/057366.html>`__ - `Autoloading? (Making Queue.Queue easier to use) < http://mail.python.org/pipermail/python-dev/2005-October/057368.html>`__ - `problem with genexp < http://mail.python.org/pipermail/python-dev/2005-October/057370.html>`__ - `PEP 3000 and exec < http://mail.python.org/pipermail/python-dev/2005-October/057380.html>`__ - `Pythonic concurrency - offtopic < http://mail.python.org/pipermail/python-dev/2005-October/057442.html>`__ - `enumerate with a start index < http://mail.python.org/pipermail/python-dev/2005-October/057459.html>`__ - `list splicing < http://mail.python.org/pipermail/python-dev/2005-October/057479.html>`__ - `bool(iter([])) changed between 2.3 and 2.4 < http://mail.python.org/pipermail/python-dev/2005-October/057481.html>`__ - `A solution to the evils of static typing and interfaces? < http://mail.python.org/pipermail/python-dev/2005-October/057485.html>`__ - `PEP 267 -- is the semantics change OK? < http://mail.python.org/pipermail/python-dev/2005-October/057506.html>`__ - `DRAFT: python-dev Summary for 2005-09-01 through 2005-09-16 < http://mail.python.org/pipermail/python-dev/2005-October/057508.html>`__ - `int(string) (was: DRAFT: python-dev Summary for 2005-09-01 through 2005-09-16) < http://mail.python.org/pipermail/python-dev/2005-October/057510.html>`__ - `LXR site for Python CVS < http://mail.python.org/pipermail/python-dev/2005-October/057511.html>`__ - `int(string) < http://mail.python.org/pipermail/python-dev/2005-October/057512.html>`__ - `Comparing date+time w/ just time < http://mail.python.org/pipermail/python-dev/2005-October/057514.html>`__ - `AST reverts PEP 342 implementation and IDLE starts working again < http://mail.python.org/pipermail/python-dev/2005-October/057528.html>`__ - `cross compiling python for embedded systems < http://mail.python.org/pipermail/python-dev/2005-October/057534.html>`__ - `Inconsistent Use of Buffer Interface in stringobject.c < http://mail.python.org/pipermail/python-dev/2005-October/057589.html>`__ - `Reminder: PyCon 2006 submissions due in a week < http://mail.python.org/pipermail/python-dev/2005-October/057618.html>`__ - `MinGW and libpython24.a < http://mail.python.org/pipermail/python-dev/2005-October/057624.html>`__ - `make testall hanging on HEAD? < http://mail.python.org/pipermail/python-dev/2005-October/057662.html>`__ - `"? operator in python" < http://mail.python.org/pipermail/python-dev/2005-October/057673.html>`__ - `[Docs] MinGW and libpython24.a < http://mail.python.org/pipermail/python-dev/2005-October/057693.html>`__ - `Help with inotify < http://mail.python.org/pipermail/python-dev/2005-October/057705.html>`__ - `[Python-checkins] commit of r41352 - in python/trunk: . Lib Lib/distutils Lib/distutils/command Lib/encodings < http://mail.python.org/pipermail/python-dev/2005-October/057780.html>`__ - `svn:ignore < http://mail.python.org/pipermail/python-dev/2005-October/057783.html>`__ - `svn checksum error < http://mail.python.org/pipermail/python-dev/2005-October/057790.html>`__ - `svn:ignore (Was: [Python-checkins] commit of r41352 - in python/trunk: . Lib Lib/distutils Lib/distutils/command Lib/encodings) < http://mail.python.org/pipermail/python-dev/2005-October/057793.html>`__ - `StreamHandler eating exceptions < http://mail.python.org/pipermail/python-dev/2005-October/057798.html>`__ - `a different kind of reduce... < http://mail.python.org/pipermail/python-dev/2005-October/057814.html>`__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from October 16, 2005 through October 31, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the 6th summary written by the python-dev summary dyad of Steve Bethard and Tony Meyer (more thanks!). To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com ) - Tony Meyer (tony.meyer at gmail.com ) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/2005-09-16_2005-09-30.html .. _original text file: http://www.python.org/dev/summary/2005-10-16_2005-10-31.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgporter at acm.org Tue Nov 22 19:21:44 2005 From: bgporter at acm.org (Brett g Porter) Date: Tue, 22 Nov 2005 19:21:44 -0500 Subject: [Fwd: Re: hex string to hex value] In-Reply-To: <4383AE55.2050905@skynet.be> References: <4383AE55.2050905@skynet.be> Message-ID: <4383B618.9000000@acm.org> tim wrote: > > I end up with 66 again, back where I started, a decimal, right? > I want to end up with 0x42 as being a hex value, not a string, so i can > pas it as an argument to a function that needs a hex value. > (i am trying to replace the 0x42 in the line midi.note_off(channel=0, > note=0x42) with a variable) As far as Python is concerned, 66 decimal and 42 hex are exactly the same thing. There's absolutely no difference in calling note_off(0x42) and note_off(66) See: >>> def f(c): ... print c ... >>> f(66) 66 >>> f(0x42) 66 >>> -- // Today's Oblique Strategy (? Brian Eno/Peter Schmidt): // Repetition is a form of change // Brett g Porter * BgPorter at acm.org From steve at ferg.org Fri Nov 25 10:33:17 2005 From: steve at ferg.org (Steve) Date: 25 Nov 2005 07:33:17 -0800 Subject: How to get started in GUI Programming? References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132932797.213901.35850@o13g2000cwo.googlegroups.com> > Can anyone offer any suggestions as to the least painful way forwards? http://www.ferg.org/easygui/index.html From fgeiger at datec.at Wed Nov 2 05:59:11 2005 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 2 Nov 2005 11:59:11 +0100 Subject: tachometer diagram References: <1130753253.564379.63190@g47g2000cwa.googlegroups.com> Message-ID: Could it be http://xoomer.virgilio.it/infinity77/eng/freeware.html#speedmeter you are looking for? HTH Franz GEIGER "Andreas Kaiser" schrieb im Newsbeitrag news:1130753253.564379.63190 at g47g2000cwa.googlegroups.com... > Hello, > > I'am searching for a python solution for display a tachometer diagram. > I prefer a solution for wxPython. > The plot libraries I've found do not implement this diagram type. > Any hints welcome! > > Thanks > Andreas > From cito at online.de Tue Nov 29 17:30:45 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 29 Nov 2005 23:30:45 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <438ca42e.241094455@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <1132735254.039468.106660@g44g2000cwa.googlegroups.com> <4385b7b6.632202659@news.oz.net> <4389193a.8914908@news.oz.net> <438ca42e.241094455@news.oz.net> Message-ID: I had the same idea to create a py.test to verify and compare various implementations. The doctests in odict.py are nice, but you can't use them for this purpose and they may not test enough. It would be also good to have something for testing and comparing performance. -- Christoph From steve at REMOVETHIScyber.com.au Tue Nov 15 05:53:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 15 Nov 2005 21:53:23 +1100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <11ni1sddrhsm03d@corp.supernews.com> <1132048673.702127.307450@g47g2000cwa.googlegroups.com> Message-ID: On Tue, 15 Nov 2005 01:57:53 -0800, Ben Sizer wrote: >> I don't think I even understand what the objection is. What is >> needed is a code fragment that shows how the use of strings is >> untenable. > > myObject.value = 'value1' > > #... 100 lines of code elided... > > if myObject.value = 'Value1': > do_right_thing() > else: > do_wrong_thing() > > > I don't actually think string use is 'untenable', but it is definitely > more error-prone. With some sort of named object on the right hand side > you will at least get a helpful NameError. It is moments like this that I'm not too proud to admit I learnt some good techniques from Pascal: # define some pseudo-constants RIGHT_THING = 'value1' WRONG_THING = 'some other value' INCHES_TO_FEET = 12 CM_TO_METRES = 100 # ... myObject.value = RIGHT_THING #... 100 lines of code elided... if myObject.value = RIGHT_THING: do_right_thing() else: do_wrong_thing() It isn't always appropriate or necessary to define "constants" (and I sometimes wish that Python would enforce assign-once names), but they can help avoid some silly mistakes. -- Steven. From devlai at gmail.com Mon Nov 7 21:08:44 2005 From: devlai at gmail.com (Devan L) Date: 7 Nov 2005 18:08:44 -0800 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> Message-ID: <1131415724.099700.235380@f14g2000cwb.googlegroups.com> Gustav H?llberg wrote: > I tried finding a discussion around adding the possibility to have > optional underscores inside numbers in Python. This is a popular option > available in several "competing" scripting langauges, that I would love > to see in Python. > > Examples: > 1_234_567 > 0xdead_beef > 3.141_592 > > Would appreciate if someone could find a pointer to a previous > discussion on this topic, or add it to a Python-feature-wishlist. > > - Gustav I'm not sure what the _s are for, but I'm guessing they serve as separators ("." or "," depending on where you're from). I think the _s look ugly to me, besides, underscores look more like spaces than separators. From aleax at mail.comcast.net Wed Nov 23 22:25:47 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 19:25:47 -0800 Subject: (newbie) N-uples from list of lists References: <1132776015.567869.214570@g14g2000cwa.googlegroups.com> <1132799696.603772.323700@g44g2000cwa.googlegroups.com> <1132801693.407770.215630@g43g2000cwa.googlegroups.com> Message-ID: <1h6huuv.3o2ah01wodl9qN%aleax@mail.comcast.net> bonono at gmail.com wrote: > Out of curiousity, is "recursion" the desirable way(or is it pythonic > way) ? How would one do it in the imperative way ? For an inherently recursive problem (as this one appears to be), the traditional alternative to recursion is maintaining your own LIFO stack. If (with all the obvious refactorings) things gets messy, ah well, at least you've broken free of the recursion limit;-). [[ Sometimes (rarely) things don't get messy, and then you find out that the problem wasn't really "inherently recursive";-) ]] An example of recursion elimination in Python can be found at Alex From drochom at googlemail.com Mon Nov 21 10:01:32 2005 From: drochom at googlemail.com (drochom) Date: 21 Nov 2005 07:01:32 -0800 Subject: duplicate items in a list In-Reply-To: References: Message-ID: <1132585292.021266.219470@g47g2000cwa.googlegroups.com> http://groups.google.com/group/comp.lang.python/browse_thread/thread/32e545ebba11dd4d/49a9f0cc799cc1f1#49a9f0cc799cc1f1 From mwm at mired.org Thu Nov 24 13:32:40 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 13:32:40 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <43850a7a$0$8074$9b622d9e@news.freenet.de> <868xvex8d6.fsf@bhuda.mired.org> Message-ID: <86veyhx5fb.fsf@bhuda.mired.org> Christoph Zwerschke writes: >>>- Because sets can only contain immutable values > > Mike Meyer wrote: > >> Not true. Sets can only contain *hashable* objects, which isn't the >> same thing. > > I trusted the doco which defines a set as "an unordered collection of > immutable values" (http://docs.python.org/lib/types-set.html). If the hash changes, you've screwed up the set. What it really should say is "collection of objects with fixed hashes", or words to that effect. Do you want to file a PR on this? > Anyway, the problems stays the same. How so? As I demonstrated, you can subclass any class that doesn't have a hash to add one, and then use the subclass, which - except for having a hash - will have exactly the same behavior as your original class. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From lycka at carmen.se Tue Nov 22 10:06:51 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 22 Nov 2005 16:06:51 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <438258f2.411334718@news.oz.net> Message-ID: Christoph Zwerschke wrote: > I still believe that the concept of an "ordered dictionary" ("behave > like dict, only keep the order of the keys") is intuitive and doesn't > give you so much scope for ambiguity. Sure. Others think so too. The problem is that if you and these other people actually write down exactly how this unambigous ordered dict should behave, you'll end up with a dozen different sets of semantics, which can be divided in at least three main groups. People use different idioms, and often gather collections of classes and functions that fit their style of coding and their typical problem domains. There is nothing wrong with that, and they might well be made publically available if they are more generally useful. When adding things to the standard library, there are some more things to consider, particularly for something general such as an odict class: Is is general enough, and does it add enough value to outweigh the increased cognitive burden of more classes/functions/types in the library? For a beginner, it's easy to believe that things would be easier if the tool you use had already solved the problem you have at hand for you, but it turns out that the world has so many problems, that you would end up with a impenetrable forest of standard library modules if we actually tried to achieve this. From rrr at ronadam.com Mon Nov 7 21:51:12 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 08 Nov 2005 02:51:12 GMT Subject: Newbie Alert: Help me store constants pythonically In-Reply-To: <1131412583.285926.185740@g49g2000cwa.googlegroups.com> References: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> <436EDDA8.5020600@REMOVEMEcyber.com.au> <1131412583.285926.185740@g49g2000cwa.googlegroups.com> Message-ID: Brendan wrote: >>How many is LOOONG? Ten? Twenty? One hundred? > > > About 50 per Model > > >>If it is closer to 100 than to 10, I would suggest >>putting your constants into something like an INI file: >> >>[MODEL1] # or something more meaningful >>numBumps: 1 >>sizeOfBumps: 99 >> >>[MODEL2] >>numBumps: 57 >>sizeOfBumps: 245 It looks to me like you may want a data file format that can be used by various tools if possible. A quick search for 3d file formats finds the following list. If any of these are close to what you need you may have an additional benefit of ready made tools for editing. http://astronomy.swin.edu.au/~pbourke/dataformats/ > which I'm not sure the .ini format can easily support. I could use > (key buzzword voice) XML, but I fear that might send me down the > 'overcomplicating things' path. Your suggestion has given me some new > places to search Google (configparser, python config files), so I'll > look around for better ideas. > > Brendan One approach is to just store them as Python dictionaries. Then just import it and use it where it's needed. # models.py M1 = dict( numBumps=1, sizeOfBumps=2, transversePlanes=[ dict(type=3, z=4), dict(type=5, z=6), dict(type=3, z=8) ] ) M2 = ... Then in your application... # makemodels.py import models class Model(object): def __init__( self, numBumps=None, sizOfBumps=None, transversePlanes=None ): self.numBumps = numBumps self.sizeOfBumps = sizeOfBumps self.transversePlanes = [] for p in tranversePlanes: self.transversePlanes.append(Plane(**p)) mod1 = Model(**models.M1) This may be good to use until you decide how else to do it. You can easily write the dictionaries to a text file in the chosen format later and that will tell you what you need to do to read the file back into the dictionaries as it will just be reversed. Cheers, Ron From p at ulmcnett.com Wed Nov 30 20:18:15 2005 From: p at ulmcnett.com (Paul McNett) Date: Wed, 30 Nov 2005 17:18:15 -0800 Subject: wxPython installation issues on Debian In-Reply-To: References: <1132795557.301034.92000@o13g2000cwo.googlegroups.com> <1133373197.812027.135740@g44g2000cwa.googlegroups.com> <1133388676.563922.55190@g14g2000cwa.googlegroups.com> <438E4984.1010804@ulmcnett.com> Message-ID: <438E4F57.2000305@ulmcnett.com> Robert Kern wrote: > Although Ubuntu is a Debian derivative, it does have different packages. > At the moment, Debian's default Python is 2.3 although one can also > install Python 2.4, and most Python packages in Debian have been built > for both (that's why I erroneously recommended installing the apparently > nonexistant python2.4-wxgtk2.4). However, it appears that the maintainer > of the Debian wxPython is not building packages for both Python 2.3 and > 2.4. The maintainer of the Ubuntu wxPython package apparently is. As far as I know, the maintainer of the wxPython package is the same (Ron) and Ubuntu just uses the upstream wxPython from Debian. However, I see above that you are referencing wxPython 2.4 and not 2.6. It is very possible that for wxPython 2.4, there is only a Python 2.3 package. wxPython 2.4 is obsolete. If possible, wxPython 2.6 should be used. But, I don't know if it is available for Python 2.4 under Debian (or Ubuntu, for that matter). -- Paul McNett http://paulmcnett.com http://dabodev.com From bobueland at yahoo.com Sun Nov 20 02:38:11 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 19 Nov 2005 23:38:11 -0800 Subject: Where can I find string.translate source? Message-ID: <1132472291.390282.82380@g43g2000cwa.googlegroups.com> The module string has a function called translate. I tried to find the source code for that function. In: C:\Python24\Lib there is one file called string.py I open it and it says """A collection of string operations (most are no longer used). Warning: most of the code you see here isn't normally used nowadays. Beginning with Python 1.6, many of these functions are implemented as methods on the standard string object. They used to be implemented by a built-in module called strop, but strop is now obsolete itself.""" Inside the file string.py I couldn't find the source code for translate. Where could it be? From cito at online.de Tue Nov 22 13:54:18 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 19:54:18 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <43835452.475686410@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <43835452.475686410@news.oz.net> Message-ID: Bengt Richter wrote: > I'm mostly friendly ;-) I'm pretty sure you are :-) -- Chris From martin at v.loewis.de Mon Nov 21 23:58:11 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 22 Nov 2005 05:58:11 +0100 Subject: bsddb185 question In-Reply-To: <1132611401.426797.143120@g47g2000cwa.googlegroups.com> References: <1132611401.426797.143120@g47g2000cwa.googlegroups.com> Message-ID: <4382a563$0$8870$9b622d9e@news.freenet.de> thakadu wrote: > So it seems I am forced to use the bsddb185 module > which does not have convenient record level methods. > Am I missing something here or have others eperienced > tha same? I think you are missing that bsddb185 implements the dictionary interface. So you can use [key] to access the value for a certain key. Regards, Martin From lycka at carmen.se Tue Nov 8 03:25:42 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 08 Nov 2005 09:25:42 +0100 Subject: python server In-Reply-To: <1131387737.953307.178470@g44g2000cwa.googlegroups.com> References: <1131387737.953307.178470@g44g2000cwa.googlegroups.com> Message-ID: linuxpld wrote: > I`m writing a program (server in future) in python. > I would like to write it in such a way that I will be able to write gui > in any language and connect to my python program and use functionality > included with it. > are there any libraries that I could use? Thee are many solutions. An XML-RPC server springs to mind as a solution. There are several Python XML-RPC servers, and clients for a wide range of languages, see: http://xmlrpc.scripting.com/directory/1568/implementations Plain sockets can work of course, but that's fairly low level: You'll need to device a protocol etc. For more possible solutions, see http://www.thinkware.se/cgi-bin/thinki.cgi/UsingPythonWithOtherLanguages From lycka at carmen.se Tue Nov 1 08:17:40 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 01 Nov 2005 14:17:40 +0100 Subject: Need Python Pro for Help!! Plzz In-Reply-To: References: <5uSdnSSK7vYrTfneRVn-pQ@giganews.com> Message-ID: Ruben Charles wrote: > What is better? It's better if programs work by design and not just by accident. There is of course a risk that "experts" talk above the heads of newbies, and that newbies feel uncomfortable exposing their lack of knowledge to much better programmers, but I think the Tutor mailing list has shown over and over that it's quite possible for very good Python programmers to help complete newbies get up to speed with Python fairly quickly. So, the answer is still: Go to http://www.python.org/mailman/listinfo/tutor From smithsm at samuelsmith.org Tue Nov 15 17:59:16 2005 From: smithsm at samuelsmith.org (Samuel M. Smith) Date: Tue, 15 Nov 2005 15:59:16 -0700 Subject: Configure failing why? In-Reply-To: References: Message-ID: <2C428E8C-2B20-42C7-962A-C6D786235EAE@samuelsmith.org> cat > foo.cpp int main(){return 0;} c++ foo.cpp ll a.out -rwxr-xr-x 1 root tsarm 12124 Nov 15 15:54 a.out ./a.out but if I gcc foo.cpp ll a.out -rw-r--r-- 1 root tsarm 12060 Nov 15 15:55 a.out but if I do it again # gcc foo.cpp ll a.out -rwxr-xr-x 1 root tsarm 12060 Nov 15 15:58 a.out On 15 Nov, 2005, at 15:40, Fredrik Lundh wrote: > Samuel M. Smith wrote: > >> I am trying to build python2.4.2 on an arm 9 running Debian 3 Sarge > >> configure:1842: ./a.out >> ./configure: line 1: ./a.out: Permission denied >> configure:1845: $? = 126 >> configure:1854: error: cannot run C++ compiled programs. >> If you meant to cross compile, use `--host'. >> See `config.log' for more details. >> >> It appears that for some reason the a.out file that the configure >> script is making is not getting execute permissions enable by the >> configure script > > on a sane standard Unixoid system, the compiler is required to set the > following permission flags > > S_IRWXO | S_IRWXG | S_IRWXU > > if and only if the program was successfully compiled and linked. > > what happens if you do > > $ cat >foo.cpp > int main(){ return 0; } > $ c++ foo.cpp > $ ls -l a.out > > ? > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list ********************************************************************** Samuel M. Smith Ph.D. 2966 Fort Hill Road Eagle Mountain, Utah 84043 801-768-2768 voice 801-768-2769 fax ********************************************************************** "The greatest source of failure and unhappiness in the world is giving up what we want most for what we want at the moment" ********************************************************************** From Dennis.Benzinger at gmx.net Thu Nov 17 08:59:32 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Thu, 17 Nov 2005 14:59:32 +0100 Subject: searching for files on Windows with Python In-Reply-To: References: Message-ID: <437c8cc2$1@news.uni-ulm.de> Shane schrieb: > I've been giving Google a good workout with no luck. I would like to be able to search a Windows filesystem for filenames, returning a list off absolute paths to the found files, something like: > > def findFiles(filename, pathToSearch): > ... > ... > return foundFileNames > > Is the os module where I should start? > [...] Yes, especially the os.walk() function should help you. Bye, Dennis From fuzzyman at gmail.com Fri Nov 25 03:18:05 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Nov 2005 00:18:05 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> <1132828514.489889.7110@g44g2000cwa.googlegroups.com> <1132844756.190248.141870@g47g2000cwa.googlegroups.com> Message-ID: <1132906685.036452.180860@f14g2000cwb.googlegroups.com> Christoph Zwerschke wrote: > Fuzzyman schrieb: > > d.keys() will still return a copy of the list, so d.keys()[i] will > > still be slower than d.sequence[i] > > Right, I forgot that. Bengt suggested to implement __call__ as well as > __getitem__ and __setitem__ for keys, values and items. > > In this case, you could very effectively access it as d.values[i]. > That means making keys, values, and items custom objects. Creating a new instance would have the overhead of creating 4 new objects instead of just 1. Is the added convenience worth it ? (Plus the extra layers of method calls for each access). I'm not sure. It's a nice idea in terms of using it (we could just leave the sequence attribute as an alias for the new keys attribute - for backwards compatibility). All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -- Christoph From mwm at mired.org Fri Nov 4 18:20:56 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 04 Nov 2005 18:20:56 -0500 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: <86wtjof19j.fsf@bhuda.mired.org> Steven D'Aprano writes: > equal? Some things are a matter of objective fact: should CPython use a > byte-code compiler and virtual machine, or a 1970s style interpreter that > interprets the source code directly? For the record, I've only seen one interpreter that actually interpreted the source directly. Pretty much all of the rest of them do a lexical analysis, turning keywords into magic tokens (dare I say "byte codes") and removing as much white space as possible. Or maybe that's what you meant? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From courtneyboisseree at gmail.com Thu Nov 17 18:04:18 2005 From: courtneyboisseree at gmail.com (court) Date: 17 Nov 2005 15:04:18 -0800 Subject: PayPal co-founder looking for talented developers for his new venture!!! Message-ID: <1132268658.493081.224760@g14g2000cwa.googlegroups.com> Slide, ( http://www.slide.com ) the new SF startup founded by Max Levchin (who also founded PayPal, which sold to eBay for $1.5B) is seeking qualified candidates to help us change the way we share photos online! http://www.slide.com please send resumes to: jobs (at) slide (dot) com If you know of anyone in the job market, please send them to us! We've been looking high and low!! Thanks!!! From jepler at unpythonic.net Thu Nov 17 17:34:38 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 17 Nov 2005 16:34:38 -0600 Subject: Hashing Function In-Reply-To: <20051117194537.43512.qmail@web30609.mail.mud.yahoo.com> References: <20051117194537.43512.qmail@web30609.mail.mud.yahoo.com> Message-ID: <20051117223438.GF18024@unpythonic.net> As Fredrik suggests, consult the source to find out. Almost all of this is in the realm of being an implementation detail, and hashes aren't guaranteed to be the same from version to version or machine to machine. I'm not even sure they're guaranteed to be the same from run to run. Here's an example: On a 32-bit linux machine running python 2.3: $ python -c 'print hash("a" * 1000)' -884397280 On a 64-bit linux machine running python 2.4: $ python -c 'print hash("a" * 1000)' 2513399373082733344 A little more research suggests that, at least for strings, the hashing algrithm is unchanged from 1.5.2 to 2.4, but is dependant on the range of a platform 'long'. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From piet at cs.uu.nl Thu Nov 24 06:27:46 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 24 Nov 2005 12:27:46 +0100 Subject: Why are there no ordered dictionaries? References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383b600.500692667@news.oz.net> <4384DD77.9080303@online.de> Message-ID: >>>>> Christoph Zwerschke (CZ) escribi?: >CZ> Eso es exactamente lo que yo queria haber! ?Haber? ?Tener? :=( -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From PPNTWIMBXFFC at spammotel.com Mon Nov 7 04:00:48 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Mon, 07 Nov 2005 10:00:48 +0100 Subject: Notes 6.X not accessible with Python? Message-ID: Hi Since my upgrade from Notes 5.X to Notes 6.X I can't access Notes anymore. The third line of the following code is already a show stopper in my case: from win32com.client import Dispatch session = Dispatch('Lotus.NotesSession') session.Initialize('my_secret_passwort') When started, ends: File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\temp\notes_init.py", line 3, in ? session.Initialize('my_secret_passwort') File "c:\Python24\lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: Lotus.NotesSession.Initialize It worked before though with Version 5.x of Notes. In Notes Version 6.X they introduced the session.Initialize() - that was the point, when I couldn't create an instance anymore. I found no hint on the net... Do you have any idea what is going wrong here? Regards, Marco From kristian.zoerhoff at gmail.com Fri Nov 11 14:40:02 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Fri, 11 Nov 2005 13:40:02 -0600 Subject: odd behavior In-Reply-To: <1131737687.314760.265370@g44g2000cwa.googlegroups.com> References: <1131737687.314760.265370@g44g2000cwa.googlegroups.com> Message-ID: <3511dc750511111140v61f05073q9307b3893bd167f2@mail.gmail.com> On 11 Nov 2005 11:34:47 -0800, Greg wrote: > Forgive me, and be kind, as I am just a newby learning this language > out of M.L. Hetland's book. The following behavior of 2.4.1 seems very > strange > >>> x = ['aardvark', 'abalone', 'acme', 'add', > 'aerate'] > >>> x.sort(key=len) > >>> x > ['add', 'acme', 'aerate', 'abalone', 'aardvark'] > >>> x.sort(reverse=True) > >>> x > ['aerate', 'add', 'acme', 'abalone', 'aardvark'] > The function called on line 4, at least to me, should work on x as it > was on line 3, not the previously existing x on line 1. What gives? The key option defaults to an alphabetic sort *every time* you call sort, so if you want to change this, you must call for your sort key each time. To do what you want, roll the sorts into one step: >>> x.sort(key=len, reverse=True) >>> x ['aardvark', 'abalone', 'aerate', 'acme', 'add'] -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From erniedude at gmail.com Tue Nov 15 17:40:41 2005 From: erniedude at gmail.com (Ernesto) Date: 15 Nov 2005 14:40:41 -0800 Subject: Self terminate a python program Message-ID: <1132094441.225612.86000@g14g2000cwa.googlegroups.com> how do you self terminate a python program from within the code? something similar to exit(0) in C. I think the problem is that I'm using subprocess and popen to launch a '.exe' file and python is "waiting" on the .exe file to finish. since it never does, the python program won't end. how can I force it to end? From mhellwig at xs4all.nl Sun Nov 27 11:14:23 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sun, 27 Nov 2005 17:14:23 +0100 Subject: wxPython Licence vs GPL In-Reply-To: References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <4388385e$0$11063$e4fe514c@news.xs4all.nl> <4388c7f9$0$11080$e4fe514c@news.xs4all.nl> Message-ID: <4389db68$0$11062$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > On Sat, 26 Nov 2005 21:39:13 +0100, Martin P. Hellwig wrote: > >> The software was sold in 3 separates modules requiring a yearly renewal, > > The software is hardly sold if you have to renew that "sale" every year. > That's more like a lease. I'd call it revenue from licencing, not revenue > from sales. > > Of course you're welcome to describe it as sales. It is an arbitrary > choice one way or another -- the main thing is to not talk at > cross-purposes, as we obviously have been doing. > I agree -- mph From steve at holdenweb.com Mon Nov 7 14:00:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 Nov 2005 19:00:15 +0000 Subject: Lie Hetland book: Beginning Python.. In-Reply-To: References: Message-ID: Vittorio wrote: > I am reading "Beginning Python from Novice to Professional" and the book > is really awesome. Nonetheless on ch 13 "Database Support" I found this > code to import data (in a txt file) into a SQLite Database: > > #this was corrected because original "import sqlite" does not work > from pysqlite2 import dbapi2 as sqlite > > #this function strips the txt file from special chars > def convert(value): > if value.startswith('~'): > return value.strip('~') > if not value: > value = '0' > return float(value) > > conn = sqlite.connect('food.db') > curs = conn.cursor() > > curs.execute(''' > CREATE TABLE food ( > id TEXT PRIMARY KEY, > desc TEXT, > water FLOAT, > kcal FLOAT, > protein FLOAT, > fat FLOAT, > ash FLOAT, > carbs FLOAT, > fiber FLOAT, > sugar FLOAT > ) > ''') > > field_count = 10 > > #following is the line I suspect mistyped > markers = ', '.join(['%s']*field_count) > > query = 'INSERT INTO food VALUES (%s)' % markers > > > for line in open('ABBREV.txt'): > fields = line.split('^') > vals = [convert(f) for f in fields[:field_count]] > #the following line raises error > curs.execute(query,vals) > > conn.commit() > conn.close > > > The error was "Traceback (most recent call last): > File "C:\Python24\food.py", line 39, in ? > curs.execute(query,vals) > pysqlite2.dbapi2.OperationalError: near "%": syntax error" > > After two hours of trying (did I say I am a beginner?) and after some > documentation about PySqlite I suspect the error is in: > markers = ', '.join(['%s']*field_count) > > I think Magnus intended: > markers = ', '.join(['?']*field_count) > > > Did I found an errata or my Python is still too green? > > No, you actually did quite a creditable piece of debugging. The DB-API specifications allow database modules to substitute parameters into SQL commands in a number of different ways, and they are supposed to indicate the technique they use by setting a module variable "paramstyle" to one of five possible values. Magnus' original code was written to use a different (but valid) paramstyle, so I'm guessing that his sqlite module and your sqlite2 simply use different paramstyles. Whether that's because a change was made in developing the pysqlite code or because pysqlite and pysqlite2 come from different developers I couldn't say, but you have nailed the problem. Well done! 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 godoy at ieee.org Mon Nov 7 09:32:51 2005 From: godoy at ieee.org (Jorge Godoy) Date: 07 Nov 2005 12:32:51 -0200 Subject: Python and PL/SQL References: <1131369305.252487.30220@o13g2000cwo.googlegroups.com> <1131371902.061620.295920@g49g2000cwa.googlegroups.com> Message-ID: <87ek5s8r58.fsf@jupiter.g2ctech> Gerhard H?ring writes: > In my not so humble opinion, instead of all this fancy stuff, you will be > better off writing your stored procedures in PL/SQL, which is a very good > language for manipulating data, and writing portable, efficient and > maintainable server-side database code. And if Python is the requirement, but not Oracle, one can write "stored procedures" (functions is the name) in Python with PostgreSQL. ;-) -- Jorge Godoy From arkanes at gmail.com Mon Nov 14 08:57:37 2005 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 14 Nov 2005 07:57:37 -0600 Subject: extend In-Reply-To: <8c11e4350511140230i29652f71s176af02be130b828@mail.gmail.com> References: <8c11e4350511140230i29652f71s176af02be130b828@mail.gmail.com> Message-ID: <4866bea60511140557yf24b052v3349b160f23c1b29@mail.gmail.com> On 11/14/05, Ben Bush wrote: > is there any python code doing this: > there are two line segments (2x+y-1=0 with the coordinates of two ending > points are (1,-1) and (-1,3); > x+y+6=0 with the coordinates of two ending points are (-3,-3) and > (-4,-2);). They extend and when they meet each other, stop extending. > how can i use python to implement this in Tkinter? > > -- > Thanks! > Ben Bush > -- the comp.graphics.algorithms FAQ may be of use to you: http://cgafaq.info/wiki/Main_Page > http://mail.python.org/mailman/listinfo/python-list > > From apardon at forel.vub.ac.be Thu Nov 17 05:06:35 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Nov 2005 10:06:35 GMT Subject: GTK for windows and Linux References: <437c3560@news1.veridas.net> Message-ID: Op 2005-11-17, Ask schreef : > Hi All, > > Can someone please tell me what I need to use GTK with python for windows > and Linux? > > Any links to the appropriate installations would be greatly appreciated as I > don't know what I need... GIMP... GTK+ etc Well I think if you visit http://www.pygtk.org/, it will answer most of your questions. -- Antoon Pardon From tinman31337 at gmail.com Wed Nov 23 08:01:31 2005 From: tinman31337 at gmail.com (Tin Gherdanarra) Date: Wed, 23 Nov 2005 05:01:31 -0800 Subject: syntax errors while building pypgsql Message-ID: <3uj7hcF10k63tU1@individual.net> Hallo, I'm trying to install pypgsql. However, I get syntax errors while compiling the C sources. The following excerpt from pgconnection.h looks a little funny to me: typedef struct { PyObject_HEAD /* Here is the syntax error, and rightly so */ PGconn *conn; PyObject *host; PyObject *port; PyObject *db; PyObject *options; PyObject *tty; PyObject *user; PyObject *pass; PyObject *bePID; PyObject *socket; PyObject *version; PyObject *notices; PyObject *cinfo; int showQuery; } PgConnection; I don't know what PyObject_HEAD or PGconn is, but if they are types, a syntax error is justified here: PyObject_HEAD /* Here is the syntax error */ PGconn *conn; The setup.py-settings look good to me, I use debian sarge stable. Installation of PostgreSQL ran without any problems. From aleax at mail.comcast.net Fri Nov 25 12:29:59 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 25 Nov 2005 09:29:59 -0800 Subject: Why are there no ordered dictionaries? References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <1132531775.399671.93120@o13g2000cwo.googlegroups.com> <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383d564.508728452@news.oz.net> <1132735428.485669.153090@g43g2000cwa.googlegroups.com> <1h6h08u.5v642xndgfj2N%aleax@mail.comcast.net> <1132910022.308232.251080@o13g2000cwo.googlegroups.com> Message-ID: <1h6kscx.1c17n28m3w05N%aleax@mail.comcast.net> Fuzzyman wrote: ... > If you slice an ordered dictionary, I assume you would expect to get an > ordered dictionary back ? That would be helpful, yes, though there are precedents for types whose slicing doesn't return an instance of that type (e.g. slices of an mmap are instances of str, not of mmap, if I recall correctly), most sliceable sequences do follow that pattern. Alex From xray_alpha_charlie at yahoo.com Fri Nov 11 23:25:19 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Fri, 11 Nov 2005 20:25:19 -0800 (PST) Subject: how to think like a computer scientist Message-ID: <20051112042519.2673.qmail@web35913.mail.mud.yahoo.com> Question for the following program: sec 5.5 def factorial (n): if n == 0: return 1 else: recurse = factorial (n-1) result = n * recurse return result How come whenever I state the function with "n" given a value it prints no results in the interpreter for EX: def factorial (n): if n == 0: return 1 else: recurse = factorial (n-1) result = n * recurse return result factorial (3) So instead I have to give a "print" command to make the result appear in the interpreter for EX: def factorial (n): if n == 0: return 1 else: recurse = factorial (n-1) result = n * recurse return result print factorial(3) Is this correct....should I have to give a print command?? --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Tue Nov 1 20:33:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 01 Nov 2005 20:33:26 -0500 Subject: Importing Modules In-Reply-To: References: Message-ID: Walter Brunswick wrote: > What is the best way to import all modules in a directory > (and possibly a subdirectory/subdirectories), possibly including > conditionals, such as regexes? The "best" was, as always, depends on what your use case is. Why do you want to do this? What will you do with the modules once they are imported? Also: the second part of the question doesn't mean anything to me. What do you mean by "conditionals, such as regexes", in the context of importing modules? -Peter From jgrahn-nntq at algonet.se Wed Nov 9 15:44:41 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 9 Nov 2005 20:44:41 GMT Subject: where to download md5.py? References: <2387F0EED10A4545A840B231BBAAC722607F98@slcimail1.slcgov.com> Message-ID: On Wed, 2 Nov 2005 18:59:28 +0100, Fredrik Lundh wrote: > "Bell, Kevin" wrote: > >> I've been looking around, but haven't found a place to download the >> md5.py module. I need it to run the dupinator.py > > md5 is a standard Python module (written in C). it's been in Python since > the early ages, so if you don't have it, your install is most likely broken (per- > haps intentionally, based on this: http://eprint.iacr.org/2004/199 ) Intentionally breaking md5 in a Python installation that would be really, really stupid -- the md5 algorithm, is useful even if it's not cryptographically secure. (I understand that you don't /advocate/ ripping out module md5, of course). /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From fredrik at pythonware.com Tue Nov 29 13:05:56 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Nov 2005 19:05:56 +0100 Subject: newbie question concerning formatted output References: Message-ID: Thomas Liesner wrote: > i am having some hard time to format the output of my small script. I am > opening a file which containes just a very long string of hexdata > seperated by spaces. Using split() i can split this string into single > words and print them on stdout. So far so good. But i want to print always > three of them in a single line and after that a linebreak. > > So instead of: > > 3905 > 3009 > 0000 > 4508 > f504 > 0000 > 3707 > 5a07 > 0000 > etc... > > i'd like to have: > > 3905 3009 0000 > 4508 f504 0000 > 3707 5a07 0000 > etc... > > This is the codesnippet i am using: > > #!/usr/bin/python > > import string > inp = open("xyplan.nobreaks","r") > data = inp.read() > for words in data.split(): > print words > inp.close() > > Any hints? how about inp = open("xyplan.nobreaks","r") data = inp.read() import textwrap for line in textwrap.wrap(data, 15): print line From steve at REMOVETHIScyber.com.au Sat Nov 12 20:46:20 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 13 Nov 2005 12:46:20 +1100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> Message-ID: On Sat, 12 Nov 2005 18:59:39 +0100, Pierre Barbier de Reuille wrote: > First, I think it would be best to have a syntax to represent symbols. > Adding some special char before the name is probably a good way to > achieve that : $open, $close, ... are $ymbols. I think your chances of convincing Guido to introduce new syntax is slim to none. (Not quite zero -- he did accept @ for decorators.) I think symbols should simply be an immutable object, one with state and limited or no behaviour, rather than a brand new syntactical element. Being an object, you can reference them in whatever namespace you define them in. Personally, I think rather than adding a new language feature (...slim to none...) there is more hope of getting something like this added to the standard library: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 -- Steven. From duncan.booth at invalid.invalid Wed Nov 23 04:15:27 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Nov 2005 09:15:27 GMT Subject: sort the list References: Message-ID: Neil Hodgson wrote: >> Since no-one mentioned it and its a favourite of mine, you can use the >> decorate-sort-undecorate method, or "Schwartzian Transform" > > That is what the aforementioned key argument to sort is: a built-in > decorate-sort-undecorate. And crucially it is a built-in DSU which gets it right more often than naive DSU implementations. e.g. it is stable when you reverse the order: >>> lst = [[4,1],[4,2],[9,3],[5,4],[2,5]] >>> list(reversed([ x[-1] for x in sorted([ (x[0],x) for x in lst ]) ])) [[9, 3], [5, 4], [4, 2], [4, 1], [2, 5]] >>> l1 = list(lst) >>> l1.sort(key=operator.itemgetter(0), reverse=True) >>> l1 [[9, 3], [5, 4], [4, 1], [4, 2], [2, 5]] and it gets incomparable objects right: >>> lst = [4+1j, 4+2j, 9+3j, 5+4j, 2+5j] >>> [ x[-1] for x in sorted([ (x.real,x) for x in lst ]) ] Traceback (most recent call last): File "", line 1, in -toplevel- [ x[-1] for x in sorted([ (x.real,x) for x in lst ]) ] TypeError: no ordering relation is defined for complex numbers >>> l1 = list(lst) >>> l1.sort(key=operator.attrgetter('real')) >>> l1 [(2+5j), (4+1j), (4+2j), (5+4j), (9+3j)] >>> From rossreyes at rcn.com Sat Nov 19 06:10:45 2005 From: rossreyes at rcn.com (Ross Reyes) Date: Sat, 19 Nov 2005 06:10:45 -0500 Subject: what happens when the file begin read is too big for all lines to be read with "readlines()" Message-ID: <000b01c5ecf9$e3cc3530$a100a8c0@reyesr2> HI - Sorry for maybe a too simple a question but I googled and also checked my reference O'Reilly Learning Python book and I did not find a satisfactory answer. When I use readlines, what happens if the number of lines is huge? I have a very big file (4GB) I want to read in, but I'm sure there must be some limitation to readlines and I'd like to know how it is handled by python. I am using it like this: slines = infile.readlines() # reads all lines into a list of strings called "slines" Thanks for anyone who knows the answer to this one. From gregpinero at gmail.com Fri Nov 4 16:13:45 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Fri, 4 Nov 2005 16:13:45 -0500 Subject: Pythonwin - Word automation - Removing watermark not working In-Reply-To: <312cfe2b0511031655x22c866cdj8bd213d4d3be4ea7@mail.gmail.com> References: <312cfe2b0511031655x22c866cdj8bd213d4d3be4ea7@mail.gmail.com> Message-ID: <312cfe2b0511041313q6c2ba396u1d81b97089ff63e0@mail.gmail.com> Is there a different group/mailing list I should try? Does anyone know if there is a pythonwin group/list for example? On 11/3/05, Gregory Pi?ero wrote: > > I thought I'd take a shot and see if anyone knows the answer to this? I've > been stuck for a while now on this. > > Would anyone happen to know why this my function removewatermark() in this > code isn't working? I copied it from a Word macro I recorded and it did work > when I recorded the macro. When I run it the watermark doesn't go away. > > I've also attached the code in case the formatting gets messed up from the > email. > > > > import sys > import os > from win32com.client import gencache, constants > WORD='Word.Application' > False,True=0,-1 > > class Word: > def __init__(self): > self.app=gencache.EnsureDispatch(WORD) > self.app.Visible = 1 > self.app.DisplayAlerts = 0 > def open(self,doc): > self.app.Documents.Open(FileName=doc) > def removewatermark(self): > self.app.ActiveDocument.Sections(1).Range.Select() > self.app.ActiveWindow.ActivePane.View.SeekView = 9 # > wdSeekCurrentPageHeader > self.app.Selection.HeaderFooter.Shapes > ("PowerPlusWaterMarkObject1").Select() > self.app.Selection.Delete() > self.app.ActiveWindow.ActivePane.View.SeekView = 0 #wdSeekMainDocument > > > > Thanks, > > Greg > > -- > Gregory Pi?ero > Chief Innovation Officer > Blended Technologies > (www.blendedtechnologies.com ) > -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Mon Nov 28 22:15:44 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 28 Nov 2005 20:15:44 -0700 Subject: Death to tuples! In-Reply-To: <86acfov7zo.fsf@bhuda.mired.org> References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> <86acfov7zo.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Steven Bethard writes: > >>Dan Bishop wrote: >> >>>Mike Meyer wrote: >>> >>> >>>>Is there any place in the language that still requires tuples instead >>>>of sequences, except for use as dictionary keys? >>> >>>The % operator for strings. And in argument lists. >>>def __setitem__(self, (row, column), value): >>> ... >> >>Interesting that both of these two things[1][2] have recently been >>suggested as candidates for removal in Python 3.0. >>[1]http://www.python.org/dev/summary/2005-09-01_2005-09-15.html#string-formatting-in-python-3-0 >>[2]http://www.python.org/dev/summary/2005-09-16_2005-09-30.html#removing-nested-function-parameters > > #2 I actually mentioned in passing, as it's part of the general > concept of tuple unpacking. When names are bound, you can use a > "tuple" for an lvalue, and the sequence on the rhs will be "unpacked" > into the various names in the lvalue: > > for key, value = mydict.iteritems(): ... > a, (b, c) = (1, 2), (3, 4) > > I think of the parameters of a function as just another case of > this; any solution that works for the above two should work for > function paremeters as well. The difference is that currently, you have to use tuple syntax in functions, while you have your choice of syntaxes with normal unpacking:: py> def f(a, (b, c)): ... pass ... py> def f(a, [b, c]): ... pass ... Traceback ( File "", line 1 def f(a, [b, c]): ^ SyntaxError: invalid syntax py> a, (b, c) = (1, 2), (3, 4) py> a, [b, c] = (1, 2), (3, 4) py> a, [b, c] = [1, 2], (3, 4) py> a, [b, c] = [1, 2], [3, 4] Of course, the result in either case is still a tuple. So I do agree that Python doesn't actually require tuples in function definitions; just their syntax. STeVe From tuvas21 at gmail.com Fri Nov 11 15:34:37 2005 From: tuvas21 at gmail.com (Tuvas) Date: 11 Nov 2005 12:34:37 -0800 Subject: PIL- error message- cannot open libtiff.so.3 In-Reply-To: References: <1131732377.111363.249560@f14g2000cwb.googlegroups.com> Message-ID: <1131741277.570121.144340@g44g2000cwa.googlegroups.com> Oddly enough, that seems to have solved the problem. Duh. Take the simple solution first. Thanks for the wake up call! From http Tue Nov 29 23:12:34 2005 From: http (Paul Rubin) Date: 29 Nov 2005 20:12:34 -0800 Subject: python number handling - tiny encryption algorithm References: Message-ID: <7xek4ybwp9.fsf@ruckus.brouhaha.com> Kinsley Turner writes: > In my version, I end up with hugely long integers, which have obviously > not be constrained into the 4-byte unsigned longs that TEA is expecting. Yeah, Python promotes to long int now. The simplest way to do the 32-bit arithmetic you need is probably with the array module. From aisaac0 at verizon.net Wed Nov 23 21:56:10 2005 From: aisaac0 at verizon.net (David Isaac) Date: Thu, 24 Nov 2005 02:56:10 GMT Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <1132708265.941224.186550@g44g2000cwa.googlegroups.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:dm2b8b$p8n$02$1 at news.t-online.com... > You are in for a surprise here: You got that right! > >>> def empty(): > ... for item in []: > ... yield item > ... > >>> bool(empty()) > True Ouch. > >>> bool(iter([])) > True # python 2.3 and probably 2.5 > > >>> bool(iter([])) > False # python 2.4 Double ouch. I was relying on Python 2.4 behavior. What is the reasoning behind the changes? (Can you offer a URL to a discussion?) So, is the only way to test for an empty iterable to see if it can generate an item? I found this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413614 Seems like a reason to rely on sequences ... Thanks, Alan Isaac From thomasbartkus at comcast.net Thu Nov 3 12:31:38 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 3 Nov 2005 11:31:38 -0600 Subject: Python and MySQL References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: "Magnus Lycka" wrote in message news:dkdbov$s2b$1 at wake.carmen.se... > Thomas Bartkus wrote: > > But heck! Now I'm looking at the /usr/lib/python2.3/site-packages on a > > Mandrake Linux box. No [_mysql.] pyd here! Fewer files overall and while > > there are other file extensions, everything seems to have a corresponding > > [.py]. > > I suspect you might find _mysql.so there. If you find any .pyd files I > think you can safely remove them, since Windows DLLs work poorly in > Linux anyway. Aren't you starting to suspect that you don't really know > what you are talking about in this particular case? Yes! And thank you so much for pointing that out :-) Thomas Bartkus > Where is the pure > Python code that actually communicates with the database server? Have > you found a single line of code that actually does that? How does it > communicate? Isn't there an 'import _mysql' somewhere? Where is the > _mysql.py then? > > What's this? > http://cvs.sourceforge.net/viewcvs.py/mysql-python/MySQLdb/_mysql.c > > What's this doing in setup.py? > 'ext_modules': [ > Extension( > name='_mysql', > sources=['_mysql.c'], > include_dirs=include_dirs, > library_dirs=library_dirs, > libraries=libraries, > extra_compile_args=extra_compile_args, > extra_objects=extra_objects, > ), > ], From thakadu at gmail.com Tue Nov 22 08:41:54 2005 From: thakadu at gmail.com (thakadu) Date: 22 Nov 2005 05:41:54 -0800 Subject: bsddb185 question In-Reply-To: <4382a563$0$8870$9b622d9e@news.freenet.de> References: <1132611401.426797.143120@g47g2000cwa.googlegroups.com> <4382a563$0$8870$9b622d9e@news.freenet.de> Message-ID: <1132666914.659909.315550@g49g2000cwa.googlegroups.com> It seems it doesnt implement ALL of the dictionary interface though. dir({}) yields many more methods than dir(bsddb185.open(f)). So bsddb185 is missing many of the methods that I am used to in bsddb. I mentioned some above that are missing, pop() in particular would be useful in my situation but there are others as well. >From a java perspective I believe that its not possible to omit certain methods when implementing an interface, I am not sure about Python though. From mde at micah.elliott.name Wed Nov 16 15:29:12 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Wed, 16 Nov 2005 12:29:12 -0800 Subject: creating package question In-Reply-To: <1132169418.759267.265090@o13g2000cwo.googlegroups.com> References: <1132169418.759267.265090@o13g2000cwo.googlegroups.com> Message-ID: <20051116202912.GJ18475@kitchen.client.attbi.com> On Nov 16, erick_bodine at comcast.net wrote: > I have a package directory structure as follows > > root- > | > Common (contains __init__.py file) > WindowsComponents (contains __init__.py file) > ... > > I would like modules in the WindowsComponents directory to be able > to import some modules from the Common directory. So you now have a "Common" package. And it might contain a "mustard" module. > In my first pass, I was able to append sys.path ( > sys.path.append('../Common') ) in each module that wants to import > from Common, but this feels "clunky". Agreed. You probably want to avoid messing with sys.path whenever possible. > Is there a "standard"/"best" way to accomplish this? So "root" should already be on your sys.path/PYTHONPATH. Then in say file "root/WindowsComponents/spam.py": from Common import mustard ... mustard.attr More import info from Fredrik: http://effbot.org/zone/import-confusion.htm -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From Matt at sussex.ac.uk Fri Nov 18 10:08:07 2005 From: Matt at sussex.ac.uk (Matt at sussex.ac.uk) Date: Fri, 18 Nov 2005 15:08:07 +0000 Subject: Newbie question. Pyexpat fails on make Message-ID: <1132326487.437dee57de0f4@webmail.sussex.ac.uk> Hi I want to build pyexpat and link it statically in Python. Im using Python 2.4.2. This is just a straight forward build using ./configure and then make I change *shared* to *static* and then uncoment these two lines: EXPAT_DIR=/usr/local/src/expat-1.95.2 pyexpat pyexpat.c -DHAVE_EXPAT_H -I$(EXPAT_DIR)/lib -L$(EXPAT_DIR) -lexpat The directory /usr/local/src/expat-1.95.2 doesn't exist so I assume I need to change it to the expat dir. One question will the libexpat.a library be built and is this the one refered to -lexpat? Modules/pyexpat.c: In function `call_with_frame': Modules/pyexpat.c:387: warning: implicit declaration of function `XML_StopParser' Modules/pyexpat.c:387: error: `XML_FALSE' undeclared (first use in this function) Modules/pyexpat.c:387: error: (Each undeclared identifier is reported only once Modules/pyexpat.c:387: error: for each function it appears in.) Modules/pyexpat.c: In function `my_ElementDeclHandler': Modules/pyexpat.c:777: warning: implicit declaration of function `XML_FreeContentModel' Modules/pyexpat.c: In function `initpyexpat': Modules/pyexpat.c:1966: error: `XML_ERROR_ENTITY_DECLARED_IN_PE' undeclared (first use in this function) Modules/pyexpat.c:1967: error: `XML_ERROR_FEATURE_REQUIRES_XML_DTD' undeclared (first use in this function) Modules/pyexpat.c:1968: error: `XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING' undeclared (first use in this function) Modules/pyexpat.c:1970: error: `XML_ERROR_UNBOUND_PREFIX' undeclared (first use in this function) Modules/pyexpat.c:1972: error: `XML_ERROR_UNDECLARING_PREFIX' undeclared (first use in this function) Modules/pyexpat.c:1973: error: `XML_ERROR_INCOMPLETE_PE' undeclared (first use in this function) Modules/pyexpat.c:1974: error: `XML_ERROR_XML_DECL' undeclared (first use in this function) Modules/pyexpat.c:1975: error: `XML_ERROR_TEXT_DECL' undeclared (first use in this function) Modules/pyexpat.c:1976: error: `XML_ERROR_PUBLICID' undeclared (first use in this function) Modules/pyexpat.c:1977: error: `XML_ERROR_SUSPENDED' undeclared (first use in this function) Modules/pyexpat.c:1978: error: `XML_ERROR_NOT_SUSPENDED' undeclared (first use in this function) Modules/pyexpat.c:1979: error: `XML_ERROR_ABORTED' undeclared (first use in this function) Modules/pyexpat.c:1980: error: `XML_ERROR_FINISHED' undeclared (first use in this function) Modules/pyexpat.c:1981: error: `XML_ERROR_SUSPEND_PE' undeclared (first use in this function) make: *** [Modules/pyexpat.o] Error 1 Im sure this is something stupid im doing. Assistance apprecited Cheers Matthew From steve at holdenweb.com Thu Nov 3 06:53:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Nov 2005 11:53:29 +0000 Subject: Python's website does a great disservice to the language In-Reply-To: <1h5f4ih.1vzj241qzcz4tN%aleax@mail.comcast.net> References: <1130959513.228185.265740@g14g2000cwa.googlegroups.com> <1h5f4ih.1vzj241qzcz4tN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > The Eternal Squire wrote: > ... > >>2) Consider what he really wants for a supervisor of software >>engineers. Ideally such a person should be a software engineer with >>at least 3 times the experience of the most junior member. Such a > > > I like the general idea but not your formula. If the most junior team > member was 1 month out of school, would it really be OK for the > supervisor to be somebody who graduated 3 months ago?-) > It worked for Microsoft ... 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 bonono at gmail.com Sun Nov 20 05:59:30 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 02:59:30 -0800 Subject: about dictionary In-Reply-To: References: Message-ID: <1132484370.740953.79960@g43g2000cwa.googlegroups.com> b = dict([(x,dict()) for x in a]) Shi Mu wrote: > I have have the following code: > >>> a=[3,5,8,0] > >>> b={} > >>> > How I can i assign each item in a as the key in the dictionary b > simultaneously? > that is, > b={3:[],5:[],8:[],0:[]} > Thanks! From Serge.Orlov at gmail.com Sun Nov 13 03:17:00 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 Nov 2005 00:17:00 -0800 Subject: Problem with __str__ if baseclass is list References: <-dSdnSvs0ueX0OveRVn-sw@comcast.com> Message-ID: <1131869820.343182.126490@g47g2000cwa.googlegroups.com> Edward C. Jones wrote: > #! /usr/bin/env python > > class A(list): > def __init__(self, alist, n): > list.__init__(self, alist) > self.n = n > > def __str__(self): > return 'AS(%s, %i)' % (list.__str__(self), self.n) > > def __repr__(self): > return 'AR(%s, %i)' % (list.__repr__(self), self.n) > > a = A(['x', 'y'], 7) > > print 1, a > print 2, repr(a) > print 3, list.__str__(a) > print 4, list.__repr__(a) > > """ > The output is: > > 1 AS(AR(['x', 'y'], 7), 7) > 2 AR(['x', 'y'], 7) > 3 AR(['x', 'y'], 7) > 4 ['x', 'y'] > > Why is list.__str__(a) == "AR(['x', 'y'], 7)"? Because it's coded like this: def __str__(self): return repr(self) That implies str(x) == repr(x), since you don't want that, don't call list.__str__ > > Note: The problem goes away if "list.__str__(a)" is replaced with > "list.__repr__(self)". > """ That's right. You *cannot* call list.__str__ because it contradicts design of class A From tuvas21 at gmail.com Wed Nov 9 13:47:27 2005 From: tuvas21 at gmail.com (Tuvas) Date: 9 Nov 2005 10:47:27 -0800 Subject: PIL-> Tkinter In-Reply-To: <1131554878.017628.43180@g44g2000cwa.googlegroups.com> References: <1131551783.628602.3320@g14g2000cwa.googlegroups.com> <1131554878.017628.43180@g44g2000cwa.googlegroups.com> Message-ID: <1131562046.986871.148050@g43g2000cwa.googlegroups.com> That would be extremely useful.Thanks! From kay.schluehr at gmx.net Tue Nov 22 04:41:44 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 22 Nov 2005 01:41:44 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> Message-ID: <1132652504.327803.154790@g49g2000cwa.googlegroups.com> Christoph Zwerschke wrote: > That would be also biased (in favour of Python) by the fact that > probably very little people would look for and use the package in the > cheese shop if they were looking for ordered dicts. Does anyone actually use this site? While the Vaults offered a nice place and a nice interface the Cheese Shop has the appeal of a code slum. Kay From godoy at ieee.org Sat Nov 26 06:31:25 2005 From: godoy at ieee.org (Jorge Godoy) Date: 26 Nov 2005 09:31:25 -0200 Subject: Hello World-ish References: <1133003995.066575.54530@g49g2000cwa.googlegroups.com> Message-ID: <87psonhche.fsf@jupiter.g2ctech> "ludvig.ericson at gmail.com" writes: > from os import * > print "Working path: %s" % os.getcwd(); > > Just wondering how you would do that .. in theory, if you get what I > mean? > I get > NameError: name 'os' is not defined > currently, which I don't know how to fix.. anyone? Either: import os or print "Working path: %s" % getcwd(); Avoid "from import *" always when you can (there are still modules designed to work with it). It pollutes namespace and might lead to undesirable clobbing of data structures (is it your 'getId' method or the module's that is being used? ;-)). Be seeing you, -- Jorge Godoy From steve at holdenweb.com Mon Nov 7 23:59:20 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 Nov 2005 04:59:20 +0000 Subject: problem generating rows in table In-Reply-To: <1131424393.303923.263380@g43g2000cwa.googlegroups.com> References: <1131424393.303923.263380@g43g2000cwa.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > hi > i wish to generate a table using cgi > toprint = [('nickname', 'justme', 'someplace')] > print ''' > > > > > > > ''' > > for i in range(0,len(toprint)-1): > for j in range(0,len(toprint[0])-1): > print "" % toprint[i][j] > > print ''' >
UserNameAddress
%s
''' > > but it only prints out a table with "User | Name | address" > it didn't print out the values of toprint > > is there mistake in code? please advise > thanks > Your problem is in trying to emulate the C looping structures rather than using those native to Python: the toprint list has only one element, and the range computations suffer from out-by-one errors, leaving you iterating zero times! It might be simpler to build the output as follows: print ''' ''' rows = [] for row in toprint: print " " for cell in row: print " " % cell print " " print "
User Name Address
%s
" Of course you should really be ensuring that the cell contents correctly escape any special characters in the cell content (such as turning "<" into "<") but I'll leave that as an exercise. 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 fredrik at pythonware.com Thu Nov 24 02:41:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Nov 2005 08:41:39 +0100 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com><1132756197.635519.114180@g47g2000cwa.googlegroups.com> <1132775825.182959.314090@g43g2000cwa.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > I don't find your code any more readable than the OP's > equivalent code: the OP's question was How you do this in a practic way without the use of one-line code ? > The OPs code make one pass through the dict, your's makes > two. I do not know what effect (if any) that has in the case of > a very large dict. the OPs code contains five reads and three writes, my and steven's versions contain four reads and three writes. the yet-to-be-released ternary operator would remove one read from the OPs code, which makes both alternatives equivalent. dictionary accesses don't involve passes over the dictionary. there's a comment on readability and code understanding waiting to be made here, but I'll leave that for another day. From gregory.petrosyan at gmail.com Fri Nov 18 04:35:00 2005 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 18 Nov 2005 01:35:00 -0800 Subject: Default method arguments In-Reply-To: <1132259350.192573.212030@f14g2000cwb.googlegroups.com> References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <867jb9r6qr.fsf@bhuda.mired.org> <1132087833.419559.122310@g43g2000cwa.googlegroups.com> <86u0edpq5v.fsf@bhuda.mired.org> <1132259350.192573.212030@f14g2000cwb.googlegroups.com> Message-ID: <1132306500.643372.239150@f14g2000cwb.googlegroups.com> Thanks Martin, you are right. From larry.bates at websafe.com Mon Nov 7 19:39:35 2005 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 07 Nov 2005 18:39:35 -0600 Subject: struct.calcsize problem In-Reply-To: <1131406026.908312.13530@g44g2000cwa.googlegroups.com> References: <1131406026.908312.13530@g44g2000cwa.googlegroups.com> Message-ID: <436FF3C7.2060907@websafe.com> Chandu wrote: > In using the following struct format I get the size as 593. The same C > struct is 590 if packed on byte boundary and 596 when using pragma > pack(4). I am using pack(4) and added 3 spares at the end to get by. > hdrFormat = '16s 32s 32s B 8s H 8s H 4s H H 20s 64s 64s 64s 32s 32s > 64s L L B B B B B 64s 64s' > > Any ideas on what I am doing wrong? > Maybe this will help: import struct hdrFormats = ['16s','32s', '32s','B','8s','H','8s','H','4s','H','H', '20s','64s','64s','64s','32s','32s','64s','L','L','B', 'B','B','B','B','64s','64s'] sumofcalcsize=0 i=0 for fmt in hdrFormats: l=struct.calcsize(fmt) sumofcalcsize+=l print "fmt='%s', calcsize=%i, sumofcalcsize=%i, calcsize=%i" % \ (fmt, l, sumofcalcsize, struct.calcsize(' '.join(hdrFormats[:i+1]))) i+=1 Outputs: fmt='16s', calcsize=16, sumofcalcsize=16, calcsize=16 fmt='32s', calcsize=32, sumofcalcsize=48, calcsize=48 fmt='32s', calcsize=32, sumofcalcsize=80, calcsize=80 fmt='B', calcsize=1, sumofcalcsize=81, calcsize=81 fmt='8s', calcsize=8, sumofcalcsize=89, calcsize=89 fmt='H', calcsize=2, sumofcalcsize=91, calcsize=92 <==== fmt='8s', calcsize=8, sumofcalcsize=99, calcsize=100 fmt='H', calcsize=2, sumofcalcsize=101, calcsize=102 fmt='4s', calcsize=4, sumofcalcsize=105, calcsize=106 fmt='H', calcsize=2, sumofcalcsize=107, calcsize=108 fmt='H', calcsize=2, sumofcalcsize=109, calcsize=110 fmt='20s', calcsize=20, sumofcalcsize=129, calcsize=130 fmt='64s', calcsize=64, sumofcalcsize=193, calcsize=194 fmt='64s', calcsize=64, sumofcalcsize=257, calcsize=258 fmt='64s', calcsize=64, sumofcalcsize=321, calcsize=322 fmt='32s', calcsize=32, sumofcalcsize=353, calcsize=354 fmt='32s', calcsize=32, sumofcalcsize=385, calcsize=386 fmt='64s', calcsize=64, sumofcalcsize=449, calcsize=450 fmt='L', calcsize=4, sumofcalcsize=453, calcsize=456 <==== fmt='L', calcsize=4, sumofcalcsize=457, calcsize=460 fmt='B', calcsize=1, sumofcalcsize=458, calcsize=461 fmt='B', calcsize=1, sumofcalcsize=459, calcsize=462 fmt='B', calcsize=1, sumofcalcsize=460, calcsize=463 fmt='B', calcsize=1, sumofcalcsize=461, calcsize=464 fmt='B', calcsize=1, sumofcalcsize=462, calcsize=465 fmt='64s', calcsize=64, sumofcalcsize=526, calcsize=529 fmt='64s', calcsize=64, sumofcalcsize=590, calcsize=593 Larry Bates From bignose+hates-spam at benfinney.id.au Thu Nov 10 23:55:13 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Nov 2005 15:55:13 +1100 (EST) Subject: Abstract Base Classes References: <861x1n6cit.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > class FooException(Exception): > def __init__(self): > if self.__class__ == FooException: > raise NotImplementedError, > "FooException is an abstract class for exceptions" Shall try this when I get the chance. Thanks. > Personally, I find this unpythonic. FooException doesn't contribute > anything, and has no real reason for existing. The purpose is to be able to specify an 'except FooException:' in some user of that module; this allows exceptions from that particular module to be handled differently, if necessary. (And so on for a hierarchy of modules in a package, if that's warranted.) -- \ "A cynic is a man who knows the price of everything and the | `\ value of nothing." -- Oscar Wilde | _o__) | Ben Finney From linuxlah at gmail.com Wed Nov 23 04:24:26 2005 From: linuxlah at gmail.com (Mohammad Jeffry) Date: Wed, 23 Nov 2005 17:24:26 +0800 Subject: Hot to split string literals that will across two or more lines ? In-Reply-To: References: Message-ID: I tried to use this method in my code like this:- --------------------------------------------------------------------------------- #!/usr/bin/python def print_sql(): sql = '''aaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbb'''.replace("\n","") print sql print_sql() --------------------------------------------------------------------------------- the ouput of this is aaaaaaaaaaaaaaaabbbb...... I can always do this :- --------------------------------------------------------------------------------- #!/usr/bin/python def print_sql(): sql = '''aaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbb'''.replace("\n","") print sql print_sql() --------------------------------------------------------------------------------- but it looks ugly On 11/22/05, Mohammad Jeffry wrote: > > > On 11/22/05, Paul McGuire wrote: > > > Or for a large literal string: > > > > """ > > lots of text hundreds of characters long > > more text on another line but we really don't want any line breaks > > in our final string > > so we replace newlines in this multiline string > > with an empty string thus > > """.replace('\n','') > > > > -- Paul > > > > I love your method. The only drawbacks for this method is I can't tell > whether there is blank space at the end of each lines. For EG: the above > string might be > > lots of text hundreds of characters longmore text on another..... > ^ > or > > lots of text hundreds of characters long more text on another..... > ^ > > > > > > -- > And whoever does an atom's weight of evil will see it. -- And whoever does an atom's weight of evil will see it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bonono at gmail.com Fri Nov 4 02:26:42 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 3 Nov 2005 23:26:42 -0800 Subject: I need Motivation In-Reply-To: <436b0b9b$0$11068$e4fe514c@news.xs4all.nl> References: <436b0b9b$0$11068$e4fe514c@news.xs4all.nl> Message-ID: <1131089202.065204.48370@z14g2000cwz.googlegroups.com> Martin P. Hellwig wrote: > blah at blah.blah wrote: > > I m not a python Expert or anythin > > i need help, i m losin my motivation to continue with python > > can anyone inspire me again.??? > > Ooh that is easy, start learning other programming languages, you'll go > back continuing with python very soon after that! ;-) It seems that many people switch to Ruby and never look back, some other go to haskell as well. From steve at REMOVETHIScyber.com.au Wed Nov 16 17:25:27 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 17 Nov 2005 09:25:27 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> <1132178416.518202.138740@f14g2000cwb.googlegroups.com> Message-ID: On Wed, 16 Nov 2005 14:00:16 -0800, The Eternal Squire wrote: >>The legality of copying, modifying and redistributing works should be >>reformed until it matches a 6th grader's intuitions about sharing. > > A 6th grader also has intuitions regarding the ownership of an idea. > "It was MY idea!!!" "No, it's NOT!!!" "Is TOO!!!" That's what happens when you try to teach 6th graders about intellectual property: they revert back to two year old mentality. -- Steven. From steve at REMOVETHIScyber.com.au Mon Nov 21 16:28:32 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 22 Nov 2005 08:28:32 +1100 Subject: Aproximative string matching References: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> <1132543801.861940.146530@g43g2000cwa.googlegroups.com> <438149D6.5090403@REMOVEMEcyber.com.au> <3uej2eF11506mU1@uni-berlin.de> Message-ID: On Mon, 21 Nov 2005 19:47:45 +0100, Diez B. Roggisch wrote: > The idea is that otherwise e.g. "cat" and "hippopothamus" have a > l-distance of only 3, which one would consider good at the first look. ??? I make it that the L-distance between cat and hippopothamus is twelve, not three. With len(cat)=3 and len(hippopothamus) = 13, you need ten insertions just to get the lengths equal, so the L-distance must be at least ten. -- Steven. From mwm at mired.org Fri Nov 25 14:40:33 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 25 Nov 2005 14:40:33 -0500 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <1132841680.454026.203420@z14g2000cwz.googlegroups.com> <11ocu1og1660965@corp.supernews.com> <1132928461.261842.132720@g47g2000cwa.googlegroups.com> Message-ID: <867jawiki6.fsf@bhuda.mired.org> "Paul Boddie" writes: > Ed Jensen wrote: > [On proprietary ports of Python...] >> Show me the harm done. > We'll have to wait and see what happens. There's a risk that versions > of Python with different semantics or characteristics to the original > could cause the development of parallel communities, instead of > everyone working on/with the same project. How are the proprietary forks any worse/more dangerous than the open implementations of Python when it comes to such things? In other words, what does the GPL do that prevents this forking? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dalke at dalkescientific.com Tue Nov 29 20:34:52 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 30 Nov 2005 02:34:52 +0100 Subject: Update the sorting mini-howto In-Reply-To: References: Message-ID: <69e77bba0ec27e510b32146ada50dc4a@dalkescientific.com> I wrote: > Years ago I wrote the Sorting mini-howto, currently at > > http://www.amk.ca/python/howto/sorting/sorting.html Thanks to amk it's now on the Wiki at http://wiki.python.org/moin/HowTo/Sorting so feel free to update it directly. Andrew dalke at dalkescientific.com From mortenbagai at gmail.com Fri Nov 18 12:41:46 2005 From: mortenbagai at gmail.com (mortenbagai at gmail.com) Date: 18 Nov 2005 09:41:46 -0800 Subject: Los Angeles Python Users' Group, anyone? Message-ID: <1132335706.182177.58370@g14g2000cwa.googlegroups.com> Hi, I was rifling through python.org to see if there was an existing Python user's group for the Los Angeles area. Doesn't seem like it, so maybe we should start one? I'm interested in helping with the coordination of activities etc. Since everybody living in greater L.A. area is likely to have superhuman tolerance for traffic and commuting times, I see no reason why an L.A users' group couldn't cover the whole LA/Valley/Burbank/Glendale/Pasadena/Long Beach/etc sprawl. Anyone interested, please email me at: m AT bagai DOT com Thanks! /Morten From bignose+hates-spam at benfinney.id.au Mon Nov 14 16:08:20 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Nov 2005 08:08:20 +1100 (EST) Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> Message-ID: Pierre Barbier de Reuille wrote: > The problem is not about having something constant ! > The main point with symbols is to get human-readable values. > Let say you have a symbol "opened" and a symbol "closed". The state > of a file may be one of the two. from some_enum_module import Enum FileState = Enum('open', 'closed') input_file.state = FileState.closed > If you have these symbols, you can ask for the state at any point > and get something readable. If you use constants valued, typically, > to integers, the state of your file will we 0 or 1, which does not > mean anything. str(input_file.state) # -> 'closed' > Now, if you're using an object with more than two states, and > moreover if the number of states is likely to increase during > developpement, it's much more convenient to directly get the > *meaning* of the value rather than the value itself (which does not > mean anything). PixelColour = Enum('red', 'green', 'blue', 'black') > The key point that, I think, you misunderstand is that symbols are > not *variables* they are *values*. So far, I see nothing that requires anything but a special object type with the behaviour you describe. Which most of the enumerated-type implementations do quite neatly. > Well, once more, new syntax for new objects never solve new > problems, they just make them easier to write. If you want to promote something, it would be best to implement it and demonstrate some problems that it solves. You don't seem to be arguing against a new object type, so perhaps it would be best to simply start using that type to solve some actual problems. Since "promotion" is the only argument you've given for new syntax for this concept, I don't see what is served talking about creating syntax for something that does not yet exist to be promoted. Once an implementation exists for examination and is actually useful to some amount of users for solving actual problems, that's the time to talk about promoting it. -- \ "I went to the cinema, it said 'Adults: $5.00, Children $2.50'. | `\ So I said 'Give me two boys and a girl.'" -- Steven Wright | _o__) | Ben Finney From ericwan78 at yahoo.com Tue Nov 22 12:37:34 2005 From: ericwan78 at yahoo.com (wanwan) Date: 22 Nov 2005 09:37:34 -0800 Subject: Entry widget -- how to prevent change Message-ID: <1132681054.145460.169830@g43g2000cwa.googlegroups.com> let's say I already have some content. How do I set the widget so user cannot change it/? From yeahright at redshifted.net Thu Nov 17 08:35:25 2005 From: yeahright at redshifted.net (=?iso-8859-4?Q?Shane?=) Date: Thu, 17 Nov 2005 08:35:25 -0500 Subject: searching for files on Windows with Python Message-ID: <20051117133525.21047.qmail@server285.com> I've been giving Google a good workout with no luck. I would like to be able to search a Windows filesystem for filenames, returning a list off absolute paths to the found files, something like: def findFiles(filename, pathToSearch): ... ... return foundFileNames Is the os module where I should start? Thanks, Shane From bignose+hates-spam at benfinney.id.au Tue Nov 1 18:24:26 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 2 Nov 2005 10:24:26 +1100 (EST) Subject: Rich __repr__ References: Message-ID: Erik Max Francis wrote: > Ben Finney wrote: > > If I want to implement a __repr__ that's reasonably "nice" to the > > programmer, what's the Right Way? Are there recipes I should look > > at? > > I tend to use: > > def __repr__(self): > if hasattr(self, '__str__'): > return '<%s @ 0x%x (%s)>' % (self.__class__.__name__, > id(self), str(self)) > else: > return '<%s @ 0x%x>' % (self.__class__.__name__, id(self)) Well that just begs the question: what's a good way (or a Right Way, if that exists) to write a __str__ for a complex class? > If it's a relatively straightforward class where the entire state is > exposed through the constructor, then a friendly repr is possible. > Otherwise, it's not, and trying to otherwise do so may just be > confusing. "A friendly __repr__" doesn't necessarily mean outputting the full syntax of a hypothetical constructor for the instance. I'm looking for ways that people use to have __repr__ communicate things the programmer will actually want to know, rather than only the qualified class name and an arbitrary memory address. It could be done just by hacking __repr__ with whatever things seem appropriate, in some ad-hoc format. Or, as I'm hoping with this thread, there may be common practices for outputting object state from __repr__ that are concise yet easily standardised and/or recognised. An idempotent __repr__ output seem to be the ideal, but as you say, there are many classes for which it's impossible. What to do in those cases? What's the Right Way? What's the common way? -- \ "There was a point to this story, but it has temporarily | `\ escaped the chronicler's mind." -- Douglas Adams | _o__) | Ben Finney From ale.of.ginger at gmail.com Tue Nov 8 21:12:15 2005 From: ale.of.ginger at gmail.com (ale.of.ginger at gmail.com) Date: 8 Nov 2005 18:12:15 -0800 Subject: Goto XY In-Reply-To: <1131501865.133982.97930@z14g2000cwz.googlegroups.com> References: <1131499644.561039.16420@g14g2000cwa.googlegroups.com> <1131501865.133982.97930@z14g2000cwz.googlegroups.com> Message-ID: <1131502335.530040.58260@g47g2000cwa.googlegroups.com> Thanks -- I downloaded WConio. When I just tried it out in the IDLE, it said: NameError: name 'WConio' is not defined I assume I have to use a header somewhere (import WConio ?). Or is there something I'm missing (I downloaded the Python 2.4 (I have 2.4.2) auto installer and it ran fine...) From bonono at gmail.com Sun Nov 27 00:51:07 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 26 Nov 2005 21:51:07 -0800 Subject: Which License Should I Use? In-Reply-To: <1133041306.601950.213710@g43g2000cwa.googlegroups.com> Message-ID: <1133070667.796967.286760@g43g2000cwa.googlegroups.com> First thing first, you need to find out if you are an "employee", not in the normal sense, but legal sense. This directly affect the copyright issue, outside your "work hours". If you need their consent on take on other clients, that would be iffy. There are a number of things a court would look at to determine this. You may think you are a consultant(thus tools you develop during the course is yours, so long it is outside "contracted hours"), the court may not think it this way. From zelzel.zsu at gmail.com Sun Nov 6 12:13:03 2005 From: zelzel.zsu at gmail.com (zelzel.zsu at gmail.com) Date: 6 Nov 2005 09:13:03 -0800 Subject: socket receive file does not match sent file Message-ID: <1131297183.385236.146170@g14g2000cwa.googlegroups.com> I wrote two simple socket program. one for sending a file and the other for receiving the file. but when I run it, a curious thing happened. The received file was samller that the sent file. $ cat receivefile.py #!/usr/local/bin/python # -*- coding: utf-8 -*- import socket import time import string import sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', 9000)) sock.listen(5) try: while True: # 1. client connect, open file newSocket, address = sock.accept() print "Connected from ", address filename = sys.argv[1] f=open( filename, 'wb') # 2. recieve data while True: data = newSocket.recv(8192) if not data: break f.write(data) # 3.close file f.close() print filename, "Received\n" finally: sock.close() $ cat putfile.py #!/usr/local/bin/python # -*- coding: utf-8 -*- import sys import socket import string # "Usage: prog file hostip" filename = sys.argv[1] host = sys.argv[2] f=open(filename, 'rb') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, 9000)) while True: data = f.read(8192) if not data: break else: s.send(data) f.close() s.close() print filename, " Sent!\n" $ python receivefile.py save_apache_1.33.tar.gz $ python putfile.py apache_1.33.tar.gz localhost The result is : save_apache_1.33.tar.gz 's size was smaller then the apache_1.33.tar.gz file What is the cause of the problem, can anyone tell me? Thanks. From ejatwellkeepercom Wed Nov 9 18:54:49 2005 From: ejatwellkeepercom (ej) Date: Wed, 9 Nov 2005 16:54:49 -0700 Subject: struct, IEEE-754 and internal representation References: <437280ee$1@nntp.zianet.com> <11n50p6ddmpn55f@corp.supernews.com> Message-ID: <43728ccd@nntp.zianet.com> Ah! Well! That explains it. I started to suspect that but (obviously) did not know that. LOL Thanks for your prompt reply, Grant. :) -ej From fredrik at pythonware.com Wed Nov 23 16:10:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 22:10:18 +0100 Subject: Backwards compatibility [was Re: is parameter an iterable?] References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com><1h62slm.up4s2tqyk1gjN%aleax@mail.comcast.net><437C36EA.8010600@REMOVEMEcyber.com.au><438287DF.8030506@REMOVEMEcyber.com.au> Message-ID: Tom Anderson wrote: > How about detecting which environment you're in, then running one of two > entirely different sets of code? Rather than trying to construct modern > features in the antique environment, write code for each, using the local > idioms. The trouble with this is that you end up with massive duplication; > you can try to factor out the common parts, but i suspect that the > differing parts will be a very large fraction of the codebase. That sounds like the worst possible way of writing portable code (unless you have huge amounts of time and money, and wasting them don't really matter to you). In my experience, a more practical approach is to write code that targets the 2.0/2.1 platform, and selectively (based on feature tests, not version numbers) replace portions with more efficient mechanisms from newer versions. (most of those are found in the standard library, not in the language itself). (this is related to another popular myth: that code that uses "the old way" is automatically slower than code that uses newfangled stuff, also when running on recent Python versions. that's very seldom true; new Python versions runs "old" code faster too.) If you want to support 1.5.2 or Unicode-less Python builds, you need to add some fallbacks too, but that's mostly trivial. The easiest way is to pass 8-bit strings through "as is", leaving encoding issues to the application. >> If I have to write code that can't rely on iter() existing in the >> language, what should I do? > > Can you implement your own iter()? I have no idea what python 2.0 was > like, but would something like this work: Python 2.0 had sequences. Python 2.4 has sequences. Iterators don't really add anything. Emulating them in older versions is mostly pointless. I've said it many times, and I'll say it again: the only fundamentally new concept that has been added since Python 1.5.2 is generators. And a lot of the stuff you want generators for can be emulated with sequences and extra buffer layers. All the rest is just coloured frosting; you can save a line here and there (which is a real benefit only if your return key is broken), but that's about it. From bonono at gmail.com Wed Nov 23 22:19:40 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 19:19:40 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: Message-ID: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> Peter Hansen wrote: > Christoph Zwerschke wrote: > > Ok, the answer is easy: For historical reasons - built-in sets exist > > only since Python 2.4. > > > > Anyway, I was thinking about whether it would be possible and desirable > > to change the old behavior in future Python versions and let dict.keys() > > and dict.values() both return sets instead of lists. > > Definitely not. I believe it's currently guaranteed that the order of > the items in dict.keys() and dict.values() will match (i.e. the index of > any key in its list will be the same as the index of the corresponding > value in its list). This property is almost certainly used in some > code, so it can't be broken without good reason. Interesting, but why it guaranteed this as functionality wise they are two different things and since dict is unordered, there is no need for such guarantee, would it be just implementation consequence ? This to me is even more uncertain than the zip(it,it) case. From bokr at oz.net Thu Nov 10 17:01:29 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 10 Nov 2005 22:01:29 GMT Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131627394.890394.200070@g44g2000cwa.googlegroups.com> Message-ID: <4373bcbc.150778327@news.oz.net> On 10 Nov 2005 04:56:34 -0800, "bonono at gmail.com" wrote: > >Peter Hansen wrote: >> (I say "readable or somehow better" since you stated in another post "I >> just try to use list/generator expression when possible" but you didn't >> explain your reason for doing so. I assume you have some reason other >> than arbitrary whim.) >The reason is simple: > >I found it easier to read for me and using list/generator expression >helped me uncover a number of subtle bugs comparing with an imperative >approach. > >on its own : > >takewhile(lambda x: condition(x), some_generator) is not very much >difference than(well, still more things to type) > >(x for x in some_generator when condition(x)) I wish you wouldn't write "when" like that, as if it were legal python python syntax. (Nor do I like guessing what it's supposed to mean ;-) >>> list (x for x in xrange(20) when x<5)) File "", line 1 list (x for x in xrange(20) when x<5)) ^ SyntaxError: invalid syntax If you want to terminate a generator expression after the first sequence of elements satisfying a condition, and you don't want to use takewhile, I don't know of a gotcha to prevent you from just raising StopIteration, using an expression that will do that, e.g., >>> list (x for x in xrange(20) if x<5 or iter([]).next()) [0, 1, 2, 3, 4] Or a bit more readably: >>> def stop(): raise StopIteration ... >>> list (x for x in xrange(20) if x<5 or stop()) [0, 1, 2, 3, 4] IOW, your "when condition(x)" (IIUIC) can be spelled "if condition(x) or stop()" > >but when I have a number of them in the same expression, the >takewhile/dropwhile becomes to add up. If you don't like Alex'(s?) good advice, you can continue bracketed expressions on several lines, and indent and group for clarity. Regards, Bengt Richter From bonono at gmail.com Wed Nov 23 00:57:47 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 21:57:47 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <1h6g70e.19ub6oh1pa0proN%aleax@mail.comcast.net> References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> <1132715742.672265.259740@o13g2000cwo.googlegroups.com> <4383e912.513766727@news.oz.net> <1132719449.516504.268980@z14g2000cwz.googlegroups.com> <1h6g70e.19ub6oh1pa0proN%aleax@mail.comcast.net> Message-ID: <1132725466.987600.167800@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > What you can obtain (or anyway easily simulate in terms of effects on a > loop) through an explicit call to the 'sorted' built-in, possibly with a > suitable 'key=' parameter, I would call "sorted" -- exactly because, as > Bengt put it, there IS a sorting algorithm which, etc, etc (if there > wasn't, you couldn't implement it through the 'sorted' built-in!). > > So, any ordering that can be reconstructed from the key,value data held > in a dict (looking up some combinations of those in an external table is > nothing special in these terms) falls under this category. But, a dict > does not record anything about what was set or changed or deleted when; > any ordering which requires access to such information thus deserves to > be placed in a totally separate category. > But I can also record these changes in a seperate table which then becomes a "sorted" case ? From deets at web.de Mon Nov 7 10:25:12 2005 From: deets at web.de (Diez B. Roggisch) Date: 7 Nov 2005 07:25:12 -0800 Subject: Python and PL/SQL In-Reply-To: <1131375297.942110.86200@f14g2000cwb.googlegroups.com> References: <1131369305.252487.30220@o13g2000cwo.googlegroups.com> <1131371902.061620.295920@g49g2000cwa.googlegroups.com> <87ek5s8r58.fsf@jupiter.g2ctech> <1131375297.942110.86200@f14g2000cwb.googlegroups.com> Message-ID: <1131377112.162173.126140@g47g2000cwa.googlegroups.com> vb_bv wrote: > Thanks for your answers. > I would like to document with Python PL/SQL of programs, so similarly > as javadoc for Java. > I do not know whether it is possible. If yes, I would like to know how. Is it possible - yes. Has it been done? I doubt it. You can fetch the sourcecode of oracle packages through sql-statements (google for how to do it), and then process it with whatever tool you like. But you will have to write your own parser and generator for that, pydoc or epydoc won't be of much use here. However, implementing such a thingy in python is certainly a good idea. Diez From james at colannino.org Fri Nov 11 20:12:59 2005 From: james at colannino.org (James Colannino) Date: Fri, 11 Nov 2005 17:12:59 -0800 Subject: weird problem with os.chmod In-Reply-To: <43753D14.8040400@colannino.org> References: <43753C13.2010609@colannino.org> <43753D14.8040400@colannino.org> Message-ID: <4375419B.8070602@colannino.org> James Colannino wrote: >Ok, so further research revealed that 0600 is actually the octal >representation for 384 (which makes sense.) So then, I guess my >question would have to be, is there a way for me to make Python aware >that the 0600 I'm passing to int() is octal and not decimal so that I >will get 384 instead of 600? > > I discovered the solution and thought I'd share it with everyone. I discovered as I googled that Python used to have a function called atoi() that took the parameter base=X. I decided to see if that worked with the newer function int() and it did :) James -- My blog: http://www.crazydrclaw.com/ My homepage: http://james.colannino.org/ "A well regulated militia being necessary to the security of a free state, THE RIGHT of the people to keep and bear arms SHALL NOT BE INFRINGED." --United States Constitution, Second Ammendment From dcrespo at gmail.com Tue Nov 15 09:49:25 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 15 Nov 2005 06:49:25 -0800 Subject: A way for launch an app monitor Message-ID: <1132066165.696657.298930@o13g2000cwo.googlegroups.com> Hello, I'm in the way for creating an application and its monitor. Yes, there are 2 applications: The main app, and a monitor. The last one monitors the main application for keeping it alive, and viceversa. But if I close the main app, I want to close the monitor. That is very easy under nt systems, but in 98 is a little more tricky because of the problem with closing processes. For example, I can't use the following code on a win98 machine: def FindPID(exename): """ usage: pid=FindPID("pythonw.exe") print pid """ a = os.popen4('tasklist /FI "IMAGENAME eq '+exename+'"') a[0].flush() try: info=a[1].readlines()[3].split() except: info=[exename,"NotFound"] return info[1] #PID because the "tasklist" command doesn't exist on win98. Also, I tried to install the kill.exe and a dont-remember-dll (from the Win98 Resource Kit), but it doesn't work. So my solution (need help on this) is that I have been thinking on letting the monitor listen for socket connection. Through this, the main app can tell him to close when the main app closes correctly. Do you think this is well thought? Any suggestions? Daniel From bonono at gmail.com Wed Nov 16 04:27:12 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 16 Nov 2005 01:27:12 -0800 Subject: Default method arguments In-Reply-To: <1132071889.676287.240030@o13g2000cwo.googlegroups.com> References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a0a1b_1@newsgate.x-privat.org> <1132071889.676287.240030@o13g2000cwo.googlegroups.com> Message-ID: <1132133232.891184.63710@g47g2000cwa.googlegroups.com> What you want is essentially : if parm_x is not supplied, use self.val_x So why not just express it clearly at the very beginning of the function : def f(self, parm_x=NotSupplied, parm_y=NotSupplied ,,,) if parm_x is NotSupplied: parm_x = self.val_x if parm_y is NotSupplied: parm_y = self.val_y Much easier to understand than the "twisting your arm 720 degree in the back" factory method, IMO. Gregory Petrosyan wrote: > Thanks a lot, but that's not what I do really want. > 1) f() may have many arguments, not one > 2) I don't whant only to _print_ x. I want to do many work with it, so > if I could simply write > > def f(self, x = self.data) (*) > > it would be much better. > > By the way, using > > class A(object): > data = 0 > .... > def f(self, x = data) > > solves this problem, but not nice at all > > So I think (*) is the best variant, but it doesn't work :( From bokr at oz.net Sun Nov 6 03:40:11 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 06 Nov 2005 08:40:11 GMT Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> <7x4q6q7f6b.fsf@ruckus.brouhaha.com> <86hdaqsfjo.fsf@bhuda.mired.org> <7x3bmafrip.fsf@ruckus.brouhaha.com> <86d5lescfd.fsf@bhuda.mired.org> <7x8xw2ea4e.fsf@ruckus.brouhaha.com> Message-ID: <436dc164.259807483@news.oz.net> On 05 Nov 2005 19:19:29 -0800, Paul Rubin wrote: >Mike Meyer writes: >> > It's only -because- of those licenses that there's any reason not to >> > bundle. >> >> Actually, there are other reasons, just as there are reasons besides >> licensing for not simply including third party libraries into the >> standard library. > >I'm not talking about 3rd party libraries, I'm talking about 3rd party >documentation for modules that are already in the Python standard >library. For example, if someone wrote a good Tkinter manual that >were licensed in a way that the PSF could drop it into the Python >distro, then PSF should certainly consider including it. The same >goes for good docs about urllib2, or various other modules that >currently have lousy docs. > >> > I found >> > http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html >> > to be a pretty good tutorial, though incomplete as a reference. >> >> Thanks for the URL, but that's just a short list of links, most of >> which I've already seen. > >Sorry, I meant: > > http://infohost.nmt.edu/tcc/help/pubs/tkinter/ (html) > http://www.nmt.edu/tcc/help/pubs/tkinter.pdf (pdf of same) > >You've probably seen this manual already. If not, I'll second the recommendation for the pdf. It's not complete, but it's quite useful and pretty easy to use. Hm, seems to be updated since I downloaded a copy, guess I'll grab the newest ;-) Hm2, it doubled in size! The creation dates are *** FILE tkinter.pdf *** /CreationDate (D:20030416170500) *** FILE tkinter2.pdf *** /CreationDate (D:20050803114234) So I guess it could double in 2 years 4 months. I'll have to look into it. Regards, Bengt Richter From bonono at gmail.com Fri Nov 25 01:10:59 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 22:10:59 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <86y83dto2z.fsf@bhuda.mired.org> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> Message-ID: <1132899059.919842.74190@f14g2000cwb.googlegroups.com> Mike Meyer wrote: > "bonono at gmail.com" writes: > > Christoph Zwerschke wrote: > >> jepler at unpythonic.net schrieb: > >> > You can already get a set from a dictionary's keys in an efficient manner: > >> >>>>l = dict.fromkeys(range(10)) > >> >>>>set(l) > >> > Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > >> Good point. I expected that set(l) = set(l.items()) and not > >> set(l.keys()), but the latter would not work with mutable values. See > >> discussion with Martin. > > puzzled. items() return tuples which I believe can be element of set ? > > Or I misread you ? > > Not all tuples can be elements of a set. Elements of a set have to be > hashable. Tuples compute their hash by hashing their contents. If > their contents aren't hashable, the tuple isn't hashable, and hence > can't be an element of a set. If the values in the dictionary aren't > hashable, then the tuples returned by items() won't be hashable > either, and hence can't be elements of a set. > A related issue, from the doc : Set elements are like dictionary keys; they need to define both __hash__ and __eq__ methods. and dir(any_tuple) would show __hash__ and __eq__, would that be a bit confusing as even though tuple has these two properties(or whatever terms it should be called), it really depends what it contains ? Or in other words, tuple is hashable if and only if every object it contains is also hashable ? If that is the case, would it be better to correct the doc to say such thing ? From peter at engcorp.com Thu Nov 17 23:16:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Nov 2005 23:16:30 -0500 Subject: .pth - howto? In-Reply-To: <1132286440.597347.186850@g47g2000cwa.googlegroups.com> References: <1132286440.597347.186850@g47g2000cwa.googlegroups.com> Message-ID: flippetigibbet wrote: > I've tried specifying the .pth file with > r'\documents and settings\user\My Documents\my\scripts\py\dirname' > \DOCUME~1\user\MyDocu~1\my\scripts\py\dirname > /doceme~1/user/MYDOCU~1/MY/SCRIPTS/PY/DIRNAME > but I can't seem to get python 2.4 to pick up an absolute path on > windows. Does that directory actually exist? It won't get added if it doesn't exist. You can also just trace through the source in "site.py" as it loads (by inserting an "import pdb; pdb.set_trace()" near the top), or add some print statements at key points to see what it's doing. (Note that your first example above definitely wouldn't work, since that is the syntax for a string in Python source, whereas the relevant function [i.e. addpackage()] is merely reading lines from a file...) -Peter From grante at visi.com Tue Nov 15 15:09:20 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Nov 2005 20:09:20 -0000 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: <11nkg3glg6k5e8a@corp.supernews.com> On 2005-11-15, py wrote: > Dan Sommers wrote: >> Just do it. If one of foo's callers passes in a non-iterable, foo will >> raise an exception, and you'll catch it during testing > > That's exactly what I don't want. I don't want an exception, instead I > want to check to see if it's an iterable....if it is continue, if not > return an error code. I can't catch it during testing since this is > going to be used by other people. If I were those other people, and you decided to return error codes to me instead of passing up the proper exception (the good, Pythonic thing to do), I'd be fairly pissed off at you. An exception is the _right_ way to let the caller know something is wrong. -- Grant Edwards grante Yow! I smell like a wet at reducing clinic on Columbus visi.com Day! From karczma at info.unicaen.fr Tue Nov 8 04:30:23 2005 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Tue, 08 Nov 2005 10:30:23 +0100 Subject: Addressing the last element of a list In-Reply-To: References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> Message-ID: Peter Otten wrote: > pinkfloydhomer at gmail.com wrote: > > >>Just to satisfy my curiousity: Is there a way to do something like the >>reference solution I suggest above? > > > No. You cannot overload assignment. I have the impression that this is not an issue, to overload assignments, which btw. *can* be overloaded, but the absence of *aliasing* (undiscriminate handling of pointers) in Python. Am I wrong? Jerzy Karczmarczuk From apardon at forel.vub.ac.be Mon Nov 28 08:17:11 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2005 13:17:11 GMT Subject: General question about Python design goals References: Message-ID: Op 2005-11-28, Duncan Booth schreef : > Antoon Pardon wrote: > >> So suppose I want a dictionary, where the keys are colours, represented >> as RGB triplets of integers from 0 to 255. A number of things can be >> checked by index-like methods. >> >> e.g. >> >> def iswhite(col): >> return col.count(255) == 3 >> >> def primary(col): >> return col.count(255) == 1 and col.count(0) == 2 >> >> def secondary(col): >> return col.count(255) == 2 and col.count(0) == 1 > > Just because you *can* implement these by treating your colour like a list > doesn't make it a good idea. Treating them as opaque values makes these > particular tests clearer: You are getting sidetracked. Whether this is the best possible implementation here is not the issue. This example is just to illustrate. I'm sure I could come up with an other example where I would like to have both some list method and use it as a dictionary key and again people could start about that implementation having some flaws and give better implementations. I'm just illustrating that some list-like methods with tuples could be usefull. -- Antoon Pardon From ms at cerenity.org Sun Nov 13 17:29:13 2005 From: ms at cerenity.org (Michael) Date: Sun, 13 Nov 2005 22:29:13 +0000 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> Message-ID: <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> Ben Finney wrote: ... > I've yet to see a convincing argument against simply assigning values > to names, then using those names. I don't like any syntax I've seen so far, but I can understand the problem. If you have a name, you can redefine a name, therefore the value a name refers to is mutable. As a result if you have 2 symbols represented by names and values, you may have two symbols with different names but the same value. Hence the two "symbols" are no longer unique) Conversely consider "NAME" to be a symbol. I can't modify "NAME". It always means the same as "NAME" and "NAME", but is never the same as "FRED". What's tricky is I can't have namespaceOne."NAME" [1] and namespaceTwo."NAME" as different "NAME"s even though logically there's no reason I couldn't treat "NAME" differently inside each. [1] Supposing for a moment that I could have a string as a name in a namespace. (Rather than a string used as a key in that namespace) However it might be useful to note that these two values (or symbols) are actually different, even if you remove their namespaces. To me, the use of a symbol implies a desire for a constant, and then to only use that constant rather than the value. In certain situations it's the fact that constant A is not the same as constant B that's important (eg modelling state machines). Often you can use strings for that sort of thing, but unfortunately even python's strings can't be used as symbols that are always the same thing in all ways. For example, we can force the id of identical strings to be different: >>> s = "h"*10000 >>> x = "h"*10000 >>> id(s), id(x) (135049832, 135059864) As a result I can see that *IF* you really want this kind of symbol, rather than the various other kinds people have discussed in the thread, that some special syntax (like u'hello' for unicode 'hello') could be useful. However, I'd be more interested in some real world usecases where this would be beneficial, and then seeing what sort of syntax would be nice/useful (Especially since I can think of some uses where it would be nice). On the original syntax proposal, I'm firmly in the -1 camp - to me having done lots of perl in the past $foo looks very firmly like a mutable, rather than an immutable. The reason I'm more interested in seeing usecases, is because I'd rather see where the existing approaches people use/define symbols has caused the OP problems to the extent he feels the language needs to change to fix these real world problems. Michael. From eternalsquire at comcast.net Wed Nov 23 18:59:42 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 23 Nov 2005 15:59:42 -0800 Subject: a new design pattern for Python Library? In-Reply-To: <4384b27e$0$21217$626a54ce@news.free.fr> References: <1132709883.708313.279720@g44g2000cwa.googlegroups.com> <1132738181.664201.272500@g44g2000cwa.googlegroups.com> <43847514$0$21623$636a15ce@news.free.fr> <1132759269.421882.303340@g47g2000cwa.googlegroups.com> <4384b27e$0$21217$626a54ce@news.free.fr> Message-ID: <1132790382.738090.260270@g49g2000cwa.googlegroups.com> Let me try again: Suppose I have a central class with complex behavior that I want to simply write as a bare skeleton upon which to hang the auxillary classes that help provide the complex behavior. The naive approach would be to write: class Skeleton: def __init__ (self): self.core_data = 1 class Auxillary: def __init__ (self): pass def string (self, skeleton): return "%s %d" % (self.__class__.__name__, skeleton.core_data) skeleton = Skeleton () auxillary = Auxillary () auxillary.behavior () What I will typically do is create the auxillary class as a friend so that I can have tighter integration between the Skeleton instance and an Auxillary member instance, where the Auxillary instance isolates behavior that I might want to modify later through inheritance. class Auxillary (Friend): def __str__ (self): return "%s %d" % (self.__class__.__name__, self.friend.core_data) class Skeleton: def __init__ (self): self.auxillary = Auxillary (self) skeleton = Skeleton () print skeleton.auxillary See the difference? I know this is a bit contrived, but I wanted to keep the effect simple. Effectively I now have a self-documenting friend relationship between classes. The Eternal Squire From blahman Thu Nov 3 12:12:59 2005 From: blahman (blah@blah.blah) Date: Thu, 03 Nov 2005 11:12:59 -0600 Subject: Can Anyone Help me on this Message-ID: i m trying to reverse the order in which the strings are stored in list then pop it into another list what m i doin worng?? here's the code: list1 = [] list2 = [] list1.extend('123456789') print list1 for a in list1: list2 = list1.pop() print list2 -- * Posted with NewsLeecher v3.0 Beta 7 * http://www.newsleecher.com/?usenet From swaroopch at gmail.com Thu Nov 10 01:38:02 2005 From: swaroopch at gmail.com (Swaroop C H) Date: 9 Nov 2005 22:38:02 -0800 Subject: How to set program name in Python? ($0 in Perl) Message-ID: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> Hi, Is there a way to set the program name in Python, similar to $0 in Perl? >From `man perlvar`: $0 Contains the name of the program being executed. On some oper- ating systems assigning to "$0" modifies the argument area that the ps program sees. This is more useful as a way of indicat- ing the current program state than it is for hiding the program you're running. (Mnemonic: same as sh and ksh.) Thanks! Swaroop www.swaroopch.info From roy at panix.com Wed Nov 16 09:56:00 2005 From: roy at panix.com (Roy Smith) Date: Wed, 16 Nov 2005 09:56:00 -0500 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: In article , Rick Wotnaz wrote: > Steven D'Aprano wrote in > news:pan.2005.11.15.22.57.58.855137 at REMOVETHIScyber.com.au: > > > def foo(inputVal): > > try: > > for val in inputVal: > > # do stuff > > except TypeError, msg: > > if msg == "iteration over non-sequence": > > # handle non-iterable case > > else: > > # some other TypeError is a bug, so re-raise the > > exception raise > > Does this in fact work on your system? On mine (2.4.1 (#65, Mar 30 > 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]), it doesn't seem to. I > tried > if msg.find("iteration over non-sequence") >= 0: > ... but I got a traceback, and > AttributeError: TypeError instance has no attribute 'find' > ... which leads me to belive that 'msg' is not type(str). It can be > coerced (str(msg).find works as expected). But what exactly is msg? > It appears to be of , and does not test equal to a > string. This is not the least surprise to me. It's an easy experiment to do: ------------------- Roy-Smiths-Computer:play$ cat ex.py #!/usr/bin/env python try: 1 + "foo" except TypeError, msg: print type(msg) print msg print repr(msg) print dir(msg) Roy-Smiths-Computer:play$ py ex.py unsupported operand type(s) for +: 'int' and 'str' ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] --------------------- From jgardner at jonathangardner.net Fri Nov 4 11:03:01 2005 From: jgardner at jonathangardner.net (jgardner at jonathangardner.net) Date: 4 Nov 2005 08:03:01 -0800 Subject: Not Equal to Each Other? In-Reply-To: <1131073383.521851.75720@g44g2000cwa.googlegroups.com> References: <1131066067.980875.223790@g43g2000cwa.googlegroups.com> <1131073383.521851.75720@g44g2000cwa.googlegroups.com> Message-ID: <1131118798.877182.210510@o13g2000cwo.googlegroups.com> > will I have to write that out for each number? Not if you know how to use the 'for' statement. It will allow you to iterate through the rows or columns or whatnot. From bignose+hates-spam at benfinney.id.au Wed Nov 23 17:50:07 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 24 Nov 2005 09:50:07 +1100 (EST) Subject: Making immutable instances Message-ID: Howdy all, How can a (user-defined) class ensure that its instances are immutable, like an int or a tuple, without inheriting from those types? What caveats should be observed in making immutable instances? -- \ "Love is the triumph of imagination over intelligence." -- | `\ Henry L. Mencken | _o__) | Ben Finney From bonono at gmail.com Tue Nov 22 23:39:05 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 20:39:05 -0800 Subject: Anyway to clarify this code? (dictionaries) In-Reply-To: <86sltoyoml.fsf@bhuda.mired.org> References: <1132711108.860281.59900@g49g2000cwa.googlegroups.com> <86ek5812a3.fsf@bhuda.mired.org> <1132716816.034104.325340@o13g2000cwo.googlegroups.com> <86sltoyoml.fsf@bhuda.mired.org> Message-ID: <1132720745.095497.18570@z14g2000cwz.googlegroups.com> Mike Meyer wrote: > First, remember the warnings about premature optimization. Which is why I said the one-liner(your first one) is clean and clear, and bug free in one go. > > use = set(another) - set(keys) > return dict([[k, another[k]] for k in use if another[k] >= x] > > Though I still think I prefer the longhand version: > > out = dict() > for key in set(another) - set(keys): > if another[k] >= x: > out[k] = another[k] This is definitely better than the other long hand version as the set operation remove the potential problem of another[k] raise KeyError. From claudio.grondi at freenet.de Mon Nov 14 10:13:28 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 14 Nov 2005 15:13:28 -0000 Subject: SciPy python 2.4 wintel binaries References: <1131803968.993069.29660@f14g2000cwb.googlegroups.com> <1131967481.007598.158350@g44g2000cwa.googlegroups.com> Message-ID: <3trkcoFrqtgvU2@individual.net> Is http://heanet.dl.sourceforge.net/sourceforge/scipy/scipy-0.4.3.win32-py2.4.exe not what are you looking for? Claudio "jelle" schrieb im Newsbeitrag news:1131967481.007598.158350 at g44g2000cwa.googlegroups.com... > Hi Peter, > > I'm aware of the Enthought distribution, which really is my preferred > 2.3 Python distribution. > Problem is that many programs I'm working on would require both 2.4 & > SciPy > > What kind of puzzles me is that SciPy.core is available for wintel 2.4, > is that an indication a full SciPy distribution is coming along? > > Cheers, > > -jelle > From martin.clausen at gmail.com Fri Nov 18 08:22:47 2005 From: martin.clausen at gmail.com (martin.clausen at gmail.com) Date: 18 Nov 2005 05:22:47 -0800 Subject: Adding through recursion Message-ID: <1132320167.127338.92460@g47g2000cwa.googlegroups.com> There is problaly a really simple answer to this, but why does this function print the correct result but return "None": def add(x, y): if x == 0: print y return y else: x -= 1 y += 1 add(x, y) print add(2, 4) result: 6 None Martin From news at NOwillmcguganSPAM.com Sat Nov 5 05:49:53 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Sat, 05 Nov 2005 10:49:53 +0000 Subject: Converting a List into a String In-Reply-To: <7vKdnRaO_eOiEfHeRVn-iQ@giganews.com> References: <7vKdnRaO_eOiEfHeRVn-iQ@giganews.com> Message-ID: <436c8e53$0$23286$db0fefd9@news.zen.co.uk> blah at blah.blah wrote: > I have a List > > list = ['f', 'e', 'd', 'c', 'b', 'a'] > > How can i convert it into a string so the output is > > fedcba > > i used > > for a in list: > print a, > > the output is > > f e d c b a > > How can i remove the spaces b/w each letter? print "".join(list) BTW list isnt a good name for a list, it hides the built in type. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From renmybiru at libero.it Tue Nov 8 04:31:44 2005 From: renmybiru at libero.it (Vittorio) Date: Tue, 8 Nov 2005 09:31:44 +0000 (UTC) Subject: Lie Hetland book: Beginning Python.. References: Message-ID: Steve Holden wrote in news:mailman.234.1131390819.18701.python-list at python.org: > No, you actually did quite a creditable piece of debugging. The DB-API > specifications allow database modules to substitute parameters into > SQL commands in a number of different ways, and they are supposed to > indicate the technique they use by setting a module variable > "paramstyle" to one of five possible values. > > Magnus' original code was written to use a different (but valid) > paramstyle, so I'm guessing that his sqlite module and your sqlite2 > simply use different paramstyles. Whether that's because a change was > made in developing the pysqlite code or because pysqlite and pysqlite2 > come from different developers I couldn't say, but you have nailed the > problem. Well done! Thanks Steve for your encouragement. Actually, subsequently to my posting, I had realised that the point was in the different version of the Pysqlite interface: in fact I found many other pieces of code which were affected the same way, and each of them made use of "import pysqlite". Nonetheless, I was unable to find any documentation about such a different behaviour between Pysqlite and Pysqlite2; from my beginner point of view the Pysqlite (Magnus' version) paramstyle looks a better and more pythonic choice and I don't grasp the Pysqlite2 developers' intentions deviating from that way. I would be very grateful if someone would cast a light over Pysqlite/Pysqlite2 discrepancies. From lee at example.com Fri Nov 11 17:20:43 2005 From: lee at example.com (Lee Harr) Date: Fri, 11 Nov 2005 22:20:43 GMT Subject: 3-dimensional plot in Python? References: <1131736814.721116.16890@g14g2000cwa.googlegroups.com> Message-ID: <%O8df.2255$lg.64@news01.roc.ny> On 2005-11-11, questions? wrote: > I want to make a 3d plot. x is a vector(discrete), y is also a > vector(discrete), for each pairwise x,y I have a value z(x,y)(it is not > a function, just discrete values for each pair of x,y) > > I want to show them on a two dimensional plot by showing z(x,y) with > colors. > http://matplotlib.sourceforge.net/ From nope at nottelling.com Mon Nov 28 18:51:17 2005 From: nope at nottelling.com (JustSomeGuy) Date: Mon, 28 Nov 2005 23:51:17 GMT Subject: Call OCX from python? References: <5n4if.627200$1i.183531@pd7tw2no> <3usl5aF12ja39U1@individual.net> Message-ID: "Claudio Grondi" wrote in message news:3usl5aF12ja39U1 at individual.net... > "JustSomeGuy" schrieb im Newsbeitrag > news:5n4if.627200$1i.183531 at pd7tw2no... > > Hi I have a commercial OCX that I want to use in > > my python application. How do I call OCXs from > > python? > > TIA > > import win32com.client > axOCX = > win32com.client.Dispatch("RegistryEntryForThisOCXin[VersionIndependentProgID > ]section") > retVal = axOCX.methodOfThisOCX(param1, param2) > value = axOCX.attributeOfThisOCX > > Claudio > > Thank you Claudio... Can you explain the RegistryEntryForThisOcxin[VersionIndependentProgID] I don't know what I should use here.. From jeremy.d.brewer at gmail.com Tue Nov 22 13:28:34 2005 From: jeremy.d.brewer at gmail.com (jbrewer) Date: 22 Nov 2005 10:28:34 -0800 Subject: PIL FITs image decoder In-Reply-To: References: <1132681491.921657.291860@z14g2000cwz.googlegroups.com> Message-ID: <1132684114.165243.33310@g43g2000cwa.googlegroups.com> >http://www.stsci.edu/resources/software_hardware/pyfits I know and love PyFits, but I need to be able to do draw shapes on a FITs image (and perhaps some other operations), and I don't believe that PyFits allows these kinds of operations. It might be possible to import the data into a numarray object and turn that into something PIL can read, though. Jeremy From mwm at mired.org Mon Nov 28 16:48:28 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 28 Nov 2005 16:48:28 -0500 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> <86lkz8vh34.fsf@bhuda.mired.org> <7x1x10ii5r.fsf@ruckus.brouhaha.com> Message-ID: <86sltgtpeb.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> Which means you can't create a verifier which will verify all >> programs. Is there a reason to believe that you can't have a verifier >> with three possible outcomes: Correct, Incorrect, and I don't know, >> and it is always correct in doing so? Note that "I don't know" could >> be "I ran longer than I think is reasonable and gave up trying." > It's trivial to write such a verifier, if you get my drift. Almost as cute as the simplest self-replicating shell script. Ok, so it's possible. Are there any useful examples? Does the BCPL type verifier count? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dcrespo at gmail.com Tue Nov 1 07:22:48 2005 From: dcrespo at gmail.com (dcrespo) Date: 1 Nov 2005 04:22:48 -0800 Subject: OpenSSL in Python In-Reply-To: References: <1130425810.431748.39660@g14g2000cwa.googlegroups.com> Message-ID: <1130847768.899376.128360@o13g2000cwo.googlegroups.com> Hi, Excuse me all of you for the way I answered. Sybren, and all of you, accept my apology. I saw the Sybren's message yersterday late night in a bad moment. I'll visit the OpenSSL forum. Thank you all. From maxerickson at gmail.com Sat Nov 12 08:42:37 2005 From: maxerickson at gmail.com (Max Erickson) Date: Sat, 12 Nov 2005 13:42:37 +0000 (UTC) Subject: tutorial example References: <20051112015026.74881.qmail@web35903.mail.mud.yahoo.com> Message-ID: Not in python. For example, what would you call the following? def rsum(n, m): print n+m return n+m In python a method is callable attached to an object. A function is a callable object constructed with a def statement. max From rurpy at yahoo.com Tue Nov 22 22:05:33 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 22 Nov 2005 19:05:33 -0800 Subject: about sort and dictionary References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> Message-ID: <1132715133.075670.298670@g49g2000cwa.googlegroups.com> Mike Meyer wrote: > rurpy at yahoo.com writes: > > I think this is just another (admittedly minor) case of Python's > > designers using Python to enforce some idea of programming > > style purity. > > You say that as if it were a bad thing. Well, there are many languages that promote a specific style of programming and many of the ideas developed have been incorporated in later, more general languages to good effect. But for a language that wants to be a general purpose language, yea, I guess I think it's bad. A general purpose language should strive to support as wide a varity of styles as possible. But this is getting rather off-topic. From sdb1031 at gmail.com Fri Nov 18 20:27:35 2005 From: sdb1031 at gmail.com (sdb1031 at gmail.com) Date: 18 Nov 2005 17:27:35 -0800 Subject: deleting registry keys and value Message-ID: <1132363655.563531.318090@g14g2000cwa.googlegroups.com> Hi, I am trying to learn how to write, change and delete registry keys and values of a remote computer via Python's _winreg module. So far, I've been able to programmatically create a value and read the value. However, I am unable to figure out how to delete the value. Using the following code, I get the following output: MyNewKey c:\winnt\explorer2.exe 1 Traceback (most recent call last): File "C:\Documents and Settings\sbriley.STAT\Desktop\testreg.py", line 12, in ? DeleteValue(aKey, r"MyNewKey") WindowsError: [Errno 5] Access is denied I have administrative access on the target machine and can delete the key manually by connecting remotely using regedit. Here's the code. BTW, does anyone know how to provide credentials to the remote system if it has a different user/pass than the host system? I don't believe that ConnectRegistry() will allow this. Thanks, Steve from _winreg import * #create the key aReg = ConnectRegistry("remotecomputer",HKEY_LOCAL_MACHINE) aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0, KEY_WRITE) SetValueEx(aKey,"MyNewKey",0, REG_SZ, r"c:\winnt\explorer2.exe") aReg = ConnectRegistry("remotecomputer",HKEY_LOCAL_MACHINE) aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", KEY_ALL_ACCESS) n,v,t = EnumValue(aKey,5) #print out the key print n, v, t CloseKey(aKey) aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", KEY_ALL_ACCESS) DeleteValue(aKey, "MyNewKey") From cito at online.de Sun Nov 20 20:02:36 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 21 Nov 2005 02:02:36 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: Message-ID: Ben Finney wrote: > Without an example, it's hard to know what you want to do and whether > an ordered dictionary is the best way to do it. I have indicated an example, discussed in more detail in another subthread. >> There are already enough competing implementations. > Have they been sufficiently shaken out to show a clearly superior > version? Is any version sufficiently beneficial to write a PEP for its > inclusion in the standard library? At least it shows I'm not the only one who thinks ordered dictionaries may be sometimes nice to have. >> I simply wanted to ask why it is not available in the standard lib, >> since I simply don't know >> - has it not been demanded loud enough? > Loud demands don't count for much. PEPs with popular working > implementations do. Sorry, I did not mean "loud enough" but "often enough". The same what you are calling "popular." >> - because nobody presented a satisfying implementation yet? > I'm not sure what you mean by "satisfying". You can take your own definition: "sufficiently shaken out", "working", "popular", and "succifiently beneficial" and "proven (to the BDFL's criteria)". > Another possibility: ordered dictionaries are not needed when Python > 2.4 has the 'sorted' builtin. The 'sorted' function does not help in the case I have indicated, where "I do not want the keys to be sorted alphabetically, but according to some criteria which cannot be derived from the keys themselves." -- Christoph From tprimke at interia.pl Wed Nov 9 09:11:35 2005 From: tprimke at interia.pl (TPJ) Date: 9 Nov 2005 06:11:35 -0800 Subject: Wrapping C functions in Pyrex and distutils problem Message-ID: <1131545495.855778.145250@g44g2000cwa.googlegroups.com> I'm trying to get a wrapper for my C code in order to be able to use it as a module in Python. I'm doing it as follows: C code (file_c.c): ------------------------------- #include void hello( int size ) { printf("Hello! %d\n", size); } ------------------------------- Pyrex code (file.pyx): ------------------------------- cdef extern void hello( int size ) ------------------------------- Python code (setup.py): ------------------------------- from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = "File", ext_modules=[ Extension( "file", ["file.pyx", "file_c.c"] ) ], cmdclass = { 'build_ext': build_ext } ) ------------------------------- After $ python setup.py build_ext --inplace all is compiled ok, but the shared library (file.so) is built only from one file (file_c.o) - and the second object file (file.o) is ignored. Of course it's imposible to import such a module in Python. What am I doing wrong? From tim.golden at viacom-outdoor.co.uk Wed Nov 9 04:19:24 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 9 Nov 2005 09:19:24 -0000 Subject: Looking Python script to compare two files Message-ID: <9A28C052FF32734DACB0A288A3533991044D2303@vogbs009.gb.vo.local> [yys2000] > I want to compare two PDF or WORD files. Could you be more precise, please? + Do you only want to compare PDF-PDF or Word-Word? Or do you want to be able to do PDF-Word? + In either case, are you only bothered about the text, or is the formatting significant? + If it's only text, then use whatever method you want to extract the text (antiword, ghostscript, COM automation, xpdf, etc.) and then use the difflib module, or some external diff tool. + If you want a structure/format comparison, you're into quite difficult territory, I believe. It's easy enough to convert a Word Doc to PDF if that were needed but PDFs are notoriously difficult to disentangle, altho' relatively straightforward to build. There's pdftools (http://www.boddie.org.uk/david/Projects/Python/pdftools/) which I can't say I've tried, but even once you've got the document object into Python, I don't imagine it'll be easy to compare. + To do Word-Word comparison, there's more hope on the horizon (if that's the metaphor I want). Word has built-in comparison functionality, and recent versions of TortoiseSVN, for example include a script which will automate Word to do the right thing. Which is, essentially, one doc, and call its .Compare method against the other. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From phil at riverbankcomputing.co.uk Thu Nov 17 12:53:42 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 17 Nov 2005 17:53:42 +0000 Subject: PyQt layout question: QScrollView and QGridLayout? In-Reply-To: <3u3jq1Fv4h36U1@news.dfncis.de> References: <3u3jq1Fv4h36U1@news.dfncis.de> Message-ID: <200511171753.42378.phil@riverbankcomputing.co.uk> On Thursday 17 November 2005 2:56 pm, Volker Lenhardt wrote: > For a QApplication (PyQt) on the small screen of my Zaurus 5500 PDA I > try to layout my data output in a QScrollView as the central widget. I'd > prefer to use QGridLayout, but cannot add it to the scroll view. > > sc=QScrollView(self) > layout=QGridLayout(..., sc.viewport()) > sc.addChild(layout) > > results in a TypeError. > > Is there a way to get it to work? Filling a box viewport with lots of > padding boxes and white space labels to establish grids is very > cumbersome. And I need 4 different layouts to change places. QGridLayout is not a sub-class of QWidget, which is what addChild() is expecting. You probably want QGrid. Phil From andrea_gavana at tin.it Sun Nov 6 16:33:32 2005 From: andrea_gavana at tin.it (Andrea Gavana) Date: Sun, 6 Nov 2005 22:33:32 +0100 Subject: Python gui References: Message-ID: <436d25ea$0$6014$4fafbaef@reader4.news.tin.it> Hello Philippe, > Is wxWidget now part of python ? or will it be ? No, I don't think it will ever be part of Python. But, wxWidgets is written in C++, so it has nothing *pythonic* in it. There is, however, a "Python Binding" of wxWidgets, called (obviously ;-) ) wxPython. If you can install a site-package, I would suggest you to visit http://www.wxpython.org/. wxPython has a very active newsgroup and a lot of nice user contribution. If you can not install a site-package, I think that Tkinter is the only choice you have (but I may be wrong here). HTH. Andrea. -- "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77 From aleax at mail.comcast.net Tue Nov 15 11:48:25 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 15 Nov 2005 08:48:25 -0800 Subject: best way to discover this process's current memory usage, cross-platform? References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132037126.467573.184300@o13g2000cwo.googlegroups.com> Message-ID: <1h6283c.11rnxzy16xusl2N%aleax@mail.comcast.net> MrJean1 wrote: > My suggestion would also be to use sbrk() as it provides a high-water > mark for the memory usage of the process. That's definitely what I would have used in the '70s -- nowadays, alas, it ain't that easy. > Below is the function hiwm() I used on Linux (RedHat). MacOS X and > Unix versions are straigthforward. Not sure about Windows. The MacOSX version using sbrk is indeed straightforward, it just doesn't work. See my response to Neal's post and my little Python extension module at http://www.aleax.it/Python/memtry.c -- on a Mac (OSX 10.4, Python 2.4.1, gcc 4.1) sbrk(0) returns the same value as the process's virtual memory consumption goes up and down (as revealed by ps). As the MacOSX's manpage says, "The brk and sbrk functions are historical curiosities left over from earlier days before the advent of virtual memory management." Guess I'll now try the linux version you suggest, with mallinfo: > #if _LINUX > #include > > size_t hiwm (void) { > /* info.arena - number of bytes allocated > * info.hblkhd - size of the mmap'ed space > * info.uordblks - number of bytes used (?) > */ > struct mallinfo info = mallinfo(); > size_t s = (size_t) info.arena + (size_t) info.hblkhd; > return (s); > } and see if and how it works. I do wonder why both Linux and MacOSX "implemented" getrusage, which would be the obviously right way to do it, as such a useless empty husk (as far as memory consumption is concerned). Ah well!-( Alex From steve at holdenweb.com Thu Nov 10 20:13:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 11 Nov 2005 01:13:49 +0000 Subject: Stopping Execution In-Reply-To: References: <1131659313.977724.105960@g44g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > robert.dowell at gmail.com wrote: > > >>import sys >>sys.exit > > > $ more test.py > import sys > print "should get here" > sys.exit > print "should never get here" > > $ python test.py > should get here > should never get here > Which is Fredrik's way of telling you you need to *call* sys.exit and not just reference it (works in Perl, which assumes you want to call it, but in Python "explicit is better than implicit"). $ more test.py import sys print "should get here" sys.exit() print "should never get here" $ python test.py should get here 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 exarkun at divmod.com Sat Nov 12 15:27:01 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 12 Nov 2005 15:27:01 -0500 Subject: XUL behavior in Python via XPCOM, Mozilla In-Reply-To: <20051112142551.1cbe8641@samwise.anansi> Message-ID: <20051112202701.10365.1668323168.divmod.quotient.7061@ohm> On Sat, 12 Nov 2005 14:25:51 -0600, Terry Hancock wrote: >I recently saw a claim that Mozilla XUL behaviors (normally >scripted in Javascript) can (or perhaps will) be scriptable >in Python. > >Also, "other languages such as Java or Python are supported >through XPCOM", said about Mozilla (from Luxor website). > >Yes, I know several ways to *generate* XUL from Python, and >at least one way to use XUL to create interfaces for Python >programs, but in this case, I'm talking about defining >button action behavior in XUL by calling Python scripts. > >I know that Javascript is the preferred language, but I've >seen several references to being able to do this in Python, >including a claim that a release was targeted for early >November (2005), to provide this. > >Now I can't find it again. Anyway, I was hoping someone >on c.l.p / python.org would have a reliable reference on >this. I'm not sure which claim you read, but perhaps it was in reference to PyXPCOM? I'm not quite sure if you are looking for the product itself or the announcement about it. Anyway, hope this helps. Jean-Paul From peterm at resmed.com.au Tue Nov 29 22:47:13 2005 From: peterm at resmed.com.au (Peter Milliken) Date: Wed, 30 Nov 2005 14:47:13 +1100 Subject: wxPython : getting started References: <438c8dc4$1@epflnews.epfl.ch> Message-ID: <6h9jf.213$kQ2.5985@nnrp1.ozemail.com.au> The book that Colin points out looks good - but not available until Jan 2006. When it comes out I might buy it - just out of curiosity :-) Personally I "bounced" when I attempted to learn wxPython - I found it much easier to learn and use Tkinter combined with Pmw. I really tried on the wxPython as well - it wasn't just a 1/2hr exercise :-) I must have spent between 4 - 6 weeks attempting to get my head around it before giving up. The Pmw/TkInter combination was much easier to get up and going with. Pmw is incredibly powerful once you get the ghist of its core i.e. the MegaWidget, MegaArchetype etc. Having said that, I still have my printer utility (Win32) written using wxPython - I never could work out how to get that working with Pmw/TkInter. I just used sockets to transfer the text to be printed between the wxPython print utility and my TkInter/Pmw based application :-) Peter "David Sulc" wrote in message news:438c8dc4$1 at epflnews.epfl.ch... > Hi ! > > I've looked all over (internet, books, etc.) and I haven't found a very > good ressource to get started with wxPython (yes, I've been through > their tutorial). > > What I would basically like to do for starters is to be able to define > the main panel being displayed. For example : > 1. wxFrame contains a wxPanel (call it mainPanel). > 2. mainPanel contains another panel (childPanelA) > 3. another panel has been defined (childPanelB) but is not displayed > (the user can only see childPanelA inside mainPanel) > 4. by clicking on a menu entry (for example), the displayed panel is now > childPanelA (which is inside mainPanel) > > So how do I do this ? I realize it's a very basic question, but it's > been driving me mad... > > Also, is there any good open source wxPython program that I could study ? > > Thanks for any help... From rapp at acm.org Tue Nov 8 15:17:21 2005 From: rapp at acm.org (rapp at acm.org) Date: 8 Nov 2005 12:17:21 -0800 Subject: [ANN] SMC - State Machine Compiler v. 4.3.0 Message-ID: <1131481041.245745.110770@f14g2000cwb.googlegroups.com> SMC - The State Machine Compiler v. 4.3.0 Requires: Java 1.4.1 SE (Standard Edition) or better. Download: http://sourceforge.net/projects/smc Home Page: http://smc.sourceforge.net ================================================================= What's New? ================================================================= + Added -reflect option for Java, C#, VB.Net and Tcl code generation. When used, allows applications to query a state about its supported transitions. Returns a list of transition names. This feature is useful to GUI developers who want to enable/disable features based on the current state. See Programmer's Manual section 11: On Reflection for more information. + Updated LICENSE.txt with a missing final paragraph which allows MPL 1.1 covered code to work with the GNU GPL. + Added a Maven plug-in and an ant task to a new tools directory. Added Eiten Suez's SMC tutorial (in PDF) to a new docs directory. ================================================================= Bug fixes ================================================================= + (GraphViz) DOT file generation did not properly escape double quotes appearing in transition guards. This has been corrected. + A note: the SMC FAQ incorrectly stated that C/C++ generated code is thread safe. This is wrong. C/C++ generated is certainly *not* thread safe. Multi-threaded C/C++ applications are required to synchronize access to the FSM to allow for correct performance. + (Java) The generated getState() method is now public. ================================================================= What is SMC? ================================================================= SMC takes a state machine description (stored in a .sm file) and generates State pattern classes in a target language (C, C++, C#, Java, Perl, Python, Ruby, Tcl and VB.Net are currently supported). SMC is a console-based app written in Java which means SMC can run anywhere Java (1.4.1 or better) can run. The download package includes a document and example directory showing how SMC can used with C, C++, C#, Java, Perl, Python, Ruby, Tcl (requires [incr Tcl] package) and VB.Net. The examples range from trivial to GUI apps. ================================================================= How can I learn more? ================================================================= At http://smc.sourceforge.net. You can access the SMC Programmer's Manual there as well. While you're there, check out the SMC demo applet at http://smc.sourceforge.net/SmcDemo.htm. ================================================================= Where can I get it? ================================================================= SMC and the Programmer's Manual can be downloaded from http://sourceforge.net/projects/smc. You can also use this website to: + Ask questions (via the Public Forum's Help discussion) + Submit a bug. + Join a mailing list. + Access SMC documentation. + Access SMC's source code in the CVS repository. (Note: in order to make full use of SourceForge capabilities, you must be a SourceForge member. If you are not a member, head over to http://sourceforge.net/account/register.php and sign up. SourceForge membership is free - no money, no requirements and NO SPAM! Membership has its benefits.) If you have any problems, surf over to http://sourceforge.net/forum/forum.php?forum_id=27865 and report the problem. I will try and answer you via the Help forum as quickly as I can. Enjoy! Charles Rapp From opengeometry at yahoo.ca Wed Nov 9 20:34:29 2005 From: opengeometry at yahoo.ca (William Park) Date: Wed, 09 Nov 2005 20:34:29 -0500 Subject: XML GUI References: <1131457704.275657.237970@g49g2000cwa.googlegroups.com> Message-ID: <3f7f9$4372a3a5$d1b717e1$3433@PRIMUS.CA> py wrote: > Looking for information on creating a GUI using a configuration file > (like an XML file or something). Also, how do you map actions (button > clicks, menu selections, etc) to the XML? > > Any other suggestions for building GUI's for Python projects...even > Jython. If you're talking about simple "dialog" thing, where you ask question and users respond, then take a look at http://home.eol.ca/~parkw/index.html#gtk Also, you may want to look at Glade which spits out the layout in XML. But, for more intricate to-and-fro, use C and GTK+2. :-) -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From wuwei23 at gmail.com Tue Nov 1 21:51:25 2005 From: wuwei23 at gmail.com (alex23) Date: 1 Nov 2005 18:51:25 -0800 Subject: Flat file, Python accessible database? In-Reply-To: References: Message-ID: <1130899885.108485.173650@g49g2000cwa.googlegroups.com> Karlo Lozovina wrote: > I've been Googling around for _small_, flat file (no server processes), > SQL-like database which can be easily access from Python. Although it doesn't support SQL queries, Metakit (http://www.equi4.com/metakit/python.html) is a very lightweight and easy to use db with a nicely pythonic API. -alex23 From nico-NoSp at m-tekNico.net Wed Nov 16 09:32:35 2005 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Wed, 16 Nov 2005 15:32:35 +0100 Subject: best way to discover this process's current memory usage, cross-platform? In-Reply-To: <1132136375.267076.116850@g14g2000cwa.googlegroups.com> References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132080864.280909.51540@g44g2000cwa.googlegroups.com> <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> <1132121442.019702.66620@g47g2000cwa.googlegroups.com> <1132136375.267076.116850@g14g2000cwa.googlegroups.com> Message-ID: <437b430e$1_3@newsgate.x-privat.org> > On the subject of memory statistics, I'm surprised no-one has mentioned > "top" in this thread (as far as I'm aware): I would have thought such > statistics would have been available to "top" and presented by that > program. Talking about "top", this article may be useful: On measuring memory usage http://www.kdedevelopers.org/node/1445 -- Nicola Larosa - nico-NoSp at m-tekNico.net ...Linux security has been better than many rivals. However, even the best systems today are totally inadequate. Saying Linux is more secure than Windows isn't really addressing the bigger issue - neither is good enough. -- Alan Cox, September 2005 From dieter at handshake.de Tue Nov 15 13:36:40 2005 From: dieter at handshake.de (Dieter Maurer) Date: 15 Nov 2005 19:36:40 +0100 Subject: Python-based Document Management System? References: Message-ID: "W. Borgert" writes on Thu, 10 Nov 2005 14:43:14 +0100: > I'm looking for a Python-based DMS, but I don't know any. > The following points are relevant: > > - suitable for 10..100 users with more than 10000 documents > > - documents are mostly proprietary formats: MS Word, MS Excel, > MS PowerPoint, but maybe also: PDF, HTML, DocBook, ... > > - typical DMS features: access control, archive older > versions, search/query, document hierarchy, web frontend You may have a look at Plone, Silva and CPS (all Zope based). Dieter From steve at REMOVETHIScyber.com.au Sun Nov 13 10:25:31 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 14 Nov 2005 02:25:31 +1100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <43770305$0$5294$636a15ce@news.free.fr> <4377247a$0$12627$636a15ce@news.free.fr> Message-ID: On Sun, 13 Nov 2005 12:33:48 +0100, Pierre Barbier de Reuille wrote: > Steven D'Aprano a ?crit : >> On Sun, 13 Nov 2005 10:11:04 +0100, Pierre Barbier de Reuille wrote: >> >> >>>The problem, IMHO, is that way you need to declare "symbols" >>>beforehands, that's what I was trying to avoid by requiring a new syntax. >> >> >> ??? >> >> If you don't declare your symbols, how will you get the ones that you want? >> >> I don't understand why it is a problem to declare them first, and if it is >> a problem, what your solution would be. >> > > Well, just as Python do not need variable declaration, you can just > *use* them ... in dynamic languages using symbols, they just get created > when used (i.e. have a look at LISP or Ruby). If you want to be technical, Python doesn't have variables. It has names and objects. If I want a name x to be bound to an object 1, I have to define it (actually bind the name to the object): x = 1 If I want a symbol $x$ (horrible syntax!!!) with a value 1, why shouldn't I define it using: $x$ = 1 instead of expecting Python to somehow magically know that I wanted it? What if somebody else wanted the symbol $x$ to have the value 2 instead? >> [snip] >> >> >>>Well, I don't think enumarated objects ARE symbols. I can see two >>>"problems" : >>> 1 - in the implementation, trying to compare values from different >>>groups raises an error instead of simply returning "False" (easy to fix ...) >> >> >> As you say, that's easy to fix. >> >> >>> 2 - You have to declare these enumerable variables, which is not >>>pythonic IMO (impossible to fix ... needs complete redesign) >> >> >> Are you suggesting that the Python language designers should somehow >> predict every possible symbol that anyone in the world might ever need, >> and build them into the language as predefined things? >> >> If that is not what you mean, can you explain please, because I'm confused. >> > > Well, the best I can propose is for you to read the discussion with Mike > Meyer. > He pointer out the flaws in my proposal and we're trying to precise things. I've read the discussion, and I am no wiser. You haven't explained why enums are not suitable to be used for symbols. You gave two "problems", one of which was "easy to fix", as you said yourself, and the other reason was that you don't want to define enums as symbols. If you don't want to define something manually, that can only mean that you expect them to be predefined. Or am I misunderstanding something? -- Steven. From everettcc at hotmail.com Thu Nov 17 21:30:45 2005 From: everettcc at hotmail.com (Chad Everett) Date: Thu, 17 Nov 2005 20:30:45 -0600 Subject: newb ? References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> <1132279704.095131.129440@g44g2000cwa.googlegroups.com> Message-ID: <4%aff.4810$i7.2845@bignews2.bellsouth.net> Mensanator, Thanks for your help. That should get me along. I appreciate your time. Chad wrote in message news:1132279704.095131.129440 at g44g2000cwa.googlegroups.com... > > Chad Everett wrote: >> Hey guys, >> >> I am back. Trying to expand on a program that was given in the book I >> am >> studying. >> >> No I am not a high school or college student. Doing this on my own. and >> having way to much trouble >> >> I am trying to add a hint section to a word jumble program. >> >> I get a traceback error that the word in the jumble is not defined. >> Can anyone help? > > You have several errors. > >> thanks, >> >> import random >> >> # create a sequence of words to choose from >> WORDS = ("python", "easy") >> # pick one word randomly from the sequence >> word = random.choice(WORDS) >> # create a variable to use later to see if the guess is correct >> correct = word >> # create variable to use for hint if needed > > You didn't create a variable here. Something like > > hint = "hint" > > And this is the core of your problems. You are confusing a > variable name with the value assigned to it. > > >> # create a jumbled version of the word >> jumble ="" >> while word: >> position = random.randrange(len(word)) >> jumble += word[position] >> word = word[:position] + word[(position + 1):] >> >> # start the game >> print \ >> """ >> Welcome to Word Jumble! >> >> Unscramble the letters to make a word. >> (Press the enter key at the prompt to quit.) >> """ >> print "The jumble is:", jumble >> print "If you need a hint type 'hint' and Hit enter." > > Here you have specifically told the user that the hint word is "hint". > >> >> guess = raw_input("\nYour guess: ") >> guess = guess.lower() >> while (guess != correct) and (guess != "")and (guess != hint): ##not sure >> about this either## > > It will fail because you did not define the hint variable. > Note you actually don't need a hint variable (because the > hint word never changes), you could have said > > ... and (guess != "hint") > > whereas (guess != correct) needs to compare against a variable > because correct does change. > >> print "Sorry, that's not it." >> guess = raw_input("Your guess: ") >> guess = guess.lower() >> >> >> ###I don"t lnow how to set up this part correct so that when they ask for >> the hint it will give it to them### >> >> >> while word == easy: > > Same problem here, easy is a variable (which you haven't defined). > What you meant to say was > > while word == "easy": > > >> if guess == hint: >> print "not hard but" >> guess = raw_input("Your guess: ") >> guess = guess.lower() >> >> while word == python: > > Ditto. But this is going to get tedious when your word list gets large. > You should have your words and their hints stored in a dictionary: > > hints = {'easy':'not hard but','python':'snake'} > > then you need just a single code block that can print the hint > by using the correct word to look up the hint in the dictionary. > > if guess == hint: > print hints[correct] > guess = raw_input("Your guess: ") > guess = guess.lower() >> >> if guess == correct: >> print "That's it! You guessed it!\n" >> >> print "Thanks for playing." >> >> raw_input("\n\nPress the enter key to exit.") > From eight02645999 at yahoo.com Sat Nov 12 04:48:08 2005 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 12 Nov 2005 01:48:08 -0800 Subject: passing values from one form to another Message-ID: <1131788888.332355.103660@g43g2000cwa.googlegroups.com> hi i have 3 python cgi scripts created, one is a login page(login.py), another is the main page(main.py) with a lot of user inputs and the last one is a python cgi script results.py to process main.py In main.py, i am able to check for the value of the user and password field, eg if form.has_key("user") and form["button"].value == "Login" and form.has_key("password"): # show all fields how can i also check for the user field in the results.py script? ie , pass the value of the "user" to the python script..so that user must always login to get to results.py.... thanks.. From tnoell at gmail.com Wed Nov 16 15:43:20 2005 From: tnoell at gmail.com (tnoell at gmail.com) Date: 16 Nov 2005 12:43:20 -0800 Subject: readline vi mode in python interactive shell In-Reply-To: References: <1132171451.328876.177210@z14g2000cwz.googlegroups.com> Message-ID: <1132173800.042990.227990@g44g2000cwa.googlegroups.com> Well, I subsequently found this: http://groups.google.com/group/gnu.bash.bug/browse_thread/thread/ab3d3d5ff3e1ea89/f50f81b86161b271?lnk=st&q=readline+vi+mode&rnum=25#f50f81b86161b271 to explain it. Bummer ... From xray_alpha_charlie at yahoo.com Mon Nov 14 17:52:49 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Mon, 14 Nov 2005 14:52:49 -0800 (PST) Subject: Is Python worth it?? Message-ID: <20051114225249.89689.qmail@web35901.mail.mud.yahoo.com> I have started out trying to learn Python for my first programming language. I am starting off with the book "how to think like a computer scientist." I spend about 4-5 hrs a day trying to learn this stuff. It is certainly no easy task. I've been at it for about 1-2 weeks now and have a very elementary picture of how Python works. I am teaching myself from home and only recieve help from this forum. Can anybody give me a timeframe as to how long it usually takes to pick something like this up, so I can maybe figure out a way to pace myself? I can dedicate a good amount of time to it everyday. Any advice on what is the best way to learn Python? I am a fairly educated individual with a natural sciences degree (forestry), so I also have a decent math background. Are there any constraints mathematically or logic "wise" that would prevent me from building a firm grasp of this language? --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan at naewe.de Wed Nov 2 15:34:58 2005 From: stefan at naewe.de (Stefan =?UTF-8?B?TsOkd2U=?=) Date: Wed, 02 Nov 2005 21:34:58 +0100 Subject: Hexadecimal Conversion in Python References: <1130963306.183112.3720@g49g2000cwa.googlegroups.com> Message-ID: DaBeef wrote: > Hello, I am reading in a socket message from a server and am only > receiving this '....'. Now obviously it is in the wrong format. How > would I convert these bys in Python, I have looked everywhere but I do > not see much documentation on converting ptyhon types to other data > types. What is the server supposed to send (you need to know that if you want to decode it). Then, lookup struct.unpack . HTH Stefan From frank at chagford.com Tue Nov 29 10:40:24 2005 From: frank at chagford.com (Frank Millman) Date: 29 Nov 2005 07:40:24 -0800 Subject: sax.make_parser() segfaults Message-ID: <1133278824.029426.142640@z14g2000cwz.googlegroups.com> Hi all I am using Python 2.4.1. I have machines running FC4, RH9, and MSW Server 2003 for testing. If I call sax.make_parser() from the interpreter or from a stand-alone program, it works fine on all machines, but in the following setup it works correctly on MSW, but segfaults on both FC4 and RH9. The setup is a client program running wxPython as a gui, and Twisted as a means of connecting to a server. Both wxPython's and Twisted's main loops seem to be running ok. I have made a remote call to a Twisted server, which has returned an xml string. In the callback routine, I print the xml for debugging purposes, which looks fine, then I call 'parser = sax.make_parser()'. At that point it segfaults. I added a 'print sax' command just before the call to ensure it is valid. It displays , which looks correct. A little digging reveals that the segfault occurs in xml/parsers/expat.py, when it tries to execute 'from pyexpat import *'. On FC4 and RH9, pyexpat.so is in python2.4/lib-dynload. On MSW, there is a pyexpat.pyd in Python24/DLLSs, and a pyexpat.lib in Python24/libs. I don't know if any of this is relevant, but I thought I would supply as much info as possible. As mentioned above, I do not have the problem with MSW. Any suggestions will be much appreciated. Thanks Frank Millman From http Fri Nov 11 22:24:06 2005 From: http (Paul Rubin) Date: 11 Nov 2005 19:24:06 -0800 Subject: Internal Variables References: Message-ID: <7xu0eio8fd.fsf@ruckus.brouhaha.com> James Colannino writes: > Basically, I just want to know how from within a script I can get > information about the python interpreter that I'm running. Thanks in > advance. import sys print sys.version From onurb at xiludom.gro Wed Nov 16 13:54:17 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 16 Nov 2005 19:54:17 +0100 Subject: HTML generation vs PSP vs Templating Engines In-Reply-To: <1132158690.299954.90920@g14g2000cwa.googlegroups.com> References: <1132158690.299954.90920@g14g2000cwa.googlegroups.com> Message-ID: <437b805a$0$625$626a14ce@news.free.fr> pkassianidis at gmail.com wrote: > Hello everybody, > > I am in the process of writing my very first web application in Python, > and I need a way to > generate dynamic HTML pages with data from a database. (snip) > After some thought I decided to leave the various frameworks > aside for the > time being and use mod_python.publisher I know this is not exactly an answer to your question, but have you tried Django ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From khemkaamit at gmail.com Wed Nov 23 00:51:51 2005 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 23 Nov 2005 11:21:51 +0530 Subject: matching a string to extract substrings for which somefunctionreturns true In-Reply-To: References: <1360b7230511220418q6ede018bhcd80655f8a4f1530@mail.gmail.com> Message-ID: <1360b7230511222151y75228df0w70ed5cd28eb2b241@mail.gmail.com> thanks for you suggestions :-) .. cheers, On 11/23/05, Fredrik Lundh wrote: > I wrote: > > > if you cannot cache session data on the server side, I'd > > recommend inventing a custom record format, and doing your > > own parsing. turning your data into e.g. > > > > "foo:1:foobar:3:0+foo1:2:foobar1:3:1+foo2:2:foobar2:3:2" > > > > is trivial, and the resulting string can be trivially parsed by a couple > > of string splits and int() calls. > > on the other hand, the "myeval" function I posted here > > http://article.gmane.org/gmane.comp.python.general/433160 > > should be able to deal with your data, as well as handle data from > malevolent sources without bringing down your computer. > > just add > > if token[1] == "(": > out = [] > token = src.next() > while token[1] != ")": > out.append(_parse(src, token)) > token = src.next() > if token[1] == ",": > token = src.next() > return tuple(out) > > after the corresponding "[" part, and call it like: > > data = myeval("[" + input + "]") > > > > > > -- > 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 rschroev_nospam_ml at fastmail.fm Sat Nov 12 11:37:59 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 12 Nov 2005 16:37:59 GMT Subject: weird problem with os.chmod In-Reply-To: References: <43753C13.2010609@colannino.org> <43753D14.8040400@colannino.org> Message-ID: Gary Herron wrote: > James Colannino wrote: > >> James Colannino wrote: >> >> >> >>> So then I entered the command print 0600, and saw that the actual >>> number being output was 384 (why would it output 384?!) >>> >>> >>> >> >> >> Ok, so further research revealed that 0600 is actually the octal >> representation for 384 (which makes sense.) So then, I guess my >> question would have to be, is there a way for me to make Python aware >> that the 0600 I'm passing to int() is octal and not decimal so that I >> will get 384 instead of 600? >> >> > int('0600',8) will do, but why would you want to do that? > > Any of > x = 0600 > x = 384 > x = 0x180 > x = int('0600',8) > will bind x to the same value (110000000 in binary if you care). > > But once you've got the valued defined, through whatever human readable > representation you want, the command > chmod(filename, x) > can be issued without further thought. He reads the string ('0600' in this case, but I guess it can be any permission) from a file. So he doesn't have the numerical value to begin with. BTW, I guess it's safer to do int(permission, 8) than int(permission, 0), since the first digit isn't guaranteed to be zero: it is used for set user ID, set group ID and the sticky bit. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From bulliver at badcomputer.org Sun Nov 27 18:13:41 2005 From: bulliver at badcomputer.org (darren kirby) Date: Sun, 27 Nov 2005 15:13:41 -0800 Subject: exception KeyboardInterrupt and os.system command Message-ID: <200511271513.48021.bulliver@badcomputer.org> Hello all. I have a python script here which is just a wrapper for 2 or more system commands. I would estimate the program spends at least 95.5% of 'real' time running the system commands. I want to trap the [crtl-c] key combo and exit (somewhat) gracefully if the user decides to abort the program. I am using os.system for the system call, and I have wrapped the entire main loop in a try: except KeyboardInterrupt statement to try to attain these ends. As it is though, if the program is currently in the system command, only that system command is terminated, and the next loop of my program starts. Is there a way to make this work? ie: terminate the entire script? Will popen do this? I don't really want to use popen because all I need is for the system command to run, and check the exit status. Also, popen will pooch the output of the system commands (which I want to be printed to the console) because the system commands (faad, mpg123, and oggenc) have buffered output which won't properly be displayed if I simply print each line of the file object returned by popen. I don't want to use subprocess because I can't expect my users to have 2.4 installed... OS is Linux, if it matters. If you need to see the code it is here: http://badcomputer.org/unix/dir2ogg/dir2ogg.bot Although, this code is the program as it stands, not the code I am testing. Thanks, -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From pmartin at snakecard.com Mon Nov 7 11:50:21 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Mon, 07 Nov 2005 16:50:21 +0000 Subject: Tkinter and X11 References: Message-ID: Thanks jeff, I actually want that Tkinter application to be the greater: replace gdm.... Still feasible as far as Tkinter is conserned ? Thanks and regards, Philippe jepler at unpythonic.net wrote: > There should be no problem with this. After all, even the "greeter" is > just an > X application. Depending on which login manager you use > (xdm/kdm/gdm/whatever) the details of getting your Tkinter app to actually > be run will vary, though. In gdm, it looks like adding it to the file > /etc/X11/gdm/Init/default may be the ticket. > > It is probably best to run > app.tk.call("rename", "send", "") > in your program, for the reasons outlined in the send(n) manpage: > SECURITY > The send command is potentially a serious security loophole. On > Unix, > any application that can connect to your X server can send > scripts to > your applications. These incoming scripts can use Tcl to > read and > write your files and invoke subprocesses under your name. > > Jeff From martin at v.loewis.de Fri Nov 25 17:49:31 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 25 Nov 2005 23:49:31 +0100 Subject: Move xml.sax.saxutils.*? In-Reply-To: <1132949881.719999.162010@g44g2000cwa.googlegroups.com> References: <1132949881.719999.162010@g44g2000cwa.googlegroups.com> Message-ID: <438794FB.5070201@v.loewis.de> chris.atlee at gmail.com wrote: > It seems like functions such as xml.sax.saxutils.escape and unescape > are generally useful, and not at all tied to the xml.sax module. Would > it make sense to move them somewhere else, like to xml? Moving it would be a bad idea. Exposing it elsewhere would be useful. The precise details are best discussed at xml-sig at python.org. While this is obviously wrong, it is not at all obvious what the right thing to do is (it never is when dealing with XML). Regards, Martin From matthewharrison at gmail.com Tue Nov 15 13:54:24 2005 From: matthewharrison at gmail.com (matt) Date: 15 Nov 2005 10:54:24 -0800 Subject: best way to discover this process's current memory usage, cross-platform? References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> Message-ID: <1132080864.280909.51540@g44g2000cwa.googlegroups.com> Perhaps you could extend Valgrind (http://www.valgrind.org) so it works with python C extensions? (x86 only) matt From kevin.bell at slcgov.com Wed Nov 2 18:18:20 2005 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Wed, 2 Nov 2005 16:18:20 -0700 Subject: convert COM obj to integer Message-ID: <2387F0EED10A4545A840B231BBAAC722607FA1@slcimail1.slcgov.com> Well that looks quite nice, so I'll work that into my script. Thanks!!! That 1-tuple business was confusing me, and I was getting errors stating something about converting an object, so as you can see, I was grasping at straws. -----Original Message----- From: python-list-bounces+kevin.bell=slcgov.com at python.org [mailto:python-list-bounces+kevin.bell=slcgov.com at python.org] On Behalf Of Steve M Sent: Wednesday, November 02, 2005 3:56 PM To: python-list at python.org Subject: Re: convert COM obj to integer I don't know exactly what a COM object is, but those aren't them. The win32com package takes care of converting everything to Python types. The excel call returns a tuple of tuples. That is, the outer tuple is the sequence of rows, and each such row is itself a tuple with one member per column requested. Since you only request one column, it is a one-item-long tuple, also called a 1-tuple. That is demonstrated by the result of print'ing the list. By the way, you shouldn't use 'list' as a name because it is also the name of a built-in function. And it isn't a list anyway, it's a tuple. Now, each number is in fact already a primitive Python object of type float. (The asterisk is a unicode string.) So you want to convert the floats into integers, and it looks like you want to round rather than truncate. ---- table = xlApp.ActiveWorkbook.ActiveSheet.Range("Q13:Q36") converted_values = [] for row in table: value = row[0] #get the first (and only) item in the tuple try: value = round(value) except TypeError: #value is not a float value = None else: value = int(value) #turn the float into an int converted_values.append(value) print converted_values ---- By the way, if you wonder how I knew to catch the TypeError, I just fired up the interactive Python interpreter, and typed this: round(u'*') -- http://mail.python.org/mailman/listinfo/python-list From mwm at mired.org Sat Nov 5 03:35:53 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 03:35:53 -0500 Subject: re sub help References: <1131173343.954029.211530@o13g2000cwo.googlegroups.com> <86br0z7e3w.fsf@bhuda.mired.org> <1131177215.248797.268670@f14g2000cwb.googlegroups.com> Message-ID: <8664r77aqe.fsf@bhuda.mired.org> s99999999s2003 at yahoo.com writes: > i am still interested about using re, i find it useful. am still > learning it's uses. > so i did something like this for a start, trying to get everything in > between [startdelim] and [enddelim] > > a = > "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" > > t = re.compile(r"\[startdelim\](.*)\[enddelim\]") > > t.findall(a) > but it gives me []. it's the "\n" that prevents the results. > why can't (.*) work in this case? Or am i missing some steps to "read" > in the "\n"..? > thanks. Newlines are magic to regular expressions. You use the flags in re to change that. In this case, you want . to match them, so you use the DOTALL flag: >>> a = "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" >>> t = re.compile(r"\[startdelim\](.*)\[enddelim\]", re.DOTALL) >>> t.findall(a) ['this\nis\nanother'] >>> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bonono at gmail.com Thu Nov 24 06:27:43 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 03:27:43 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: <1132829997.320905.47980@g14g2000cwa.googlegroups.com> Message-ID: <1132831663.116973.312110@o13g2000cwo.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > > These results make more sense. However, I am still puzzled : > > > > 1. why would d.keys()/d.values() only return one list element ? Why > > isn't it a list of 1M element of either the keys or values but items() > > is ? > > "keys" returns a single list object which contains references to existing > key objects. "items" has to create one million new pair objects (which > in turn hold references to existing key and value objects). > Ah, that is clearer now. So keys()/items() create a list of 1M reference(object identity?) to existing objects, items() also contains 1 M reference, but to a newly created 1M tuples. How about the other puzzle of whether seperate keys()/values() pair have real performance gain in real use ? From petantik.fool at gmail.com Thu Nov 10 11:23:07 2005 From: petantik.fool at gmail.com (petantik) Date: 10 Nov 2005 08:23:07 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> Message-ID: <1131639786.958533.45070@z14g2000cwz.googlegroups.com> Alex Martelli wrote: > Anand S Bisen wrote: > > > I dont know much !! But if somebody asks me this question my answer > > would be to convert some of the meat inside my programs to C/C++ and > > then provide the interface to those novel ideas to Python using swig. > > And for another level of protection maybe use these offuscator on the > > remaining Python source. What do you think ? > > I think that's feeble protection. If you have valuable code, and > distribute it, people WILL crack it -- just check the warez sites for > experimental proof... EVERYTHING that people are really interested in > DOES get cracked, no matter what tricky machine-code the "protections" > are coded in. > > There's ONE way to have uncrackable code -- don't distribute it, but > rather put it up on the net on a well-secured machine under your > control, available as (say) a webservice (subscription-only, pay per > use, or whatever business model you want). You can distribute all the > parts of your app that aren't worth protecting as a "fat client" app (in > Python or whatever) and keep those which ARE worth protecting on the > server that YOU control (and make sure it's very, VERY safe, of course); > and you may write the precious parts in Python, too, no problem. > > This is (a minor) one of the many reasons that make webservices the way > of the future (hey, even *MSFT* noticed that recently, it seems...). > There are many other advantages, especially if you keep the clients > thin. The only issue is, your apps will require network connectivity to > execute... but these days, with airlines and train lines busy adding > wi-fi, and towns busily blanketing themselves with free wi-fi, etc, etc, > that's less and less likely to be a big problem... > > > Alex I think that is not workable because it is easy to say the the internet is available everywhere. It is not available in developing countries or in rural areas and so these people who live/work there will never benefit from a webservice type protection scheme, and what if the network in your area goes down? bye bye app that I *really* need for tomorrow. Reliability is important but so is protecting your code in an effective manner I do believe that you are right about those that crack software for kicks or money. If you look around at you local market place i'm sure there are many 'discounted' commercial softwares/games sold. of course the big software companies might say 'trusted computing will save us' but I for one will never truly trust it. Perhaps a comprehensive protection for interpreted languages can never be built because of their high level nature? From aleax at mail.comcast.net Sat Nov 12 21:26:09 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 12 Nov 2005 18:26:09 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <1h5ty4g.1onzjda6fc7xmN%aleax@mail.comcast.net> <86ek5l3ho2.fsf@bhuda.mired.org> Message-ID: <1h5xefn.hsrciidr3dmgN%aleax@mail.comcast.net> Steven D'Aprano wrote: > In a competitive marketplace, why would I choose to buy DRMed software if > there is a non-DRMed equivalent with the same functionality and equivalent > cost? The only explanation I can think of is, their marketing must be AWEsome!-) Alex From __peter__ at web.de Fri Nov 18 08:50:53 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Nov 2005 14:50:53 +0100 Subject: Yield in a wrapper function References: <1132319319.419585.9600@g44g2000cwa.googlegroups.com> Message-ID: peterbe at gmail.com wrote: > from?time?import?sleep > def?foo(on): > for?e?in?list(on): Just for e in on: #... is better. The list() constructor defeats much of the laziness you gain by using a generator. > sleep(1) > yield?e > > def?wrapper(x): > if?x? return?foo('ABC') > else: > return?foo('XYZ') > > When I run this, variable three letters are shown and it takes 3 > seconds for the whole thing to complete. The problem is that the whole > iteration is glogged up in the wrapper() function because the first > letter is shown after 3 seconds and then all letters are shown at the > same time. > > How do I wrap functions that return iterators? ...if possible. The code you presented is OK. Your diagnosis is probably the result of a of a misconstrued test case. Something like for s in wrapper(1): print s, seems to work like you described because the text is buffered until the line is complete. Try for s in wrapper(1): print s or import sys for s in wrapper(1): print s, sys.stdout.flush() # explicitly flush the buffer instead. Peter From duncan.booth at invalid.invalid Tue Nov 29 11:13:28 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Nov 2005 16:13:28 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> Message-ID: Dan Bishop wrote: >> Is there any place in the language that still requires tuples instead >> of sequences, except for use as dictionary keys? > > The % operator for strings. And in argument lists. > > def __setitem__(self, (row, column), value): > ... > Don't forget the exception specification in a try..catch statement: > An object is compatible with an exception if it is either the object > that identifies the exception, or (for exceptions that are classes) it > is a base class of the exception, or it is a tuple containing an item > that is compatible with the exception. Requiring a tuple here means that the code doesn't have to worry about a possible recursive data structure. From cito at online.de Sun Nov 20 07:47:05 2005 From: cito at online.de (Christoph Zwerschke) Date: Sun, 20 Nov 2005 13:47:05 +0100 Subject: Why are there no ordered dictionaries? Message-ID: This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part of the standard library: http://groups.google.com/group/comp.lang.python/msg/e652d2f771a49857 Are there plans to get it into the standard lib sometime? -- Christoph From daniel.evers at rwth-aachen.de Sat Nov 12 10:52:57 2005 From: daniel.evers at rwth-aachen.de (Daniel Evers) Date: Sat, 12 Nov 2005 16:52:57 +0100 Subject: What do you use as symbols for Python ? References: <4372f88a$0$31833$636a15ce@news.free.fr> <1131653466.538695.69890@f14g2000cwb.googlegroups.com> <3tk628Fsqa6aU1@news.dfncis.de> Message-ID: <3tmheqFtnu6sU1@news.dfncis.de> Peter Otten wrote: > > You should ditch what follows and instead add just > > def __iter__(self): > return iter(self.__keys) Mhh. I should start learning the builtins ... :) > To see the problem with your original code (an object serving as its own > iterator) try the following example: > > friends = Enum("Eric", "Kyle", "Stan", "Kenny") > if "Kyle" in friends: > print "Hi Kyle" > print "My friends:", ", ".join(friends) > > Only Stan and Kenny show up in the last print statement because the > containment test did not iterate over all friends. Never would have thought of this... Makes it even easier. > Also, Type.__name seems redundant. Just > > class Type(str): pass > > should do the job. Right, works just fine. I'm not used to types, meanwhile I replaced Type(str) by a simple class Type, works as well. Thanks a lot, I was starting to integrate this solution in my code, now I can fix it before it's even used :) Daniel From stefan_NOSPAM at NOSPAM_naewe.de Wed Nov 2 09:50:30 2005 From: stefan_NOSPAM at NOSPAM_naewe.de (Stefan =?UTF-8?B?TsOkd2U=?=) Date: Wed, 02 Nov 2005 15:50:30 +0100 Subject: where to download md5.py? References: Message-ID: Bell, Kevin wrote: > I've been looking around, but haven't found a place to download the > md5.py module. I need it to run the dupinator.py > > Anyone know where to find it? Google knows... Stefan -- From bignose+hates-spam at benfinney.id.au Thu Nov 3 19:56:05 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 4 Nov 2005 11:56:05 +1100 (EST) Subject: ADT for restricted set of values Message-ID: Howdy all, I'd like to have an Abstract Data Type for a scalar value that is restricted to a small set of values. Like an Enum, I suppose. What I would like is to be able to use simple 'str' values in most of the code, but where the values are actually used in a semantically meaningful context, have them used as an ADT that will barf if the value isn't part of the set. Using the HumanSex class example from an earlier thread: class HumanSex(str): _descriptions = { None: "unknown", 'male': "Male", 'female': "Female", } def __init__(self, value): str.__init__(value) if value not in self._descriptions: raise ValueError, \ "Not a valid HumanSex value: '%s'" % value def __get_description(self): return self._descriptions[self] description = property(__get_description) This way, most of the rest of the code doesn't need to know that the HumanSex instances are anything but a simple 'str' value. Is this a sensible way to do what I'm describing? Am I missing a common programming pattern? -- \ "I bought a self learning record to learn Spanish. I turned it | `\ on and went to sleep; the record got stuck. The next day I | _o__) could only stutter in Spanish." -- Steven Wright | Ben Finney From i_vincent at hotmail.com Thu Nov 10 03:33:20 2005 From: i_vincent at hotmail.com (Ian Vincent) Date: 10 Nov 2005 08:33:20 GMT Subject: How to use generators? References: Message-ID: Tom Anderson wrote in news:Pine.LNX.4.62.0511091853420.25586 at urchin.earth.li: > > Exactly - using a queue means you'll do a breadth-first rather than a > depth-first search, which will involve much less depth of recursion. > See: Thanks for the answers but found a easier (admittedly cheating) way around the problem....run the code on my 64bit Linux system at home. From dave at pythonapocrypha.com Wed Nov 30 11:24:09 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 30 Nov 2005 09:24:09 -0700 Subject: python speed In-Reply-To: <_eqdnYiZUra9XxDenZ2dnUVZ_sadnZ2d@comcast.com> 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: <438DD229.5060804@pythonapocrypha.com> Steven Bethard wrote: > David Rasmussen wrote: > >>Harald Armin Massa wrote: >> >> >>>Dr. Armin Rigo has some mathematical proof, that High Level Languages >>>like esp. Python are able to be faster than low level code like >>>Fortran, C or assembly. >> >>Faster than assembly? LOL... :) > > > I think the claim goes something along the lines of "assembly is so hard > to get right that if you can automatically generate it from a HLL, not > only will it be more likely to be correct, it will be more likely to be > fast because the code generator can provide the appropriate optimizations". > > OTOH, you can almost certainly take automatically generated assembly > code and make optimizations the code generator wasn't able to, thanks to > knowing more about the real semantics of the program. Yeah, but the other important part of the claim has to do with just that: the real [runtime] semantics of the program. Hand optimization happens before runtime, obviously, whereas the HLL->assembly conversion can happen once the program is running and more info is known about the actual sets of data being operated on, the frequence of function calls, i.e. where the need for optimization actually exists. The optimization could even happen multiple times to adapt over time, or to allow multiple optimizations for different classes of data so that the code that actually executes is highly specialized. So, yeah, knowledge of the runtime behavior can allow a hand-optimized version to run faster than a static, automatically-generated version, but knowledge of the runtime behavior could also allow a dynamic code generator to even beat the hand-optimized version. -Dave From samrobertsmith at gmail.com Thu Nov 10 16:44:25 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Thu, 10 Nov 2005 13:44:25 -0800 Subject: [Tutor] triangulation In-Reply-To: <43737D96.4050802@tardis.ed.ac.uk> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13A0@chbnt01.alpha.wd.govt.nz> <00e701c5e582$46aa6b10$0a01a8c0@xp> <43737D96.4050802@tardis.ed.ac.uk> Message-ID: <1d987df30511101344r13bee250sb63be6c3e48b7559@mail.gmail.com> On 11/10/05, Alex Hunsley wrote: > Alan Gauld wrote: > > >>As in Pythagoras? > >> > >> > > > > > > > >>Or as in triangulation on a 2D surface, navigation etc.? > >> > >> > > > > > > > >>Or, do you mean radio triangulation by directional signal propagation > >> > >> > > > > > > > >>Or, do you mean drawing a triangle in Tkinter? > >> > >> > > > >Or even triangulation of currency from EU currency to EU currency > >via the euro? > > > >See: > >http://www.sysmod.com/eurofaq.htm#Triangulation > > > >Alan G. > > > > > This Shi Mu character is a little frustrating. They won't even respond > to peoples polite responses for clarification.... > Hit'n'run help requests. > > > the Internet is down for one day and so wonderful to have so many responses. i have checked all the links you guys mentioned. what i want is delaunay triangulation and the available ones online are written in C, Java and FORTRAN. I want to see some in Python because it is hard for me to figure out using python to do Fortune's sweeping line algorithm. Is python is not good in doing that kind of computation or some other reason? Thanks a lot for all of your responses!!! From samuel.yin at 163.com Thu Nov 10 21:16:02 2005 From: samuel.yin at 163.com (Samuel Yin) Date: Fri, 11 Nov 2005 10:16:02 +0800 Subject: Change directory not successfully done Message-ID: <4373FEE2.409@163.com> Hi, guys, This should be a simple problem, but I just can not resolve it. I just want to use a python script to change my working directory. see my following code: # mycd.py 1) destdir = "xxxxxxxx" 2) command = "cd "+ destdir 3) os.system(command) 4) os.chdir(destdir) But neither 3) nor 4) is used, I just can not change the directory after execute mycd.py. This remind me of bash script. If you change directory in your bash script file, it will only impact the sub process of that script, except that you invoke that bash script by ./script_file_name. But what should I do in the case of python script? Thanks and Regards Samuel Yin From could.net at gmail.com Tue Nov 1 09:48:49 2005 From: could.net at gmail.com (could ildg) Date: Tue, 1 Nov 2005 22:48:49 +0800 Subject: hello, I want to change n bytes of a binary file Message-ID: <311b5ce10511010648y33063589se0dbd5281b29af4e@mail.gmail.com> I want to encrypt a very large birany file, but if to change the whole file, it will take very long time, so I just want to change n(n is an int) bytes of the file. but when I turned to the file I/O of python, I found that file object can only read and write strings, so how can I do the binary stuff? I want a encrypt function like below: def encrypt(filename,n): f=open(filename,"rb") a=f.read(n) //encrypt the n byte bit by bit and then write back to the beginning of the file //assume I only want every bit change from 0->1 and 1->0, how to do it than? Thank you so much! -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Nov 24 03:54:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Nov 2005 09:54:36 +0100 Subject: Why is dictionary.keys() a list and not a set? References: <1132815683.602078.216760@g14g2000cwa.googlegroups.com> <1132820426.374743.51410@g49g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > I know that is a single list of tuples, I mean that can be used as > well. > > for k, _ in d.items(): print k > for _, v in d.items(): print v > for k in d.keys(): print k > for v in d.values(): print v > > Would there be a noticeable performance difference ? Sloppy use of print statements is a great way to produce misleading benchmarks [1], since the time it takes to print lots of stuff tends to overshadow the actual algorithm (for bonus points, print to a terminal window, and use "time" to measure performance, so you get startup times as well). If you don't necessarily want to print all the stuff, my original assertion still holds: "creating a list full of tuples just to pull them apart and throw them all away isn't exactly the most efficient way to do things" Consider a dictionary with one million items. The following operations k = d.keys() v = d.values() creates two list objects, while i = d.items() creates just over one million objects. In your "equivalent" example, you're calling d.items() twice to produce two million objects, none of which you really care about. 1) careful use of timeit and generator expressions is another one: http://online.effbot.org/2005_01_01_archive.htm#20050125 (code) http://online.effbot.org/2005_01_01_archive.htm#20050127 (explanation) From roy at panix.com Sat Nov 19 10:34:52 2005 From: roy at panix.com (Roy Smith) Date: Sat, 19 Nov 2005 10:34:52 -0500 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Alternatively the underscore syntax may be used to separate the number > from its base: > 22875 == 22875_10 == 595b_16 == 123456_7 > But probably this is less commonly useful (and not much explicit). We already have a perfectly good syntax for entering octal and hex integers, because those are commonly used in many applications. There are, on occasion, need for other bases, but they are so rare, specialized, and non-standard (RFC-1924, for example, uses an interesting flavor of base-85) that having syntax built into the language to support them would be completely unjustified. From cjw at sympatico.ca Mon Nov 21 12:31:06 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 21 Nov 2005 12:31:06 -0500 Subject: best cumulative sum In-Reply-To: <_zlgf.13457$a62.3638@trnddc07> References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> Message-ID: David Isaac wrote: > wrote in message > news:1132553397.042444.147660 at g44g2000cwa.googlegroups.com... > >>He seems to want scanl > > > Yes. But it's not in Python, right? > (I know about Keller's version.) > > Robert Kern wrote: > >>Define better. More accurate? Less code? > > > Good point. > As Bonono (?) suggested: I'd most like a solution that > relies on a built-in to give me both of those. > (Pretty is good too.) Like SciPy's cumsum. > > Thanks, > Alan Isaac > > Doesn't numarray handle this? Colin W. From fredrik at pythonware.com Thu Nov 17 06:49:55 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Nov 2005 12:49:55 +0100 Subject: strange file.write() behavior on windows: $ConvertToNonresident, $ReplaceAttribute2 References: <1132184249.849494.229190@f14g2000cwb.googlegroups.com> Message-ID: "welch" wrote: > while taking some rough disk performance measures on windows machines, > and snooping with FileMon, i've noticed some odd behavior > sometimes, depending on the phase of the moon, instead of > $ReplaceAttribute2 the write goes to $ConvertToNonresident. within a > single run of writeTest the write always goes to the same one, > whichever one that is. these runs are always slower (sometimes greatly) > than writing the same with 64K blocks, even though many fewer > file.write()'s are being issued because of the larger block size. > > finally, where you'd expect an even 10 of the WRITE > C:\$ReplaceAttribute2 lines per WRITE C:\writeTest.out lines in the > example above, instead FileMon reports 8 lines for the first, 6 for the > second, 8 for the third, 6 for the fourth, etc... i've no idea if this > means FileMon is missing messages, but this pattern is absolutely > consistent across every run i've made, on both xp and win2k3 server > machines. > > a look at the python fileobject.c source shed no light for me, anyone > know what could be going on? the "equivalent" c version of writeTest > using fwrite() shows a succession of 1K blocks writing to the named > file (even when fwrite is given 64K blocks), and no mysterious > $ReplaceAttribute2 lines you're seeing activities by the Windows caching system (c:\$ stuff is various NTFS data streams). unless you're writing low-level drivers, you don't really have to care about what it does, and when it does what... From vinjvinj at gmail.com Mon Nov 7 15:54:40 2005 From: vinjvinj at gmail.com (vinjvinj) Date: 7 Nov 2005 12:54:40 -0800 Subject: Using python for writing models: How to run models in restricted python mode? Message-ID: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> I have an application which allows multiple users to write models. These models get distributed on a grid of compute engines. users submit their models through a web interface. I want to 1. restrict the user from doing any file io, exec, import, eval, etc. I was thinking of writing a plugin for pylint to do all the checks? Is this is a good way given that there is no restricted python. What are the things I should serach for in python code 2. restrict the amount of memory a module uses as well. For instance how can I restrict a user from doing a = range(10000000000) or similar tasks so that my whole compute farm does not come down. Thanks for your help From tim.leeuwvander at nl.unisys.com Tue Nov 29 04:40:12 2005 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 29 Nov 2005 01:40:12 -0800 Subject: XMLSchema Parsing In-Reply-To: References: Message-ID: <1133257212.024904.268010@g43g2000cwa.googlegroups.com> Hi, Depends entirely on what you want. I've written some XSD tools in Python that do exactly what I want -- but don't offer support for any XSD features that I didn't happen to need. Module I wrote supports include/import and redefine; parses sequences, complexTypes and simpleTypes, but not much more. I also have some tool that generates basic XSD files from sample input xmls, and a tool that generates sample xml files from an XSD. I'm not aware of any Python XSD tooling but did you search google on it? How much of XSD do you need to be supported? And what do you need to do with it? cheers, --Tim From OurLab at gmail.com Sun Nov 20 23:34:39 2005 From: OurLab at gmail.com (Alex) Date: 20 Nov 2005 20:34:39 -0800 Subject: setattr for secondary attribute Message-ID: <1132547679.658546.40350@o13g2000cwo.googlegroups.com> I apologize for asking maybe a very trivial question. I have a new class object A with slots. One of the slots is, for example, object spam. Object spam, in turn, also has slots and one of them is attribute eggs. I need to assign a new value to eggs. In other words, I need to perform the following: A.spam.eggs=newValue The problem is that I have only a string s='spam.eggs' with which to work, so I cannot write an expression written above. I tried to use setattr: setattr(A, s, newValue) but this does not work. It says that object A does not have attribute spam.eggs How would you do it? TIA. From gsakkis at rutgers.edu Wed Nov 9 22:58:16 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Nov 2005 19:58:16 -0800 Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> Message-ID: <1131595096.310029.98740@g43g2000cwa.googlegroups.com> "bonono at gmail.com" wrote: > Alex Martelli wrote: > > This becomes a valid list comprehension by writing 'if' instead of > > 'when'. > > valid, yes. efficient, I am not sure. > > [ x for x in xrange(10000000) if p(x) ] > > means I need to go through the whole range even if p = lambda x: x < 2 Itertools is your friend in this case: >>> from itertools import takewhile >>> list(takewhile(p, xrange(10000000))) [0, 1] George From gdamjan at gmail.com Tue Nov 8 13:21:54 2005 From: gdamjan at gmail.com (Damjan) Date: Tue, 08 Nov 2005 19:21:54 +0100 Subject: how to write a blog system with Python References: <1130986622.788569.225120@o13g2000cwo.googlegroups.com> Message-ID: > I am a fresh here , and I have no idea of it. > Do you have any comments? Take a look at aether, a single CGI script and it's easy to understand. http://www.logarithmic.net/pfh/aether -- damjan From fredrik at pythonware.com Fri Nov 25 06:16:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Nov 2005 12:16:31 +0100 Subject: Python as Guido Intended References: <1132913689.347032.252040@f14g2000cwb.googlegroups.com> Message-ID: Ben Sizer wrote: > The problem you get, is that the only people who are ever likely to > need to ask questions, are those who don't fully understand Python, by > definition. really? I'd say that most people that ask questions on comp.lang.python do understand Python pretty well, and just needs help with some esoteric detail, or some part of a library that they haven't used before. And the most common response is "oh, that's cool. thanks". The "I'm personally offended by the very design of the feature you just pointed me to" kind of person is not very common; most people don't have that kind of ego pro- blem, and even those who do usually don't have time for that kind of crap. Fact is, most people see Python as a tool, use it where it fits, and focus on the problems they need the tool for. And yes, most Python users never gets anywhere near comp.lang.python. From aleax at mail.comcast.net Wed Nov 30 22:20:32 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 30 Nov 2005 19:20:32 -0800 Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> <1133191986.034689.59090@g14g2000cwa.googlegroups.com> <1h6q906.wbfwmtxr0zjN%aleax@mail.comcast.net> <1133196211.468791.220480@g47g2000cwa.googlegroups.com> <1h6r2u7.tfin37njer33N%aleax@mail.comcast.net> <1133397270.119967.56990@g14g2000cwa.googlegroups.com> Message-ID: <1h6utbe.1cj94nu1ruy07jN%aleax@mail.comcast.net> Martin Miller wrote: > You're not missing anything -- it's my own [mis-]understanding that > descriptors would only work with new-style classes, not the old-style > ones used in the OP's example. > > However your example certainly proves that is not the case, even if you > go one step further and call the bound method/function: > >>> o.z() > <__main__.old instance at 0x009D5F30> > > So I stand corrected -- thank you. You're welcome. Your previous misunderstanding may be due to the fact that (differently from __get__) the special method __set__ doesn't work when the descriptor is held in an old-style class... to be more precise, it's not even given a chance, since assigning to an instance attribute (where the instance's old-style) just blithely sets the value in the instance's __dict__, without even checking for the existence of a descriptor by that name in the class. Alex From uid09012_ti at collinsrealtime.com Sun Nov 6 15:46:24 2005 From: uid09012_ti at collinsrealtime.com (Francach) Date: 6 Nov 2005 12:46:24 -0800 Subject: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 99: ordinal not in range(128) Message-ID: <1131309984.060539.70390@g44g2000cwa.googlegroups.com> Hi, I don't know what I'm doing wrong here. I''m using Python 2.4 and py2exe. I get he following error: Traceback (most recent call last): File "notegui.pyc", line 34, in OnClose File "brain.pyc", line 61, in setNote File "points.pyc", line 151, in setNote File "point.pyc", line 100, in writeNote UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 99: ordinal not in range(128) The piece of code involved is: noteFileObj = open(noteFile, "wb") noteFileObj.write(note) noteFileObj.close() I would've thought that the 'b' option meant I can write any binary code I like to the file, but that's not so? Thanks for any tips, Martin. From jelleferinga at gmail.com Sat Nov 12 08:59:29 2005 From: jelleferinga at gmail.com (jelle) Date: 12 Nov 2005 05:59:29 -0800 Subject: SciPy python 2.4 wintel binaries Message-ID: <1131803968.993069.29660@f14g2000cwb.googlegroups.com> Hi, I dearly miss having the power of SciPy on my python 2.4 installation. The topic of SciPy python 2.4 wintel binaries has been discussed before on this list, but I haven't been able to find a compiled binary. I'm one of the 'compiled-challenged'; anything more complex than 'python setup.py build' leaves me at the grace of the non-challenged... SciPy is a complex software engineering project, so I'm hangin on the mercy of others here... Is anyone on this list aware of such a binary? Thanks, -jelle From bokr at oz.net Thu Nov 10 17:14:32 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 10 Nov 2005 22:14:32 GMT Subject: How to set program name in Python? ($0 in Perl) References: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> Message-ID: <4373c4e4.152866300@news.oz.net> On Thu, 10 Nov 2005 08:06:27 +0100, "Fredrik Lundh" wrote: >Steve Holden wrote: > >> > Is there a way to set the program name in Python, similar to $0 in >> > Perl? >> > >> >>From `man perlvar`: >> > >> > $0 Contains the name of the program being executed. On some oper- >> > ating systems assigning to "$0" modifies the argument >> > area that >> > the ps program sees. This is more useful as a way of >> > indicat- >> > ing the current program state than it is for hiding the >> > program >> > you're running. (Mnemonic: same as sh and ksh.) > >> import sys >> print sys.argv[0] > >that *gets* the name, but assigning to sys.argv[0] doesn't *set* it (afaik). > >setting the name involves overwriting the C level argv array, several large >buckets of worms, and huge portability issues, and is thus better left to non- >standard extensions. > OTOH, if the intent is just to set a value for subsequent getting by way of sys.argv[0], isn't sys.argv an ordinary list? >>> import sys >>> sys.argv[0] '' >>> sys.argv[0] = '' >>> sys.argv[0] '' >>> type(sys.argv) Regards, Bengt Richter From bonono at gmail.com Fri Nov 18 18:41:23 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 18 Nov 2005 15:41:23 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> Message-ID: <1132357283.132264.280990@g47g2000cwa.googlegroups.com> The cleanest(IMO) is this : a = (predicate and [if_true_expr] or [if_false_expr])[0] This would give you the necessary "short circuit" behaviour no matter what. a = predicate and if_true_expr or if_false_expr works most of the time but should if_true_expr turns out to be 0 or something like that(python False equvialent), the if_false_expr will still be executed, that becomes a logic error. an example : a = int_str is None and None or int(int_str) a = [if_false_expr, if_true_expr][predicate] This doesn't have the "short circuit" feature and the order is reversed(harder to read for people familiar with ternary operator). Cannot be used in some case. like this : a = [0, int(int_str)][int_str is not None] here int(int_str) may cause exception if None is a valid value. The lambda form suggested by others is another variant of the first one above where you get the short circuit feature but too complex to read. I don't understand why people are so aganst ternary operator. It is a must for list comprehension/generator expression(and I believe the reason it has finally been approved), if/else block or try/except just don't work in these situations. Daniel Crespo wrote: > Hi! > > I would like to know how can I do the PHP ternary operator/statement > (... ? ... : ...) in Python... > > I want to something like: > > a = {'Huge': (quantity>90) ? True : False} > > Any suggestions? > > Thanks > > Daniel From eric.nieuwland at xs4all.nl Thu Nov 3 05:09:55 2005 From: eric.nieuwland at xs4all.nl (Eric Nieuwland) Date: Thu, 3 Nov 2005 11:09:55 +0100 Subject: Class Variable Access and Assignment In-Reply-To: <1131011020.845873.282180@g14g2000cwa.googlegroups.com> References: <1131011020.845873.282180@g14g2000cwa.googlegroups.com> Message-ID: <90abb07e9bc56f89b8410b0183e98fb1@xs4all.nl> Graham wrote: > > > class _class: > var = 0 > #rest of the class > > instance_b = _class() > > _class.var=5 > > print instance_b.var # -> 5 > print _class.var # -> 5 > > > [...] > > > instance_b.var = 1000 # -> _class.var = 5 > _class.var = 9999 # -> _class.var = 9999 > > > > An obvious error occurs. Nope. 'var' is NOT a class variable! It is a pre-filled instance variable. You need some explicit programming to get class variables. --eric From martin at v.loewis.de Wed Nov 23 19:21:36 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 24 Nov 2005 01:21:36 +0100 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <438505AA.8000105@redlinepy.com> References: <3uk6siF11mqgvU1@individual.net> <4384ec18$0$25871$9b622d9e@news.freenet.de> <438505AA.8000105@redlinepy.com> Message-ID: <43850790$0$4066$9b622d9e@news.freenet.de> Paul Watson wrote: > Can we #undef _ALL_SOURCE for _codecs_cn.c compilation? Where does _ALL_SOURCE come from? Why is it defined? What is its effect on hz? Regards, Martin From onurb at xiludom.gro Tue Nov 8 09:45:18 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 08 Nov 2005 15:45:18 +0100 Subject: Diff. between Class types and classic classes In-Reply-To: <1131454786.272355.314740@z14g2000cwz.googlegroups.com> References: <1131454786.272355.314740@z14g2000cwz.googlegroups.com> Message-ID: <4370ba00$0$7529$626a14ce@news.free.fr> venk wrote: > Hi, > can some one properly explain the differences between class types and > classic classes? ... Still face problems in identifying what is what. I'm not sure I understand your question. Are you talking about the diff between old-style and new-style classes, or the diff between classes and metaclasses ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bdesth.quelquechose at free.quelquepart.fr Sat Nov 19 05:43:26 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 19 Nov 2005 11:43:26 +0100 Subject: examining python objects In-Reply-To: <1132339687.048155.252160@g47g2000cwa.googlegroups.com> References: <1132339687.048155.252160@g47g2000cwa.googlegroups.com> Message-ID: <437ef75a$0$32754$626a14ce@news.free.fr> rurpy at yahoo.com a ?crit : > Is there a function/class/module/whatever I can use to > look at objects? I want something that will print the object's > value (if any) in pretty-printed form, and list all it's attributes > and their values. And do all that recursively. > I want to be able to find out everything about an object that > Python can introspectively find out. Then check the inspect module From grante at visi.com Fri Nov 11 10:27:04 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 11 Nov 2005 15:27:04 -0000 Subject: Is there a built-in method for transforming (1, None, "Hello!") to 1, None, "Hello!"? References: <1131722506.604482.323720@f14g2000cwb.googlegroups.com> Message-ID: <11n9e28clbe0rb7@corp.supernews.com> On 2005-11-11, Daniel Crespo wrote: > Is there a built-in method for transforming (1,None,"Hello!") to > 1,None,"Hello!"? What transformation? The two are identical: >>> x = (1,None,"Hello!") >>> y = 1,None,"Hello!" >>> x == y True -- Grant Edwards grante Yow! Nice decor! at visi.com From edvard at majakari.net Wed Nov 16 10:14:27 2005 From: edvard at majakari.net (Edvard Majakari) Date: Wed, 16 Nov 2005 17:14:27 +0200 Subject: Creating (rather) generic plugin framework? Message-ID: <84Ief.9127$fR3.929@reader1.news.jippii.net> Hi, My idea is to create a system working as follows: each module knows path to plugin directory, and that directory contains modules which may add hooks to some points in the code. Inspired by http://www.python.org/pycon/2005/papers/7/pyconHooking.html I would create a class like this: class Printer: def printit(self, msg): stuff = self.beforePrintHook(msg) if stuff: msg = stuff print msg self.afterPrintHook(msg) def beforePrintHook(self, msg): pass def afterPrintHook(self, msg): pass Now, in the spirit of py.test, I'd like API to be practically no API at all :) moreover, deploying a plugin must consist simply of adding appropriate file to plugins directory, nothing more, and removing it would uninstall it. The plugin should be able to somehow result in all future invocations to Printer.printit() call hooks specified in the plugin. Now, the plugin module for class above /might/ be along the following lines (I'm thinking of stuff here, so I don't know yet what would be the most appropriate way): ### a very simple plugin which uppercases all data fed to it. extensions = {'Printer': 'PrinterHook'} class PrinterHook: def beforePrintHook(self, msg): return msg.upper() def afterPrintHook(self, msg): print "Called afterPrintHook with msg %s" % msg Now, I have a very rude (I think) implementation which has two methods, first the one that loads plugin modules: def find_plugins(): mods = [mod for mod in os.listdir(PLUGIN_DIR) if mod.endswith('.py')] # for each module in plugin dir, import the module and setup hooks. Hooks # must have equal method names in plugin module as in the original class. for mod in mods: name = os.path.splitext(mod)[0] fobj, fpath, desc = imp.find_module(os.path.join(PLUGIN_DIR, name)) module = imp.load_module(name, fobj, fpath, desc) set_hooks(module) ...then the other that is responsible for setting up hooks def set_hooks(mod): # mod.extensions has "base" class names as keys, (hook, priority) as # values for k, hook in mod.extensions.items(): # get class object hook_cls = mod.__dict__[hook] try: base = globals()[k] except KeyError: print "No such class to insert hooks to:", k else: for item in base.__dict__: if item.endswith('Hook'): # Override original (no-op) hook method # uhh.. kludgety kludge base.__dict__[item] = hook_cls.__dict__[item] now, my plugindemo.py just does as follows: find_plugins() p = Printer() p.printit('Hello, world!') which prints $ python2.4 plugindemo.py HELLO, WORLD! Called afterPrintHook with msg HELLO, WORLD! But hey, this has many downsides. First off, mechanism doesn't support arbitrary namespaces. Here, class identifier in the plugin must be as it is seen from the module which calls the plugin (not a problem for me, but could be more elegant; probably a mapping between logical class identifiers and actual class names, hmm?). Second, if one wants to use many hooks (with priority for conflicts), it is not possible now; set_hooks always overrides potentially existing hooks. And probably many other problems that are not obvious to me, but for the simple purpose I have in mind, it seems to work. This is the first plugin system in Python I'm writing, so I can be a way off the correct path.. From phleum_nospam at chello.se Mon Nov 28 16:04:45 2005 From: phleum_nospam at chello.se (Carl) Date: Mon, 28 Nov 2005 22:04:45 +0100 Subject: Long integer arrays in Python; how? /Carl Message-ID: I have the following problem import Numeric dim = 1 bits = 32 v = Numeric.zeros((dim, bits), 'l') for j in range(bits): v[0][j] = 1L << bits - j - 1 The problem is the last assignment, which is not valid, since the integer is on the right hand side is to large to be assigned to an array element. Is there a way around this problem in Python? Yours /Carl From sumit.nanda at gmail.com Tue Nov 15 13:01:32 2005 From: sumit.nanda at gmail.com (Sumit) Date: 15 Nov 2005 10:01:32 -0800 Subject: Needed class whose instances are many test cases In-Reply-To: References: <1131706265.113961.63370@f14g2000cwb.googlegroups.com> Message-ID: <1132077692.262402.256270@g44g2000cwa.googlegroups.com> Thanks for comments .setup() is going the Run Before every testcase Run. But i need to create resource for set of testcases , it is one time only . I can not create at every instant before testcases Run . thats why Unittest.testsuit is goingto help me out . There __init__() can be Run One time and the resource can be create one time for set of tests. From y.glodt at sitasoftware.lu Thu Nov 10 07:23:33 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Thu, 10 Nov 2005 13:23:33 +0100 Subject: iterate over class variables In-Reply-To: <43733767.1040205@sitasoftware.lu> References: <43733767.1040205@sitasoftware.lu> Message-ID: <43733BC5.4050607@sitasoftware.lu> Yves Glodt wrote: > Hello list, > > I need to iterate over a class and get all her variable names and > values, e.g. considering this example: > > > class testclass: > var1 = 'ab' > var2 = 'cd' > var3 = 'ef' > > test = testclass() > > > > Then I wanna do sonmething like this: > > for name,value in test: > print name > print value > > fails with of course with: > "TypeError: iteration over non-sequence" > > > How can I do that? sorry for selfreplying, but I found a solution: for key in dir(test): if '__' not in key: value = getattr(test,key) print key, value Does anything speak about this? Is there a better-performing way to do this? > regards, > Yves From xaver.hinterhuber at web.de Fri Nov 18 02:26:52 2005 From: xaver.hinterhuber at web.de (Xaver Hinterhuber) Date: Fri, 18 Nov 2005 08:26:52 +0100 Subject: Python under Citrix Metaframe Message-ID: Hello, I wanted to use python under Citrix Metaframe. After installation of the ActivePython 2.4.1 msi-File, printing under Citrix Metaframe no longer worked. Do you use python under Citrix Metaframe? What problems did you encounter? Greets Xaver Hinterhuber From davidb at mcs.st-and.ac.uk Thu Nov 10 06:43:17 2005 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 10 Nov 2005 03:43:17 -0800 Subject: Looking Python script to compare two files References: Message-ID: <1131622997.718912.19040@g43g2000cwa.googlegroups.com> Tim Golden wrote: > + PDF: David Boddie's pdftools looks like about the only possibility: > (ducks as a thousand people jump on him and point out the alternatives) I might as well do that! Here are a couple of alternatives: http://www.sourceforge.net/projects/pdfplayground http://www.adaptive-enterprises.com.au/~d/software/pdffile/ Both of these are arguably more "Pythonic" than my solution, and the first is also able to write out modified files. Cameron Laird also maintains a page about PDF conversion tools: http://phaseit.net/claird/comp.text.pdf/PDF_converters.html > http://www.boddie.org.uk/david/Projects/Python/pdftools/ > > Something like this might do the business. I'm afraid I've > no idea how to determine where the line-breaks are. This > was the first time I'd used pdftools, and the fact that > I could do this much is a credit to its usability! Thanks for the compliment! The read_text method in the PDFContents class also lets you extract text from a given page in a document, but you have to remember that text in PDF files isn't always composed as a series of lines or paragraphs, and often doesn't even contain whitespace characters. David From steve at REMOVETHIScyber.com.au Sat Nov 26 03:39:20 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 26 Nov 2005 19:39:20 +1100 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> Message-ID: On Fri, 25 Nov 2005 23:20:05 -0500, Mike Meyer wrote: > Steven D'Aprano writes: >> "Hmmm, the class designer didn't want me adding attributes to instances... >> maybe he had a good reason for that..." > > When it was suggested that a facility for doing this be added to the > language, I asked for a use case for it. Nobodies come up with a > reason for placing such restriction on the client yet. Oh, I think it is terribly unfair to call them nobodies, even if you don't like their use-cases *grin* > If you've got a use case, I'd be interested in hearing it. frozenset perhaps? If it were needed once, it could be needed again. The obvious case would be for a class where distinct instances that compare equal but not identical map to the same value in a dict. In any case, I'm not the one claiming that I need custom immutable classes. I'm just suggesting that there is nothing non-Pythonic about them. If Ben thinks he needs them, I'm sure he has put *far* more thought into it than I have. I know Ben in RL, and he is not someone to make snap judgements about turning Python into Some Other Language Just Because. -- Steven. From aahz at pythoncraft.com Mon Nov 28 18:03:10 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Nov 2005 15:03:10 -0800 Subject: General question about Python design goals References: Message-ID: In article , Christoph Zwerschke wrote: >Aahz wrote: >>Christoph wrote: >>>Aahz wrote: >>>>Christoph wrote: >>>>> >>>>>For instance, I just wanted to use the index() method on a tuple which >>>>>does not work. ... >>>> >>>>Because Guido believes that tuples should be primarily used as >>>>lightweight replacements for C structs. Therefore they have minimal >>>>functionality. >>> >>>But the problem is that the tutorials and manuals give the impression >>>that the difference between lists and tuples is only mutablity versus >>>immutability. They don't talk about such considerations and honestly >>>speaking even now I know that it does seem more plausible for me. >> >> Then feel free to submit patches for the docs. > >Why should I patch the docs to add things that don't seem plausible for >me? I'd rather change the behavior to be more consistent instead >tweaking the docs to somehow justify the inconsistent behavior. The problem is that Guido really is the BDFL. Unless you change his mind (and he has been historically firm about the place of tuples), your option for improving things is to improve the docs, if you care. >> PS: If you want further responses from me, please follow standard Usenet >> quoting conventions (like those above). > >I am tempted to answer, "A Foolish Consistency is the Hobgoblin of >Little Minds" ;-) > >No honestly, it was not in bad faith. I'm just not a regular usenet user >and believed one attribution line per post should suffice. But reading >the conventions I agree that they make sense. Thanks! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair From bkhl at stp.lingfil.uu.se Fri Nov 4 17:59:55 2005 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Fri, 04 Nov 2005 23:59:55 +0100 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> <1131023021.643251.113330@f14g2000cwb.googlegroups.com> <1h5fwpi.1wjmgm417fbm8dN%aleax@mail.comcast.net> <1131033712.535402.193520@z14g2000cwz.googlegroups.com> <1h5grc5.1f520xizhqvucN%aleax@mail.comcast.net> <1131128383.049466.179370@f14g2000cwb.googlegroups.com> <87pspg6yob.fsf@jupiter.g2ctech> Message-ID: <87oe502f4k.fsf@lucien.dreaming> Jorge Godoy writes: > "bonono at gmail.com" writes: > >> oops. I developed this habit because I found I like to read it this >> way. As I usually would read just the first few lines to see if I >> want to read on. top post serve me well for this purpose. And I >> assume other may also find my stuff not worth reading and skip quick >> so why force them to scroll all the way down ? I would only do >> in-line response type when there is a need for specific response in >> context. > > I'm more of the type that wouldn't read on if I have no context to > what I'm reading... Specially if there's a mix of top posts with > bottom posts... Anyway, if you keep more than a pageful of the previous message, you're probably not cutting it hard enough. Just keep what's needed to keep the context. -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From nekiv at start.no Mon Nov 7 03:40:09 2005 From: nekiv at start.no (Olav) Date: 7 Nov 2005 00:40:09 -0800 Subject: Data Type Problem in Python / COM Message-ID: <1131352809.105825.192590@g49g2000cwa.googlegroups.com> I'm trying to use Python / COM to do some drawing automation. Here is a simple code example: This code uses a object made by the Opendwg-org. Autocad has a similar object with the same methods - and the same result. ----------- import win32com.client odaHost=win32com.client.dynamic.Dispatch("DWGdirectX.OdaHostApp") odaApp = odaHost.Application point = (0,0,0) #x,y,z filename = r'c:\temp\test.dwg' odaDoc = odaApp.Documents.Add(filename) odaDoc.ModelSpace.AddPoint(point) -------------- Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "F:\dom-users\Autoproject\makedwg.py", line 13, in ? odaDoc.ModelSpace.AddPoint(a) File "C:\Python24\Lib\site-packages\win32com\gen_py\2D1051CA-C44F-4206-A86D-45E24A10ABC7x0x2x0.py", line 9516, in AddPoint ret = self._oleobj_.InvokeTypes(1562, LCID, 1, (9, 0), ((12, 1),),Point com_error: (-2147352567, 'Exception occurred.', (0, 'DWGdirectX', 'The parameter is incorrect.\r\n', None, 0, -2147024809), None) ------------------- I have tried both early and late binding but with the same result. I have seen the same code in VB, and the code looks like this: This works. ------------ Sub Example_AddPoint() ' This example creates a point in model space. Dim pointObj As AcadPoint Dim location(0 To 2) As Double ' Define the location of the point location(0) = 5#: location(1) = 5#: location(2) = 0# ' Create the point Set pointObj = ThisDrawing.ModelSpace.AddPoint(location) ---------------- It seems to me that this error is related to the data-type conversation. Any help would be much appreciated Thanks Olav From david at jotax.com Thu Nov 17 17:37:36 2005 From: david at jotax.com (David Poundall) Date: 17 Nov 2005 14:37:36 -0800 Subject: Stretching a bitmap In-Reply-To: <1132266137.875055.82600@g14g2000cwa.googlegroups.com> References: <1132262655.753062.210080@g14g2000cwa.googlegroups.com> <1132266137.875055.82600@g14g2000cwa.googlegroups.com> Message-ID: <1132267056.029743.122440@o13g2000cwo.googlegroups.com> I need to be able to do this on the fly within a WX frame. I think I have found it though. There is a resize function in the image class in the _core code of wxPython. All I have to do now is learn how to access the bugger. Syntax anyone ?? From tim.golden at viacom-outdoor.co.uk Wed Nov 23 09:13:55 2005 From: tim.golden at viacom-outdoor.co.uk (Tim G) Date: 23 Nov 2005 06:13:55 -0800 Subject: Problems with threaded Hotkey application In-Reply-To: <1132754465.629098.11240@g49g2000cwa.googlegroups.com> References: <1132727579.268059.60120@g47g2000cwa.googlegroups.com> <1132754465.629098.11240@g49g2000cwa.googlegroups.com> Message-ID: <1132755235.667064.23600@g43g2000cwa.googlegroups.com> And just to confirm, it does in fact work. If you move the RegisterHotKey line to within the thread's run method, the thread's message loop picks up the hotkey press. From mwm at mired.org Thu Nov 24 18:12:52 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 18:12:52 -0500 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> <86oe49wyky.fsf@bhuda.mired.org> <43863e25$0$11061$e4fe514c@news.xs4all.nl> Message-ID: <867jaxwsgb.fsf@bhuda.mired.org> "Martin P. Hellwig" writes: > Mike Meyer wrote: > >> Well, they chose to make it available to others for reuse. But >> software "unavailable to those who can't afford it" is better than "no >> software at all" > That I do not agree with, I think it depends on which your side of the > fence you are. Actually, I think I underspecified the statement. "Better for who" is the question. No software is the same as software you can't afford. On the other hand, so long as the price is lower than the cost of recreating the software for someone, then it's better for society as a whole if it exists at all. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From onurb at xiludom.gro Fri Nov 4 05:07:42 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 04 Nov 2005 11:07:42 +0100 Subject: I Need Motivation Part 2 In-Reply-To: References: Message-ID: <436b32ef$0$21622$636a15ce@news.free.fr> blah at blah.blah wrote: > i m currently in a network (LAN). i started python because i heard > that it has great ability for networking programs and/or scripts, but > i m losing my motivation with python because there are sooo many > modules, that i cant just learn them all, Why would you learn them all ? Learn the one you need when you need them - jus don't forget to have a quick look at the existings modules before reinventing the square wheel (I wrote a Q&D CSV parser before realinzing there was a pretty good one in the stdlib... But what, my Q&D solution took me laess than one hour to write and did what it had to do, so...) > this deters from c or c++ in > which there are only a limited number of header files. In the stdlib, yes. Now there are thousands of librairies/frameworks each reimplenting all the basic datastructure and algorithm (strings, lists, hashtables, trees and the like), so you almost have to learn a new language each time you use a new library. > what loses my > interest is that if i cant learn these modules, Once again : you don't have to. > and there are lots and > lots of python modules, how can i ever be a good enough > programmer/scripter. Like everybody else: write programs. That's the only way to become a programmer. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From suma_37 at yahoo.com Wed Nov 9 02:00:09 2005 From: suma_37 at yahoo.com (sumi) Date: 8 Nov 2005 23:00:09 -0800 Subject: How do I create a dir using Python. Message-ID: <1131519609.875766.168440@g14g2000cwa.googlegroups.com> How do i create a dir using python......... From sjdevnull at yahoo.com Wed Nov 9 16:55:31 2005 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 9 Nov 2005 13:55:31 -0800 Subject: overloading *something In-Reply-To: References: <1h5obt1.ml6ib01swfdhbN%aleax@mail.comcast.net> <200511082138.12495.jstroud@mbi.ucla.edu> Message-ID: <1131573331.623816.129710@f14g2000cwb.googlegroups.com> Robert Kern wrote: > James Stroud wrote: > > > Does anyone else find the following annoying: > > > > py> from UserDict import UserDict > > py> aud = UserDict({"a":1, "b":2}) > > py> def doit(**kwargs): > > ... print kwargs > > UserDict only exists for backwards compatibility with old code that used > it before one could subclass from dict directly. Don't use it if you can > avoid it. UserDict only ever exposed the Python-side interface of dicts. > It couldn't expose the C-side interface, and it's the C-side interface > that **kwds is using. Which means that you can't subclass dict with, say, a lazy dictionary (that doesn't retrieve values until they're looked up) and use it with **kwargs. That bit me last year: http://groups.google.com/group/comp.lang.python/browse_frm/thread/95cfa91b732cd482/24b7e17bb395494e It would be useful in some situations to be able to do this (especially where getting the dictionary values is time-consuming and the function you're calling doesn't use all the values in the dictionary). For my particular case I had a fairly easy workaround. From bignose+hates-spam at benfinney.id.au Tue Nov 15 19:22:08 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Nov 2005 11:22:08 +1100 (EST) Subject: Reinvent no more forever Message-ID: Howdy all, On dirtSimple.org[0], PJE wrote: "Why is Python "blessed" with so much reinvention? Because it's often cheaper to rewrite than to reuse. Python code is easy to write, but hard to depend on. You pretty much have to: 1. limit yourself to platforms with a suitable packaging system, 2. bundle all your dependencies into your distribution, or 3. make your users do all the work themselves Ouch. No wonder rewriting looks easier." He then goes on to talk about his own solution: PyPI, setuptools, EasyInstall, and so on for better dependency control. He concludes: "But for right now, I plan to start by putting my dependencies where my mouth is. I will bundle no more forever, for I am tired of keeping them up-to-date with their upstream maintainers. I shall rend my monolithic packages into smaller projects, so that people can make use of cool parts of PEAK without having to install anything but the part they want. I will find out if this stuff really works. From where the setuptools now stand, I will bundle no more forever." Fine sentiments. What does this mean for PyPI though? How should those of us who also want to "reinvent no more forever" proceed? How do we deal with the rampant proliferation of a zillion implementations of some standard idiom in PyPI? The case that led me to this quandary is simple: I'm developing an application that could become simple, and I'm on the lookout for pieces that might be valuable outside this application. The first one to catch my eye is an Enum implementation. I now have a setuptools package of my Enum implementation. Should I submit it to PyPI? Advantages: - I can declare a dependency on that package for all my other packages that need such functionality, instead of bundling it every time. - Others can benefit from my code, instead of yet again including an Enum implementation (home-grown, or picked from a cookbook) by a simple dependency declaration. - The code hopefully gets improved and generalised and all the other benefits that accrue to software with many users. Disadvantages: - Proliferation. What's the protocol when[1] someone else puts an (incompatible, differently-specified) Enum implementation into PyPI? - Naming. How many ways can a package providing an Enum be named? I'd prefer mine to be named "Enum" or "enum", but why should mine be the one that claims that name? - It's just a pretty simple type, with unit tests. Does this really justify a PyPI package? This is common to any repository of code. But the "automatic dependency" problem means that all those packages, and many more outside that repository, need to know how those problems are resolved. Operating system distributors have policies (to greater or lesser degrees of strictness) to ensure this kind of quality control. My understanding of PyPI is that there's no such policy. I'd love to follow the mantra PJE espouses, but if it's good for one person it's probably good for countless others. How do we deal with that? What actions can we take in advance to prevent problems in future? [0] [1] Of course, someone already has. I prefer mine to theirs, hence the question. -- \ "I planted some bird seed. A bird came up. Now I don't know | `\ what to feed it." -- Steven Wright | _o__) | Ben Finney From aleax at mail.comcast.net Thu Nov 3 00:03:13 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 2 Nov 2005 21:03:13 -0800 Subject: Most efficient way of storing 1024*1024 bits References: <86d5ljcdtn.fsf@bhuda.mired.org> <1130978288_1367@spool6-east.superfeed.net> Message-ID: <1h5f3r4.10yxd3318n389nN%aleax@mail.comcast.net> Brandon K wrote [inverting his topposting!]: > > Six megabytes is pretty much nothing on a modern computer. > BTW, it'd be 6 megabits or 750kb ;) ...but Mike was proposing using one digit per bit, hence, 6 megabytes. That makes it easy to search for bitpatterns with re or string.find; if the bits were packed 8 to a byte, such searches would be very hard. Alex From aleax at mail.comcast.net Tue Nov 15 12:19:08 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 15 Nov 2005 09:19:08 -0800 Subject: Default method arguments References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a0a1b_1@newsgate.x-privat.org> <1132071889.676287.240030@o13g2000cwo.googlegroups.com> Message-ID: <1h628u2.j7q74x1i9uhlvN%aleax@mail.comcast.net> Gregory Petrosyan wrote: ... > def f(self, x = self.data) (*) ... > So I think (*) is the best variant, but it doesn't work :( It DOES work -- it just does not work the way you _expect_ it to work, but rather, it works the way it's _defined_ to work. Specifically: all the evaluation of default arguments' values happens as a part of the execution of the 'def' statement, and so, in particular, happens at the TIME 'def' is executing. A 'def' statement which is at the top level in a 'class' statement evaluates as part of the evaluation of 'class'. So, if, *while the 'class' statement is evaluating*, something known as 'self' exists, and has a 'data' attribute, this will give you the default value for argument 'x'. If the name 'self' is unknown, or refers to an object which has no 'data' attribute, then of course appropriate exceptions get raised (NameError or AttributeError) when Python is TRYING to execute that 'def' statement. Here's an example in which this works without exceptions: class outer(object): def __init__(self, data): self.data = data def make_inner(self): class inner(object): def f(self, x=self.data): print x return inner() Now, y = outer(23).make_inner() gives you an instance of an inner class, such that y.f() is the same thing as y.f(23). The 'self.data' in the 'def f', since it's the evaluation of a default value for an argument, evaluates at the time 'def' evaluates -- and, at that time, 'self' refers to the instance of class outer that's the only argument to method make_inner of class outer. While such "factories" (classes and functions making and returning other classes and functions) are rarely used by beginners, they are an extremely important idiom for advanced users of Python. But the point is that, by having extremely simple and universal rules, it takes no exoteric knowledge to understand what the above Python code will do -- default argument values evaluate as 'def' executes, therefore there is absolutely no ambiguity or difficulty to understand when this 'self.data' in particular evaluates. If Python tried to guess at when to evaluate default argument values, sometimes during the 'def', sometimes abstrusely storing "something" (technically a 'thunk') for potential future evaluation, understanding what's going on in any given situation would become extremely complicated. There are many languages which attempt to ``helpfully'' "do what the programmer meant in each single case" rather than follow simple, clear and universal rules about what happens when; as a consequence, programmers in such "helpful" languages spend substantial energy fighting their compilers to try and work around the compilers' attempted "helpfulness". Which is why I use Python instead. Simplicity is a GREAT virtue! If it's crucial to you to have some default argument value evaluated at time X, then, by Python's simple rules, you know that you must arrange for the 'def' statement itself to execute at time X. In this case, for example, if being able to have self.data as the default argument value is the crucial aspect of the program, you must ensure that the 'def' runs AFTER self.data has the value you desire. For example: class A(object): def __init__(self, n): self.data = n def f(self, x = self.data) print x self.f = f This way, of course, each instance a of class A will have a SEPARATE callable attribute a.f which is the function you desire; this is inevitable, since functions store their default argument values as part of their per-function data. Since you want a.f and b.f to have different default values for the argument (respectively a.data and b.data), therefore a.f and b.f just cannot be the SAME function object -- this is another way to look at your issue, in terms of what's stored where rather than of what evaluates when, but of course it leads to exactly the same conclusion. In practice, the solutions based on None or sentinels that everybody has been suggesting to you are undoubtedly preferable. However, you can, if you wish, get as fancy as you desire -- the next level of complication beyond the simple factory above is to turn f into a custom descriptor and play similar tricks in the __get__ method of f (after which, one can start considering custom metaclasses). Exactly because Python's rules and building blocks are simple, clean, and sharp, you're empowered to construct as much complication as you like on top of them. That doesn't mean you SHOULD prefer complication to simplicity, but it does mean that the decision is up to you. Alex From donn at u.washington.edu Wed Nov 2 19:41:43 2005 From: donn at u.washington.edu (Donn Cave) Date: Wed, 02 Nov 2005 16:41:43 -0800 Subject: Rich __repr__ References: Message-ID: In article , Ben Finney wrote: > Erik Max Francis wrote: > > Ben Finney wrote: > > > If I want to implement a __repr__ that's reasonably "nice" to the > > > programmer, what's the Right Way? Are there recipes I should look > > > at? > > > > I tend to use: > > > > def __repr__(self): > > if hasattr(self, '__str__'): > > return '<%s @ 0x%x (%s)>' % (self.__class__.__name__, > > id(self), str(self)) > > else: > > return '<%s @ 0x%x>' % (self.__class__.__name__, id(self)) > > Well that just begs the question: what's a good way (or a Right Way, > if that exists) to write a __str__ for a complex class? Well, in my opinion there pretty much isn't a good way. That is, for any randomly selected complex class, there probably is no worthwhile string value, hence no good __str__. This dives off into a certain amount of controversy over what repr and str are ideally supposed to do, but I think everyone would agree that if there's an "represent object for programmer" string value, it's the repr. So the str is presumably not for the programmer, but rather for the application, and I'm just saying that for application purposes, not all objects can usefully be reduced to a string value. Meanwhile, the code above also raises some questions where str is already provided. Run it on your subclass-of-str object and give the object a value of ') hi ('. This is why containers use repr to render their contents, not str. > It could be done just by hacking __repr__ with whatever things seem > appropriate, in some ad-hoc format. Or, as I'm hoping with this > thread, there may be common practices for outputting object state from > __repr__ that are concise yet easily standardised and/or recognised. I guess the best I could suggest is to stick with the format already used by instances (<__main__.C instance at 0x71eb8>) and augment it with class-specific information. def make_repr(self, special): return '<%s instance at 0x%x: %s>' % (self.__class__.__name__, id(self), special) def __repr__(self): return self.make_repr(repr(self.my_favorite_things)) This omits the module qualifier for the class name, but arguably that's a bit of a nuisance anyway. If there's a best, common practice way to do it, I wouldn't care to pose as an expert in such things, so you have to decide for yourself. Donn Cave, donn at u.washington.edu From tim.golden at viacom-outdoor.co.uk Thu Nov 24 10:10:14 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 24 Nov 2005 15:10:14 -0000 Subject: Locking a file under Windows Message-ID: <9A28C052FF32734DACB0A288A3533991044D235B@vogbs009.gb.vo.local> [Guy Lateur] > I'm working on an application that will be used by several users at the same > time. The user should be able to both read and write to some data file > stored on our file server. My question is: how can I prevent that one user > writes to the file while another user is reading it? Might be worth looking in the Python Cookbook area. I seem to remember several recipes to do this kind of thing cross-platform. eg, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 Also the pywin32 docs come with a flock-style example. Hope one of the two can help you. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From peter at engcorp.com Sat Nov 19 21:37:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Nov 2005 21:37:45 -0500 Subject: path module / class In-Reply-To: References: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> <8u6dnWEcZ6-6AuPeRVn-gg@powergate.ca> Message-ID: Neil Hodgson wrote: > To me, most uses of path.py are small incremental improvements over > os.path rather than being compelling. Do a number of small improvements > add up to be large enough to make this change? If the number of small improvements is large enough then, as with other such situations in the world, the overall change can definitely become qualitative. For me that's the case with using path.py. > There is a cost to the > change as there will be two libraries that have to be known to > understand code. Could you please clarify? Which two do you mean? > Does someone have an example application that moved to > path.py with a decrease in errors or noticeable decrease in complexity? We've mandated use of path.py internally for all projects because we've noticed (especially with non-expert Python programmers... i.e. junior and intermediate types, and senior types new to Python) a decrease in errors. Adoption of the appropriate methods in path.py (e.g. joinpath(), .name and .ext, .files()) is higher than the use of the equivalent methods or idioms with the standard libraries. How to do something, if not immediately obvious, is easier to discover because the docs and code are all in one place (for path.py). There's certainly a noticeable decrease in complexity. I could elaborate, but I honestly believe that this should be obvious to anyone who has seen almost any of the examples that have been posted, where a dozen lines of regular Python collapse to half that with path.py. Just removing imports of os, shutil, fnmatch, and glob in favour of a single one makes things "noticeably" (though admittedly not hugely) less complex. > Could all path manipulation code be switched or is coverage incomplete? As far as I can tell with our own usage, it is complete. We have not yet written code that required falling back to one of the existing modules, though I certainly wouldn't be shocked if someone had examples. > The duplication argument should be answered by looking at all the > relevant modules and finding a coherent set of features that work with > path.py without overlap so that the obsolete methods can be deprecated. > If adding path.py leads to a fuzzy overlapping situation where os.path > is occasionally useful then we are complicating the user's life rather > than simplifying it. I agree with that, but don't believe it is the case. And if one or two minor examples exist, fixing those cases would make more sense to me than abandoning the entire idea. For the record, though, if I haven't said it before, it doesn't really bother me that this isn't part of the standard library. I find it trivial to install in site-packages for all our workstations, and as we deliver code with py2exe it comes along for the ride. (And I feel no particular personal need to make things a lot simpler for newcomers to the language (other than those who work with me), though for people who do feel that need I definitely promote the idea of path.py becoming standard.) -Peter From steve at holdenweb.com Tue Nov 22 13:38:37 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 22 Nov 2005 18:38:37 +0000 Subject: Hot to split string literals that will across two or more lines ? In-Reply-To: References: Message-ID: Paul McGuire wrote: > "Ben Finney" wrote in message > news:dljic3$rpv$1 at rose.polar.local... > >>Xiao Jianfeng wrote: >> >>>I need to print a long sting, which is two long so it must expand >>>two lines. >> >>How is this string being constructed in the source? If it exists as a >>single long string, why must it be so long? >> >>Some techniques you may not be aware of: >> >> >>> chunks = ["abc", "def", "ghi"] >> >>> s = ''.join(chunks) >> >>> print s >> abcdefghi >> >> >>> s = "#" * 10 >> >>> print s >> ########## >> >>You can, of course, modify the above so that they join or multiply to >>create much longer strings. >> >>-- >> \ "Everything is futile." -- Marvin of Borg | >> `\ | >>_o__) | >>Ben Finney > > > Or for a large literal string: > > """ > lots of text hundreds of characters long > more text on another line but we really don't want any line breaks > in our final string > so we replace newlines in this multiline string > with an empty string thus > """.replace('\n','') > Of course there's also the alternative of escaping the newlines out in the literal. The replace result above is exactly """\ lots of text hundreds of characters long\ more text on another line but we really don't want any line breaks\ in our final string\ so we replace newlines in this multiline string\ with an empty string thus\ """ 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 steve.horsley at gmail.com Tue Nov 1 15:11:32 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Tue, 01 Nov 2005 20:11:32 +0000 Subject: Python's website does a great disservice to the language In-Reply-To: <1130869543.556662.81220@z14g2000cwz.googlegroups.com> References: <11mfb4el2kk5b00@corp.supernews.com> <1130869543.556662.81220@z14g2000cwz.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Grant Edwards wrote: >> May God save us from "professional" looking web sites. >> I like the Python web site. It's simple, easy to read, and easy to >> use. > > I strongly agree with you, the web is full of web sites that are nice > "looking" but have microscopic fixed fonts (against the very spirit of > Html), are full of useless flash, have lots of html structures nested > inside other ones (PHP sites are often like this, with dirty > sourcecode), are difficult/slow to render on differnt/old browsers > (best viewed with its webmaster browser only), are two times bigger > than necessary, etc. Python web site can be improved, but there are lot > of ways to make it worse. > > Bye, > bearophile > Agreed completely. Because the site works WITH HTML rather than AGAINST it, it renders very quickly - small data size and easy on the browser. It is a very functional reference site and "prettying it up" would probably greatly detract from its utility. I hope the new site design continues to be as easy on the eye, and as quick to use. Last time I wrote to a web site saying how clean and easy their web site was to use, they added a bucket-load of graphics shortly afterwards. Made it take twice as long to load, and added nothing to usability. A new logo might be in order though. Steve From fredrik at pythonware.com Sun Nov 6 08:14:56 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 6 Nov 2005 14:14:56 +0100 Subject: finding and accessing multiple documentation sources References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com><1131192936.228280.150530@g44g2000cwa.googlegroups.com><436d232b$0$6017$4fafbaef@reader4.news.tin.it><86u0eqsigi.fsf@bhuda.mired.org><7x4q6q7f6b.fsf@ruckus.brouhaha.com><86hdaqsfjo.fsf@bhuda.mired.org><7x3bmafrip.fsf@ruckus.brouhaha.com><86d5lescfd.fsf@bhuda.mired.org><7x8xw2ea4e.fsf@ruckus.brouhaha.com><436dc164.259807483@news.oz.net> <1131280114.971847.125580@g43g2000cwa.googlegroups.com> Message-ID: jmdeschamps at gmail.com wrote: > This actually brings us back to the jest of F. previous post, that > documentation is question of multiple source reference, and yes that > you have to work the field (Google search, newgroups, cookbooks, > source-code, et al) a little bit to get some information. while I don't care much about the "since I don't understand the reference manual, I demand that some experts should rewrite it for me, for free" line of reasoning, I still think it would be a good idea to make it easier to navigate the existing material. I wrote about this back in may: http://mail.python.org/pipermail/python-list/2005-May/280751.html http://mail.python.org/pipermail/python-list/2005-May/280755.html http://effbot.org/zone/idea-seealso.htm but, iirc, only got "wikis rulez" and "enough with that comp.sci crap" responses. > In time, one goes from newbie to casual-user, to regular-user and > createds his own setof useful references ... exactly. From eight02645999 at yahoo.com Tue Nov 1 22:03:32 2005 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 1 Nov 2005 19:03:32 -0800 Subject: python CGI,sybase and environ variables In-Reply-To: <1130896485.220506.103570@g43g2000cwa.googlegroups.com> References: <1130896485.220506.103570@g43g2000cwa.googlegroups.com> Message-ID: <1130900612.632031.144160@z14g2000cwz.googlegroups.com> i have solved the problem. thanks. From spam.csubich+spam+block at subich.nospam.com Sun Nov 6 12:23:02 2005 From: spam.csubich+spam+block at subich.nospam.com (Christopher Subich) Date: Sun, 06 Nov 2005 12:23:02 -0500 Subject: Class Variable Access and Assignment In-Reply-To: <436c2709.154756898@news.oz.net> References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <436c2709.154756898@news.oz.net> Message-ID: Bengt Richter wrote: > On Fri, 04 Nov 2005 10:28:52 -0500, Christopher Subich wrote: >>is very much within the language specification. Indeed, the language >>specification dictates that an instance variable b.a is created if one >>didn't exist before; this is true no matter if type(b.a) == int, or if >>b.a is some esoteric mutable object that just happens to define >>__iadd__(self,type(other) == int). > > But if it is an esoteric descriptor (or even a simple property, which is > a descriptor), the behaviour will depend on the descriptor, and an instance > variable can be created or not, as desired, along with any side effect you like. Right, and that's also language-specification. Voodoo, yes, but language specification nonetheless. :) From khemkaamit at gmail.com Tue Nov 22 09:26:15 2005 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 22 Nov 2005 19:56:15 +0530 Subject: matching a string to extract substrings for which some functionreturns true In-Reply-To: References: <1360b7230511220418q6ede018bhcd80655f8a4f1530@mail.gmail.com> Message-ID: <1360b7230511220626t79b36b18s3418bed8e2d2407e@mail.gmail.com> Fredrik, thanks for your suggestion. Though the html page that are generated are for internal uses and input is verified before processing. And more than just a solution in current context, actually I was a more curious about how can one do so in Python. cheers, amit. On 11/22/05, Fredrik Lundh wrote: > Amit Khemka wrote: > > > Well actually the problem is I have a list of tuples which i cast as > > string and then put in a html page as the value of a hidden variable. > > And when i get the string again, i want to cast it back as list of tuples: > > ex: > > input: "('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), > > ('foo2', 2, 'foobar2', (3, 2))" > > output: [('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), > > ('foo2', 2, 'foobar2', (3, 2))] > > > > I hope that explains it better... > > what do you think happens if the user manipulates the field values > so they contain, say > > os.system('rm -rf /') > > or > > "'*'*1000000*2*2*2*2*2*2*2*2*2" > > or something similar? > > if you cannot cache session data on the server side, I'd > recommend inventing a custom record format, and doing your > own parsing. turning your data into e.g. > > "foo:1:foobar:3:0+foo1:2:foobar1:3:1+foo2:2:foobar2:3:2" > > is trivial, and the resulting string can be trivially parsed by a couple > of string splits and int() calls. > > to make things a little less obvious, and make it less likely that some > character in your data causes problems for the HTML parser, you can > use base64.encodestring on the result (this won't stop a hacker, of > course, so you cannot put sensitive data in this field). > > > > > > -- > 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 thomasbartkus at comcast.net Thu Nov 3 10:18:04 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 3 Nov 2005 09:18:04 -0600 Subject: Python and MySQL References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: "Steve Holden" wrote in message news:mailman.49.1130981382.18701.python-list at python.org... > Thomas Bartkus wrote: > > "Steve Holden" wrote in message > > news:mailman.44.1130970219.18701.python-list at python.org... > > > >>I have a _mysql.c as a part of my distrbution of MySQLdb. Don't you? > >> > > > > > > You made me give that library a good hard stare. > > > > And no - everything is enunciated in clear Python (.py) code with > > corresponding (.pyc) and (.pyo). It appears we have Python source for > > everything. > > > > FWIW: > > > > > >>>>print MySQLdb.version_info > > > > (1, 2, 0, 'final', 1) > > > OK. I saw that my own version was (1, 0, 0, 'final', 1), so I assumed > Andy's updated the package somewhat. However, downloading the source of > 1.2 I see that _mysql.c still appears, and that the package's > __init__.py still includes the line > > include _mysql > > My C:\Python24\Lib\site-packages directory does contain a _mylsql.pyd > file. Would you like to check that we are talking about the same module? Okay - I neglected to look at the [site-packages] directory itself. Here I do find [_mysql.pyd] full of binary code. A MySQLdb related file that doesn't seem to have a corresponding file with Python source code. Mea culpa! This is on MS Windows [C:\Python23]. But heck! Now I'm looking at the /usr/lib/python2.3/site-packages on a Mandrake Linux box. No [_mysql.] pyd here! Fewer files overall and while there are other file extensions, everything seems to have a corresponding [.py]. print MySQLdb.version_info (0, 9, 2, 'final', 1) Thomas Bartkus From carsten at uniqsys.com Wed Nov 23 09:02:26 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 23 Nov 2005 09:02:26 -0500 Subject: syntax errors while building pypgsql In-Reply-To: <3uj7hcF10k63tU1@individual.net> References: <3uj7hcF10k63tU1@individual.net> Message-ID: <1132754546.13909.20.camel@dot.uniqsys.com> On Wed, 2005-11-23 at 08:01, Tin Gherdanarra wrote: > Hallo, > > I'm trying to install pypgsql. However, I get syntax errors > while compiling the C sources. The following excerpt > from pgconnection.h looks a little funny to me: > > typedef struct { > PyObject_HEAD /* Here is the syntax error, and rightly so */ > PGconn *conn; > PyObject *host; > PyObject *port; > PyObject *db; > PyObject *options; > PyObject *tty; > PyObject *user; > PyObject *pass; > PyObject *bePID; > PyObject *socket; > PyObject *version; > PyObject *notices; > PyObject *cinfo; > int showQuery; > } PgConnection; > > > I don't know what PyObject_HEAD or PGconn is, > but if they are types, a syntax error is justified here: PyObject_HEAD is not a type, it is a macro that defines struct members that all Python objects have in common. The macro definition has a semicolon at the end, so when the macro is expanded, the result is syntactically correct, even though the above looks wrong on the surface. What error messages are you actually getting? If you are getting a long list of errors, please give us the first few rather than the last few. -Carsten From fredrik at pythonware.com Mon Nov 21 06:26:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Nov 2005 12:26:59 +0100 Subject: duplicate items in a list References: <1d987df30511210249g599223a1i13967fd4d47488d3@mail.gmail.com> Message-ID: Shi Mu wrote: > I used the following method to remove duplicate items in a list and > got confused by the error. > > >>> a > [[1, 2], [1, 2], [2, 3]] > >>> noDups=[ u for u in a if u not in locals()['_[1]'] ] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iterable argument required by the way, assuming that it doesn't really matter whether the resulting list contains lists or tuples, here's a simple oneliner-plus- optional-import solution: # this is only needed if you're using 2.3 or earlier >>> from sets import Set as set >>> hasDups = [[1, 2], [1, 2], [2, 3]] >>> noDups = list(set(map(tuple, hasDups))) >>> noDups [(1, 2), (2, 3)] if you need an order-preserving implementation, see raymond's example over at the cookbook. From klaus at seistrup.dk Fri Nov 18 11:21:43 2005 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Fri, 18 Nov 2005 16:21:43 +0000 (UTC) Subject: How to convert a "long in a string" to a "long"? References: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> Message-ID: <437dff97-47433160-8383-4413-ae65-99afea57ec53@news.szn.dk> Carsten Haese wrote: >> OK, this is what I want, so I tried >> >> s = long("0xffffffffL") >> ValueError: invalid literal for long(): 0xffffffffL >> >> s = long("0xffffffff") >> ValueError: invalid literal for long(): 0xffffffffL >> >> What can I do? >> >> Thank you in advance. >> Stefan > > Leave out the "0x" prefix and tell long() that you're using > base 16: > >>>> long("ffffffff", 16) > 4294967295L It's sufficient to tell long() that you're using base 16: #v+ >>> long('0xffffL', 16) 65535L >>> #v- Cheers, -- Klaus Alexander Seistrup Copenhagen, Denmark http://seistrup.dk/ From fredrik at pythonware.com Sat Nov 19 08:50:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Nov 2005 14:50:07 +0100 Subject: Can you set a class instance's attributes to zero by setting theinstance to zero? References: <1132406947.812243.274010@o13g2000cwo.googlegroups.com> Message-ID: Gerard Flanagan wrote: > If I have the Vector class below, is there a means by which I can have > the following behaviour > >>>>A = Vector(1, 2) >>>>print A > (1, 2) >>>>A = 0 that operation rebinds A; it doesn't affect the Vector instance in any way. more here: http://effbot.org/zone/python-objects.htm From xray_alpha_charlie at yahoo.com Mon Nov 7 15:04:04 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Mon, 7 Nov 2005 12:04:04 -0800 (PST) Subject: what the %?.... Message-ID: <20051107200405.25840.qmail@web35905.mail.mud.yahoo.com> Hey can somebody tell me what the "%" function does...I am not math illiterate...its just a new symbol for me....is it a divisor? remainder something another?? thanks -xray- --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fccoelho at gmail.com Mon Nov 28 06:44:00 2005 From: fccoelho at gmail.com (Flavio) Date: 28 Nov 2005 03:44:00 -0800 Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> Message-ID: <1133178240.261194.212130@g14g2000cwa.googlegroups.com> If you read my original post, I had no intention of atributing the user's method to the class, but to the instance. Anyway I figure it out myself, and its quite a Pythonic solution: >>> class Foo: name='John' >>> a=Foo() >>> def p(parent): self=parent print 'Hi, %s!'%self.name >>> a.met=p >>> a.met(a) Hi, John! This works the same way an object's built-in method would work, since all methods receive a reference to the parent object through the required argument "self". class Foo: def met(self): print self Thanks for all the replies, they helped to catalize my own thoughts! Fl?vio From fredrik at pythonware.com Thu Nov 10 15:47:12 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Nov 2005 21:47:12 +0100 Subject: exceptions, internals (introspection?) References: <4373ae4a$1@nntp.zianet.com> Message-ID: "ej" <"ej atwellkeepercom"@bag.python.org> wrote > try: > {}['foo'] > except Exception, x: > print "class of x =", x.__class__ > print "type(x) =", type(x) > print "dir(x) =", dir(x) > > If you don't handle an exception, the interpreter will quit and print a > stack trace. What I'm not seeing is how to handle the exception, but still > get the stack trace as a string so I could dump it to a log file or email it > or something. the second example on this page shows you how to do that: http://effbot.org/librarybook/traceback From venkatasubramanian at gmail.com Thu Nov 3 06:19:22 2005 From: venkatasubramanian at gmail.com (venk) Date: 3 Nov 2005 03:19:22 -0800 Subject: Anomaly in creating class methods Message-ID: <1131016762.522810.91780@f14g2000cwb.googlegroups.com> Hi, given below is my interaction with the interpreter.... In one case, i have created the class method using the "famous idiom"... and in the other, i have tried to create it outside the class definition... why isn't the latter working ? (of course, the presence of decorators is a different issue).... >>> class D: ... def f(cls): ... print cls ... >>> D.f=classmethod(D.f) >>> D.f > >>> D.f() Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method f() must be called with D instance as first argument (got classobj instance instead) >>> class D: ... def f(cls): ... print cls ... f=classmethod(f) ... >>> D.f > >>> D.f() __main__.D From nope at nottelling.com Thu Nov 24 19:02:42 2005 From: nope at nottelling.com (JustSomeGuy) Date: Fri, 25 Nov 2005 00:02:42 GMT Subject: Draw a triangle... Message-ID: Hi I'm writing a python application on my windows box and I want to draw a simple triangle on the screen... How can I do this. Am I going to have to use tcl/tk? From nomail at nomail.com Tue Nov 29 08:30:38 2005 From: nomail at nomail.com (Nx) Date: Tue, 29 Nov 2005 21:30:38 +0800 Subject: run runs away Message-ID: <438c57fe@127.0.0.1> Hello I think my question is how to make the script wait until it returns from a call to run() Here is a code snippet: # next lines calls python2.4 32 bit version # from a script running in python2.3 64 bit version run("python2.4", "dbviewmaster.py") # I want the following only to run after # running of python2.4 has finished self.textBrowser1.reload f = open(self.DBMETA,'r') for self.getline in f.readlines(): self.textBrowser1.append(self.getline) f.close() Thanks for any hints how to do that. Nx From rurpy at yahoo.com Thu Nov 24 17:43:39 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 24 Nov 2005 14:43:39 -0800 Subject: defining the behavior of zip(it, it) In-Reply-To: <1h6hzbn.1ww7x45cvcp7vN%aleax@mail.comcast.net> References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> <1132712643.968300.151010@g49g2000cwa.googlegroups.com> <1132713954.040591.120660@f14g2000cwb.googlegroups.com> <1132718374.960509.206800@z14g2000cwz.googlegroups.com> <1132778601.776080.80100@g44g2000cwa.googlegroups.com> <1h6hzbn.1ww7x45cvcp7vN%aleax@mail.comcast.net> Message-ID: <1132872219.800028.244770@o13g2000cwo.googlegroups.com> Alex Martelli wrote: > wrote: > ... > > cookbook recipies of which there are already several good > > collections, but shorter things like, copy(sequence) is spelled > > "sequence[:]". > > No way: > > >>> from collections import deque > >>> d=deque([1,2,3]) > >>> d[:] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sequence index must be integer > >>> deque(d) > deque([1, 2, 3]) > >>> > > I.e., NOT all sequences implement the unreadable x[:] form. > > The way that DOES work with all sequences is typeyouwant(sequence). I'm sorry, I don't understand. Does deque return a sequence? The doc says it returns a deque object, and without further info I would not expect [:] to work. Is it a sequence because it has the same methods as a sequence? Whatever, I gather my old book is outdated and the blessed way now to (shallow) copy a sequence is (as you say) "typeyouwant(sequence)" which I will make a note of. Thanks for updating me. From stefan.arentz at gmail.com Thu Nov 3 07:08:35 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 03 Nov 2005 13:08:35 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: <873bmekk70.fsf@keizer.soze.com> Antoon Pardon writes: > Op 2005-11-03, Steven D'Aprano schreef : > > >> There are two possible fixes, either by prohibiting instance variables > >> with the same name as class variables, which would allow any reference > >> to an instance of the class assign/read the value of the variable. Or > >> to only allow class variables to be accessed via the class name itself. > > > > There is also a third fix: understand Python's OO model, especially > > inheritance, so that normal behaviour no longer surprises you. > > No matter wat the OO model is, I don't think the following code > exhibits sane behaviour: > > class A: > a = 1 > > b = A() > b.a += 2 > print b.a > print A.a > > Which results in > > 3 > 1 I find it confusing at first, but I do understand what happens :-) But really, what should be done different here? S. From jschamba at physics.utexas.edu Mon Nov 14 12:36:48 2005 From: jschamba at physics.utexas.edu (Jo Schambach) Date: Mon, 14 Nov 2005 11:36:48 -0600 Subject: how do i use "tkinter.createfilehandler" with a regular c program? Message-ID: I am trying to write a GUI with tkinter that displays the stdout from a regular C/C++ program in a text widget. The idea i was trying to use was as follows: 1) use "popen" to execute the C/C++ program 2) then use "tkinter.createfilehandler" to create a callback that would be called when the C/C++ program creates output on stdout. Somehow, I can't get this to work. here is what I have tried so far: import sys,os from Tkinter import * root = Tk() mainFrame = Frame(root) textBox = Text(mainFrame) textBox.pack(fill=BOTH, expand=YES) mainFrame.pack(fill=BOTH, expand=YES) fh = os.popen('/homes/jschamba/tof/pcan/pcanloop') def readfh(filehandle, stateMask): global textBox newText = filehandle.read() textBox.insert(END, newText) tkinter.createfilehandler(fh, tkinter.READABLE, readfh) root.mainloop() I don't see any of the stdout from my program appear in the textbox. Does anyone have a short example that I could use as an inspiration for this task? I guess what my ultimate goal would be is to create something similar to the "expectk" call "expect_background", which does exactly what i just described, i.e. wait for output from a shell/C/C++ program and then do something in response to this output like insert it into a text widget. In expect, the following program seems to work: #!/usr/bin/expectk -f # disable terminal output log_user 0 spawn -noecho /homes/jschamba/tof/pcan/pcanloop set shell $spawn_id text .shell -relief sunken -bd 1 -width 90 -height 24 -yscrollcommand {.scroll set} scrollbar .scroll -command {.shell yview} pack .scroll -side right -fill y pack .shell -side bottom -expand true -fill both expect_background { -i $shell -re "\[^\x0d]+" { .shell insert end $expect_out(0,string) .shell yview -pickplace insert } } Jo -- Dr Joachim Schambach The University of Texas at Austin Department of Physics 1 University Station C1600 Austin, Texas 78712-0264, USA Phone: (512) 471-1303; FAX: (814) 295-5111 e-mail: jschamba at physics.utexas.edu From steve at REMOVEMEcyber.com.au Wed Nov 23 03:05:57 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 23 Nov 2005 19:05:57 +1100 Subject: What a curious assignment. References: <1132721032.455988.259600@o13g2000cwo.googlegroups.com> Message-ID: <438422E5.6090003@REMOVEMEcyber.com.au> Neil.Jin at gmail.com wrote: > Is there somthing wrong???? Kids today, don't they learn about inheritence? :-) Python's object model is that instances inherit both methods and attributes from the class (and superclasses). Methods are just a special case of attributes: the method is a callable attribute. When you reference an attribute, Python first checks the instance by looking up instance.__dict__, and if that fails, it looks up instance.__class__.__dict__. (This is a simplification, e.g. it isn't exactly true for objects with slots.) For attribute lookup (that is, the attribute reference is on the right hand side of an assignment), the lookup may fail and so the class attribute may be retrieved. This is by design. For attribute assignment (that is, the attribute reference is on the left hand side of an assignment), the assignment will never fail. (Again, ignoring slots and any other special cases I have't thought of.) -- Steven. From csubich.spam.block at spam.subich.block.com Mon Nov 7 14:03:45 2005 From: csubich.spam.block at spam.subich.block.com (Christopher Subich) Date: Mon, 07 Nov 2005 14:03:45 -0500 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > Op 2005-11-04, Christopher Subich schreef : >>it's the Python >>idiosyncracy about operations on mutable types. In this case, += >>mutates an object, while + returns a new one -- as by definition, for >>mutables. > > > It is the combination of the two. > > If python had chosen for an approach like function namespaces, the > problem wouldn't have occured either. What would have happened then > is that the compilor would have noticed the a.x on the right hand > side and based on that fact would then have deciced that all a.x > references should be instance reference (at least in that function > block). The a.x += ... would then result in an AttributeError being raised. Problem: """ class B: x = 1 classx = b() instx = b() instx.x = 5 def addtox(o): o.x += 1 addtox(instx) print B.x # 1 print instx.x # 6; we both agree on this one addtox(classx) # You argue this should AttributeError print B.x # ?! -- 1 currently, you argue 2 if no error print class.x # we both agree 2, if no error """ a.x is /not/ a namespace issue at all; it's an attribute issue. .x is not a name, it is an attribute. Python namespaces are lexically scoped, not dynamically scoped; if, as you argue, .x should be a name in a namespace, then you argue above that addtox in the above should work on instx but fail on classx. But this /cannot be determined at compile time/, because the attribute space is attached to the object passed in as the parameter. I repeat: this is not a name issue at all, it is an attribute issue. Python's behaviour is counterintuitive from some angles, but it is the only behaviour that is consistent with attributes in general, given the signature of __iadd__ as-is. > > You may prefer the current behaviour over this, but that is not the > point. The point is that resolution of name spaces does play its > role in this problem. There are no name spaces. > > > It also has little to do with mutable vs immutable types. > Someone could implement an immutable type, but take advantage > of some implemtation details to change the value inplace > in the __iadd__ method. Such an immutable type would show > the same problems. Immutable? I do not think that word means what you think it means. From jmdeschamps at gmail.com Sat Nov 19 10:41:26 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 19 Nov 2005 07:41:26 -0800 Subject: Tkinter from Vis. BASIC In-Reply-To: <437f3e9f$0$6383$a82e2bb9@reader.athenanews.com> References: <437f3e9f$0$6383$a82e2bb9@reader.athenanews.com> Message-ID: <1132414886.146889.158170@g43g2000cwa.googlegroups.com> Terrance N. Phillip wrote: > In VB, an easy way I indicate progress is something like > do while > lblNotify.foreground = randomcolor > lblNotify.refresh <----------- > > loop > > I want to do the same thing in Python/Tkinter: > > # Wait for network to recognize the workstation: > while os.system("slist") != 0: > self.notify["fg"] = randcolor() > # how do I refresh label l3 at this point? > time.sleep(3) > > I've tried self.notify.grid() (I'm using the grid geometry manager > throughout), but that didn't work, and there is no redraw() or refresh() > method that I can see. I know of an update_idletask() method, look it up in the tkinter doc to see if that's what you need! From steve at REMOVETHIScyber.com.au Fri Nov 25 22:16:05 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 26 Nov 2005 14:16:05 +1100 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: On Fri, 25 Nov 2005 08:36:48 +0000, Steve Holden wrote: >>>>That's not a problem if there exists a verification program A which >>>>can't verify itself but can verify program B, which in turn also can't >>>>verify itself but will verify program A. >>>> >>> >>>That is logically equivalent to the first case, so it doesn't get you >>>anywhere. (Just combine A and B into a single program which invokes A >>>unless the input is A when it invokes B instead.) >> >> >> Then there you go, there is a single program which can verify itself. >> >> I think you are confabulating the impossibility of any program which can >> verify ALL programs (including itself) with the impossibility of a program >> verifying itself. Programs which operate on their own source code do not >> violate the Halting Problem. Neither do programs which verify some >> subset of the set of all possibly programs. >> >> > There seems to have been some misattribution in recent messages, since I > believe it was *me* who raised doubts about a program verifying itself. Fair enough. > This has nothing to do with the Halting Problem at all. On the contrary, the Halting Problem is just a sub-set of the verification problem. Failure to halt when it is meant to is just one possible way a program can fail verification. On the one hand, the Halting Problem is much simpler than the question of proving formal correctness, since you aren't concerned whether your program actually does what you want it to do, so long as it halts. But on the other hand, the Halting Problem is so much harder that it actually becomes impossible -- it insists on a single algorithm which is capable of checking every imaginable input. Since real source code verifiers make no such sweeping claims to perfection (or at least if they do they are wrong to do so), there is no such proof that they are impossible. By using more and more elaborate checking algorithms, your verifier gets better at correctly verifying source code -- but there is no guarantee that it will be able to correctly verify every imaginable program. > A very simple > possible verification program is one that outputs True for any input. > This will also verify itself. Unfortunately its output will be invalid > in that and many other cases. No doubt. But slightly more complex verification programs may actually analyse the source code of some arbitrary program, attempt to use formal algebra and logic to prove correctness, returning True or False as appropriate. That program itself may have been painstakingly proven correct by teams of computer scientists, logicians and mathematicians, after which the correctness of its results are as certain as any computer program can be. That is the program we should be using, not your example. > I maintain that we cannot rely on any program's assertions about its own > formal correctness. There are two ways of understanding that statement. If all you mean to say is "We cannot rely on any program's assertions about any other programs formal correctness, including its own", then I can't dispute that -- I don't know how well formal correctness checking programs are. It is possibly, I suppose, that the state of the art merely returns True regardless of the input, although I imagine a more realistic estimate is that they would at least call something like pylint to check for syntax errors, and return False if they find any. But if you mean to say "While we can rely on the quality of correctness checkers in general, but not when they run on their own source code" then I think you are utterly mistaken to assume that there is some magic quality of a verification program's own source code that prevents the verification program working correctly on itself. And that was my point: formal correctness checking programs will be as good as testing themselves as they are at testing other programs. If you trust them to check other programs, you have no reason not to trust them to check themselves. -- Steven. From bokr at oz.net Sun Nov 20 22:06:18 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 21 Nov 2005 03:06:18 GMT Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> <86hda8hsft.fsf@bhuda.mired.org> Message-ID: <438138a1.337525155@news.oz.net> On Sun, 20 Nov 2005 15:50:10 +0100, Eric Jacoboni wrote: >Mike Meyer writes: > >> I've seen at least one language (forget which one) that allowed such >> separators, but only for groups of three. So 123_456 would be valid, >> but 9_1 would be a syntax error. > >Ada allows underscores in numeric literals since 1983, without >enforcing any grouping. The Ruby language allows also this >notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the >same for real numbers...). > Actually, I guess I could be convinced, even though I posted a you-can-do-this-now decorator to bracket the op's desired function defs. >When you have the habit to represent literals like that, all other >big numeric literals or workarounds to create grouping seem cryptic. > >-- >Eric Jacoboni, ne il y a 1435938104 secondes My previous smiley re your sig in this thread context still applies ;-) Regards, Bengt Richter From davidb at mcs.st-and.ac.uk Fri Nov 25 12:25:37 2005 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 25 Nov 2005 09:25:37 -0800 Subject: How to get started in GUI Programming? References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132939536.961593.212260@g49g2000cwa.googlegroups.com> peter.mosley at talk21.com wrote: > I am trying to learn GUI programming in Python, but have to confess I > am finding it difficult. > > I am not an experienced programmer - just someone who from time to > time writes small programs for my use. Over the years I have moved > from GWBASIC to QBASIC to Visual Basic, and now trying to move across > to a Linux platform. Python seems to be the best compromise between > the limitations of command line basic programming and the total > incomprehensibility of C. > > Googling around it seems the best GUI is either Tkinter or PyGtk. You might also want to try PyQt: http://www.riverbankcomputing.co.uk/pyqt/ I'm sure fans of wxWidgets will also point you in the direction of their favourite bindings. ;-) David From mwm at mired.org Sat Nov 5 02:14:57 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 02:14:57 -0500 Subject: re sub help References: <1131173343.954029.211530@o13g2000cwo.googlegroups.com> Message-ID: <86fyqb7eha.fsf@bhuda.mired.org> s99999999s2003 at yahoo.com writes: > hi > > i have a string : > a = > "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" > > inside the string, there are "\n". I don't want to substitute the '\n' > in between > the [startdelim] and [enddelim] to ''. I only want to get rid of the > '\n' everywhere else. Well, I'm not an expert on re's - I've only been using them for three decades - but I'm not sure this can be done with a single re, as the pattern you're interested in depends on context, and re's don't handle that well. On the -- Mike Meyer http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jeff at schwabcenter.com Wed Nov 9 14:29:05 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Wed, 09 Nov 2005 19:29:05 GMT Subject: Pythonising the vim (e.g. syntax popups) In-Reply-To: References: Message-ID: <56scf.3672$Ea3.919572@twister.southeast.rr.com> Christoph Haas wrote: > Evening, > > I'm an addicted vim user and don't really use the IDLE for anything more > than calculations where I'm too lazy to start KCalc. But one feature is > very pretty: the built-in help for function calls while you type. Like you > enter... > > var1,var2=mystring.split( > ...and the IDLE shows me a popup saying... > "S.split([sep [,maxsplit]]) -> list of strings > > Is there a decent way to get that help into vim? Or like showing docstrings > or help that I get through pydoc on request? I've been working myself > through a pile of vim macros/plugins but couldn't find even one which > simplifies programming in Python. Further issues would be handling the > indentation - maybe a plugin which syntax colors different levels of > indentation so I don't have to use my plastic ruler on the screen. ;) > Perhaps some more experienced Python/Vim users have a tip which macro sets > help most here. Vim is my editor of choice, too. I've even gone back to Vim from Eclipse. I believe what you want are "tags." http://www.vmunix.com/vim/tags.html I have not tried these in Vim yet, although I did use etags with Emacs (before I discovered the miracle of Vim). If you get context-sensitive help to work properly in Vim, please let me know! From peter at engcorp.com Sat Nov 5 19:19:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Nov 2005 19:19:43 -0500 Subject: Modify HTML data In-Reply-To: <1131235132.163505.280600@g43g2000cwa.googlegroups.com> References: <1131235132.163505.280600@g43g2000cwa.googlegroups.com> Message-ID: Swarna wrote: > I am using scp in python to copy a html file on remote server, to my > local machine. Now, i need to update this html file in my local machine > ( by adding a new Hyperlink to the existing table od hyperlinks ) and > copy it back (overwriting the old copy ) to the remote server. If you are using scp to copy the file from the remote server in the first place, what's stopping you from using scp to copy it back? From steve at REMOVETHIScyber.com.au Sat Nov 19 23:43:02 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 20 Nov 2005 15:43:02 +1100 Subject: Hot to split string literals that will across two or more lines ? References: <1132284614.326121.252250@g49g2000cwa.googlegroups.com> <*firstname*nlsnews-A71E9A.23194917112005@news.verizon.net> <86lkzkht93.fsf@bhuda.mired.org> Message-ID: On Sat, 19 Nov 2005 22:51:04 -0500, Mike Meyer wrote: > Steven D'Aprano writes: >> Brackets include: >> >> parentheses or round brackets ( ) >> square brackets [ ] >> braces or curly brackets { } >> chevrons or angle brackets ??? ??? >> >> The symbols for chevrons are not available on common keyboards, are not >> available in ordinary ASCII, and may not show up correctly in many >> typefaces, so a common alternative is to substitute less than and greater >> than signs < > as brackets. HTML and XML use that convention. > > Hmm. I'm used to seeing "angle brackets" - aka brokets - used to refer > to . That may be the convention you mention leaking across, though. > > You imply that HTML/XML might use chevrons. I don't think that's the > case. They inherit their start/end tag characters from SGML's > default. No! That's not what I said. SGML-derived languages use greater-than and less-than symbols < > as if they were brackets. That's practicality beats purity: true chevrons are not available in ASCII or on common keyboards, making them difficult to use. People commonly call < and > "angle brackets" in the context of HTML etc. but they aren't really, they are mathematical comparison operator signs. Proper chevrons are narrower and taller. The difference between ? ? and < > is *very* obvious in the font I'm using, although of course not all fonts use the proper glyphs. If it helps, the angle on the inside of the chevron is about 120 degrees, compared to maybe 60 degrees for the comparison operators. Again, this depends on the precise glyph being used. True angle brackets are available in Unicode at code points 9001 and 9002, (0x2329 and 0x232A). The less-than and greater-than symbols can be found in both Unicode and ASCII at code points 60 and 62 (0x003C and 0x003E). I did warn in my earlier post that I was being pedantic. In common usage, I'll describe as using angle brackets, just as I'll describe "quote" as using quote marks. They're not actually: they are double-prime marks, and ' is a prime mark not an apostrophe or quote mark. Prime and double-prime marks are also known as foot and inch marks, although *real* pedants would argue that there is a difference between them too. (I think they get separate Unicode points.) It is easy to get confused when it comes to characters, because there are three separate but related things to keep in mind. Firstly, there is the glyph or picture used, which differs according to the font and type-style. Two different glyphs can represent the same symbol, and two identical glyphs can represent different symbols. Secondly, there is the semantic meaning of the character: a dash and a hyphen are both horizontal lines, but they have very different meanings. Dashes -- sometimes faked with two hyphens in a row like this -- are used as separators, and hyphens are used to join compound words like fire-fighting or anti-matter. Thirdly, there is the specific implementation of the character. ASCII defines only 127 characters, a good thirty-plus being invisible control characters. Eight-bit extensions to ASCII unfortunately vary between each other: the character 176 (0xB0) is the degree symbol in the Latin-1 encoding (ISO 8859-1) but the infinity symbol in the MacRoman encoding. -- Steven. From Serge.Orlov at gmail.com Mon Nov 28 00:18:42 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 27 Nov 2005 21:18:42 -0800 Subject: Python as Guido Intended In-Reply-To: References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> Message-ID: <1133155122.587903.237140@g44g2000cwa.googlegroups.com> Antoon Pardon wrote: > No it wasn't. From what I have picked up, the ternary operator > was finaly introduced after one of the developers tripped over > the commonly used idiom to simulate a ternary operator, which > can fail in certain cases. > > Anyway, when I was arguing for a ternary operator in python, > those who opposed me, certainly gave me the impression that > they thought I wanted to mangle the language, the mere idea > of a ternary operator was against the spirit of python. > > When I argued for a more general loop construct similar > objections were made and the proposal was fiercely fought. > Someone even started a PEP, with the intention to bury > the idea. (That can be from before I argued for it) > > Now I have read about both that they will be introduced in > Python 2.5 without a whisper of protest. Protesting BDFL is absolutely useless by definition even if you disagree. Tim Peters wanted generators for 10 years and he has much more power of convincing Guido than you. Why do you think your proposal should be immediately accepted? By the way, I don't see the features you mentioned neither in nor among PEPs. Perhaps they are not final? From dwahler at gmail.com Sat Nov 19 07:17:36 2005 From: dwahler at gmail.com (David Wahler) Date: 19 Nov 2005 04:17:36 -0800 Subject: Web-based client code execution References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> Message-ID: <1132402656.285350.146460@z14g2000cwz.googlegroups.com> Steve wrote: > AJAX works because browsers can execute javascript. I don't know of a > browser that can execute python. Basically your stuck with java or > javascript because everything else really isn't cross platform Don't jump to conclusions... http://dwahler.ky/python/ If you really, really want Python in a browser, it's certainly possible. :) -- David From rganesan at myrealbox.com Tue Nov 22 23:33:25 2005 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Wed, 23 Nov 2005 10:03:25 +0530 Subject: Why are there no ordered dictionaries? References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> <1h6f39h.n2wpx91c4cc2qN%aleax@mail.comcast.net> <1h6fxle.14lh8381m383fhN%aleax@mail.comcast.net> Message-ID: >>>>> Alex Martelli writes: > Ordered *by order of key insertion*: Java, PHP > Ordered *by other criteria*: LISP, C++ Java supports both ordered by key insertion (LinkedHashMap) as well as ordered by key comparison (TreeMap). Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan | http://rganesan.blogspot.com From ashokagk at gmail.com Wed Nov 23 13:48:13 2005 From: ashokagk at gmail.com (ash) Date: 23 Nov 2005 10:48:13 -0800 Subject: python gui using boa In-Reply-To: References: <1132637738.473190.311620@g43g2000cwa.googlegroups.com> Message-ID: <1132771693.777165.63860@g43g2000cwa.googlegroups.com> Thanks Steve, i found out the solution to the problem. but a good tutorial on sizers is still missing. From robert.kern at gmail.com Sun Nov 27 20:30:22 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 27 Nov 2005 17:30:22 -0800 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > Sometimes I find myself stumbling over Python issues which have to do > with what I perceive as a lack of orthogonality. > > For instance, I just wanted to use the index() method on a tuple which > does not work. It only works on lists and strings, for no obvious > reason. Why not on all sequence types? > > Or, another example, the index() method has start and end parameters for > lists and strings. The count() method also has start and end parameters > for strings. But it has no such parameters for lists. Why? > > However when I ask such things I noticed I get answers like: "Is there a > use case?" "You can do it some other way so it is not worth bothering." > > Let me ask back: Do I really need to bother and justify it with a use > case in a case where the language can be easily made more consistent or > orthogonal without breaking anything? Yes. If it's not going to be used, then there's not much point. Practicality beats purity, and all that. However, I will note that if you were to present us with a working patch with documentation and unittests, then you'll probably get responses along the lines of "Thank you!", instead. -- 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 steve at holdenweb.com Thu Nov 3 07:50:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Nov 2005 12:50:06 +0000 Subject: Getting Python Accepted in my Organisation In-Reply-To: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> Message-ID: Stuart Turner wrote: > Hi Everyone, > > I'm working hard trying to get Python 'accepted' in the organisation I work > for. I'm making some good in-roads. One chap sent me the text below on > his views of Python. I wondered if anyone from the group could give me > some advice on how to respond / if they had been in a similar position. > > Any help appreciated, > > Thanks in advance, > > - Stuart > > > "Python is a scripting language like Perl, awk, tcl, Java etc... it is > not quite a fully developed OO language, but does support some OO that Perl > doesn't. To be clear, these scripting languages have their place in our > environment, but they are not full replacements for C#, Java, C, etc... > because they do not come with the full range of libraries e.g GDI > libraries. Python has to be compared to Perl, Awk in order to evaluate it. > Perl, until recently, did not support threading. Why would it? it is a > scripting language and can run async shell commands. I would be interested > to learn if Python supports a robust threading model (not just a pointer > reference to an object), as this is a significant drawback when using a > scripting language. CGI only works because the container can thread with > Perl. Python is object orientated, but I do not know what implementation? > Essentially any language with a pointer can claim to be OO, although Python > does market itself on OO capabilities. Do you know what implementation > they have used? > > Lets discuss, as I am not a great fan of Perl and if Python is more > structured then it is possibly worth promoting." First of all, let's dismiss the notion that "Python is a scripting language". It can be used for scripting tasks, and has been successfully so used in many environments, but it's a fully-developed programming language with a well-defined and cleanly-implemented OO model. Many people call Python a scripting language because it is interpreted, but the parallel with Java is better that that with Perl, since Python compiles programs into bytecodes for a virtual machine. An advantage of Python is that while it is fully object-oriented it is also well-suited to procedural programming and, unlike Java, you are not forced to try and fit all tasks into an object-oriented model. Python does indeed support a robust threading model, and has recently improved threading support still further by adding explicit features to support per-thread state in a cleaner way. It has been used to implement many high-volume asynchronous network server tasks, among which Zope is perhaps the best known. The author of your comments asks "what implementation" of OO capabilities Python uses. This is a very broad question, but basically Python uses a multiple-inheritance model (though nobody is forced to use multiple superclasses) and has a very clean object orientation. For background I have been studying and working with object oriented languages for over thirty years, and find Python the most natural and cleanest way to express many object oriented programming solutions. Finally I feel that the Python community is much more welcoming than that of most programming languages, which is important if you are looking for support as your familiarity with the language grows. Good luck with your Python advocacy. 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 universal_used at hotmail.com Thu Nov 3 01:16:45 2005 From: universal_used at hotmail.com (questions?) Date: 2 Nov 2005 22:16:45 -0800 Subject: how can I run python interactively? Message-ID: <1130998605.892334.70810@g49g2000cwa.googlegroups.com> I need to stop the program in the middle and pause there. Are there anyway I can stop the program in the middle and have something like: please press y to continue..... Thanks From levub137 at wi.rr.com Tue Nov 8 07:30:35 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Tue, 08 Nov 2005 12:30:35 GMT Subject: any python module to calculate sin, cos, arctan? In-Reply-To: References: Message-ID: Shi Mu wrote: > any python module to calculate sin, cos, arctan? The other answers in this thread point you to the standard modules. If you need arbitrary precision floating point versions of these functions check out: http://calcrpnpy.sourceforge.net/clnumManual.html From codecraig at gmail.com Tue Nov 8 08:46:45 2005 From: codecraig at gmail.com (py) Date: 8 Nov 2005 05:46:45 -0800 Subject: SPE IDE for Python Message-ID: <1131457605.425734.54340@g44g2000cwa.googlegroups.com> Anyone here use SPE (http://www.stani.be/python/spe/blog/). ...the IDE? Also, anyone know if it supports CVS or has a plugin for CVS? If not, what do you use to get your code into CVS (via an IDE preferably)? From jepler at unpythonic.net Mon Nov 7 14:53:00 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 7 Nov 2005 13:53:00 -0600 Subject: O_DIRECT on stdin? In-Reply-To: References: Message-ID: <20051107195300.GC4532@unpythonic.net> I think this is fcntl(..., F_SETFL, ...), so something like import os, fcntl, sys flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) flags |= os.O_DIRECT fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From R.Brodie at rl.ac.uk Tue Nov 1 10:39:52 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 1 Nov 2005 15:39:52 -0000 Subject: String Identity Test References: Message-ID: "Roy Smith" wrote in message news:dk81pf$s2p$1 at panix2.panix.com... > On the other hand, I can't imagine any reason why you would want to > define such a class, PEP 754? From DustanGroups at gmail.com Fri Nov 25 12:05:22 2005 From: DustanGroups at gmail.com (Dustan) Date: 25 Nov 2005 09:05:22 -0800 Subject: Modifying Unix ReadKey Code Message-ID: <1132938322.847134.134840@g44g2000cwa.googlegroups.com> I found this site that has code for readkey for Windows, Unix, and in an updated version, Mac: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 . The Mac object returns a character whether or not a key was pressed. I modified the Windows object to do the same when I downloaded it, but I have no idea how to make the Unix object to do the same. Any help??? Not to be pushy, but I would like an answer soon. From striker at trip.net Mon Nov 14 12:43:57 2005 From: striker at trip.net (striker) Date: 14 Nov 2005 09:43:57 -0800 Subject: replacing multiple instances of commas beginning at specific position Message-ID: <1131990237.288604.137690@z14g2000cwz.googlegroups.com> I have a comma delimited text file that has multiple instances of multiple commas. Each file will contain approximatley 300 lines. For example: one, two, three,,,,four,five,,,,six one, two, three,four,,,,,,,,,,eighteen, and so on. There is one time when multiple commas are allowed. Just prior to the letters ADMNSRC there should be one instance of 4 commas. ( ,eight,,,,ADMNSRC,thirteen, ). The text ADMNSRC is NOT in the same place on each line. What would be the best approach to replace all instances of multiple commas with just one comma, except for the 4 commas prior to ADMNSRC? Any help would be greatly appreciated. TIA, Kevin From ex_ottoyuhr at hotmail.com Wed Nov 30 22:45:04 2005 From: ex_ottoyuhr at hotmail.com (ex_ottoyuhr) Date: 30 Nov 2005 19:45:04 -0800 Subject: Recursion bug... In-Reply-To: <1133406638.583675.234700@z14g2000cwz.googlegroups.com> References: <1133405155.154823.134620@g47g2000cwa.googlegroups.com> <1133406638.583675.234700@z14g2000cwz.googlegroups.com> Message-ID: <1133408704.924385.267280@g47g2000cwa.googlegroups.com> Devan L wrote: > Well, for one, in your __init__ method, you never do anything with > anOpcode. You simply assign the name 'opcode' to anOpcode. The reason > why everything is the same is that you're accessing > TreeCommand.children or Treecommand.opcode, which is shared by all > instances unless you assign to it. OK, _that's_ what I was doing wrong... Thanks a lot. I suspected it might be a product of C++-isms and being self-taught in the language... > And you never increment generated, > so I don't see why the while loop would ever end, unless you > intentionally wanted that. I just forgot to add that part -- I was demi-transcribing it, you might put it, as opposed to actually copying. There were a few bugs in that part... :P > Try this code instead: > From kent37 at tds.net Tue Nov 1 12:49:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 01 Nov 2005 12:49:54 -0500 Subject: Flat file, Python accessible database? In-Reply-To: References: Message-ID: <4367a882$1_1@newspeer2.tds.net> Karlo Lozovina wrote: > I've been Googling around for _small_, flat file (no server processes), > SQL-like database which can be easily access from Python. Speed and > perforamnce are of no issue, most important is that all data is contained > within single file and no server binary has to run in order to use the > dbase. Oh, and I'm using Python under Cygwin. Depending on what you mean by "SQL-like" you might like KirbyBase http://www.netpromi.com/kirbybase.html Kent From steve at holdenweb.com Thu Nov 24 00:44:11 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 05:44:11 +0000 Subject: return in loop for ? In-Reply-To: <86wtiy28z5.fsf@bhuda.mired.org> References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > yomgui writes: > >>Mike Meyer wrote: >> >>>yomgui writes: >>> >>>>is it legal to return inside a for loop >>>>or am I obliged to break out of the loop before returning ? >>> >>>Try it and see: >> >>it is not because it does work on an implementation of python >>that it will work on any other platform or in the futur. > > > That's true no matter how you arrive at your answer. > But, to answer the specific question, there's nothing in the language definition that suggests the programmer should refrain from using a return inside a loop, so for any implementation to impose such a restriction would be a violation of the language definition. Yomgui: I am not a language lawyer, but I think you can feel safe returning from inside a loop. Just as a matter of interest, how else would you propose to implement the functionality Mike showed: > >>>def f(): > > ... for i in range(20): > ... if i > 10: return i > ... > Python is supposed to cleanly express the programmer's intent. I can;t think of a cleaner way that Mike's - can you? 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 desparn at wtf.com Wed Nov 23 07:36:26 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Wed, 23 Nov 2005 07:36:26 -0500 Subject: Why are there no ordered dictionaries? References: <438258f2.411334718@news.oz.net> <4383635b.479535916@news.oz.net> <1132734447.104113.99140@o13g2000cwo.googlegroups.com> Message-ID: "Fuzzyman" wrote in news:1132734447.104113.99140 at o13g2000cwo.googlegroups.com: > > Christoph Zwerschke wrote: >> - the internal keys list should be hidden > > I disagree. It is exposed so that you can manually change the > order (e.g. to create a "sorted" dict, rather than one ordered > by key insertion). > > What do you *gain* by hiding it ? The internal list should be 'hidden' in the sense that it itself would not be modifiable, though it should be routine to obtain a copy of it at any time. That copy could then be arranged as needed. Any rearrangement of the original list's order destroys the reason for having an entry- or change-ordered dict in the first place. -- rzed From steve at REMOVETHIScyber.com.au Wed Nov 2 16:33:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 03 Nov 2005 08:33:23 +1100 Subject: Most efficient way of storing 1024*1024 bits References: Message-ID: On Wed, 02 Nov 2005 13:55:10 +0100, Tor Erik S?nvisen wrote: > Hi > > I need a time and space efficient way of storing up to 6 million bits. [inserts pinky in corner of mouth] Six MILLION bits!!! That's almost 750K. Are you sure your computer will handle that much data? > Time > efficency is more important then space efficency as I'm going to do searches > through the bit-set. Could you be more vague if you tried? Searching for what? Does your data have structure you can exploit? Can you put it in a tree structure? Are you going to be inserting and deleting data? If you can handle your six million bits in lots of eight, store them as a character string. If you can keep your data sorted, then you can do binary searches instead of linear searches. If your data is hashable, you can store it in a dictionary and potentially get up to constant-time search speeds. Or forget about manipulating bits, and just store your data as bools in a list. Explain your problem a little better, and you may get some better advice. -- Steven. From rupole at hotmail.com Wed Nov 2 13:19:29 2005 From: rupole at hotmail.com (Roger Upole) Date: Wed, 2 Nov 2005 13:19:29 -0500 Subject: Using Python to add thumbnails to Explorer References: Message-ID: <1130955820_251@spool6-east.superfeed.net> Not sure how ctypes works, but with Pywin32 Pythoncom24.dll is actually registered as the shell extension dll, and it passes calls to methods of a Python class you create that implements the interface methods. Roger "c d saunter" wrote in message news:dkabqu$osi$1 at heffalump.dur.ac.uk... > John J. Lee (jjl at pobox.com) wrote: > > : "Roger Upole" writes: > > : Or, if not, then you can do it with module ctypes. > > : http://starship.python.net/crew/theller/ctypes/ > > : There's an O'Reilly book called something like "win32 shell > : programming" that covers this stuff. > > : John > > Roger & John - thanks for the info. Unless I'm wrong (a distinct > posibility) this isn't an option, as all though COM is used as the > interface, it is used to talk to *in process* code loaded from a DLL - so > Python can only be used if the interpreter is invoked from within a custom > shell extension .dll, which is probably not the best idea for various > reasons. > > Thanks, > Chris ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-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 bokr at oz.net Fri Nov 4 20:43:29 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 05 Nov 2005 01:43:29 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <871x1wu3sl.fsf@keizer.soze.com> Message-ID: <436c0d0e.148105494@news.oz.net> On 04 Nov 2005 11:04:58 +0100, Stefan Arentz wrote: >Antoon Pardon writes: > >> Op 2005-11-03, Mike Meyer schreef : >> > Antoon Pardon writes: >> >>> What would you expect to get if you wrote b.a = b.a + 2? >> >> I would expect a result consistent with the fact that both times >> >> b.a would refer to the same object. >> > >> > Except they *don't*. This happens in any language that resolves >> > references at run time. >> >> Python doesn't resolve references at run time. If it did the following >> should work. >> >> a = 1 >> def f(): >> a = a + 1 >> >> f() > >No that has nothing to do with resolving things at runtime. Your example >does not work because the language is very specific about looking up >global variables. Your programming error, not Python's shortcoming. > If someone has an old version of Python handy, I suspect that it used to "work", and the "a" on the right hand side was the global "a" because a local "a" hadn't been defined until the assignment, which worked to produce a local binding of "a". Personally, I like that better than the current way, because it follows the order of accesses implied by the precedences in expression evaluation and statement execution. But maybe I don't RC ;-) Regards, Bengt Richter From bokr at oz.net Wed Nov 2 15:43:34 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 02 Nov 2005 20:43:34 GMT Subject: Hexadecimal Conversion in Python References: <1130963306.183112.3720@g49g2000cwa.googlegroups.com> <1130963890.241985.268920@g14g2000cwa.googlegroups.com> <1130964825.322352.138330@f14g2000cwb.googlegroups.com> Message-ID: <43691f60.1643752981@news.oz.net> On 2 Nov 2005 12:53:45 -0800, "DaBeef" wrote: >I have been coding for 5 years. This is a proprietary protocol, so it >is difficult converting. I did this in java but was just able to >convert a stream. I looked through the Python library, I am more or >less getting backa string represented as a "...." So now I want to >convert it to all the hexa, bin until I see a match and can then work >teh rest of my program > Maybe the binascii module's hexlify will get you into territory more familiar to you? Python generally stores byte data as type str "strings." If you want to see the bytes as hex (a string of hex characters ;-) you can e.g., >>> import binascii >>> binascii.hexlify('ABC123...\x01\x02\x03') '4142433132332e2e2e010203' To convert individual character, you can use a format string on the ordinal value >>> for c in 'ABC123...\x01\x02\x03': print '%02X'%ord(c), ... 41 42 43 31 32 33 2E 2E 2E 01 02 03 Or perhaps you really want the integer ordinal value itself? >>> for c in 'ABC123...\x01\x02\x03': print ord(c), ... 65 66 67 49 50 51 46 46 46 1 2 3 (print obviously does a conversion to decimal string representation for output) If you are interested in the bits, you can check them with bit operations, e.g., >>> for c in 'ABC123...\x01\x02\x03': ... print ''.join(chr(48+((ord(c)>>b)&1)) for b in xrange(7,-1,- 1)), ... 01000001 01000010 01000011 00110001 00110010 00110011 00101110 00101110 00101110 00000001 00000010 00000011 (cf. 41 42 42 etc above) Regards, Bengt Richter From mensanator at aol.com Tue Nov 22 18:33:26 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 22 Nov 2005 15:33:26 -0800 Subject: hex string to hex value In-Reply-To: <1132701750.841307.97890@g14g2000cwa.googlegroups.com> References: <1132701750.841307.97890@g14g2000cwa.googlegroups.com> Message-ID: <1132702406.174338.169690@g44g2000cwa.googlegroups.com> avnit wrote: > If you just want to convert a string to an integer, it would be: > > >>> int(n) That's what the OP tried and it didn't work. BECAUSE you have to tell the int function what base the string is in (even though it has "0x" at the start). >>> int(n,16) 66 > > in your case it would be: > > >>> m=66 > >>> n=int(hex(m)) Wrong again, you still have to tell it what base. >>> h=int(hex(m),16) >>> h 66 From bokr at oz.net Sun Nov 13 16:44:43 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 13 Nov 2005 21:44:43 GMT Subject: Iterator addition References: <7x4q6lm87q.fsf_-_@ruckus.brouhaha.com> <1h5s1dp.i6hnk31bmv4xN%aleax@mail.comcast.net> <7xslu5cdhz.fsf@ruckus.brouhaha.com> <1131847923.361393.233530@g47g2000cwa.googlegroups.com> <3tp834FtpasuU1@individual.net> Message-ID: <43779dd3.405009853@news.oz.net> On Sun, 13 Nov 2005 17:31:32 +0100, Reinhold Birkenfeld wrote: >bearophileHUGS at lycos.com wrote: >> Tom Anderson: >>> And we're halfway to looking like perl already! Perhaps a more pythonic >>> thing would be to define a "then" operator: >>> all_lines = file1 then file2 then file3 >> >> Or a "chain" one: >>> all_lines = file1 chain file2 chain file3 > >That's certainly not better than the chain() function. Introducing new operators >for just one application is not pythonic. Agreed. But here's a thought: What if expr1 expr2 were as legal as expr1, expr2 and had well defined meaning? The meaning I have in mind is that expr1 and expr2 (etc if more) should be evaluated just as they are for building a tuple. Then, instead of taking the values on the stack and building the tuple, the whole sequence is evaluated by looking for three possible methods on the objects. First, a __unaryop__ method is sought. If present, that is sufficient to evaluate expr1 expr2 as expr1.__unaryop__(expr2) Now that effectively becomes the first element replacing the first two elements of the sequence. If it is the only element, that is the value of the whole. If there are more elements, we start as if with a new sequence, so expr1 expr2 expr2 is equivalent to (expr1 expr2 expr3) is equivalent to ((expr1 expr2) expr3) so we evaluate (expr1 expr2).__unaryop__(expr3) if that __unaryop__ exists. If not, we look for a postfix unary op method on expr3 and if present, we get expr3.__pfunaryop__((expr1 expr2)) as the value of the whole. Or to write it out fully, expr3.__pfunaryop__(expr1.__unaryop__(expr2)) Now if expr1 had no op method, we would look for __pfunaryop__ on expr2 and if found the value would obviously be expr2.__pfunaryop__(expr1) If there is no __pfunaryop__ on expr2, we look for a __binaryop__ method, (BTW meaning unary ops are given precedence). If we have expr2.__binaryop__, then we need an expr3, or it is an error. If present, we get a value for expr1 expr2 expr3 that is expr2.__binaryop__(expr1, expr3) Now if e.g. a bare-name expression MINUS is bound to an object that has both a __unaryop__ and a __binaryop__ method, parens can as usual control the evaluation. E.g., MINUS a MINUS b evaluates to MINUS.__binaryop__(MINUS.__unaryop__(a), b) whereas MINUS (a MINUS b) evaluates to MINUS.__unaryop__(MINUS.__binaryop__(a, b)) Presumably the byte codes for the above would look something like (faked!! minor revision of tuple-building code ;-) >>> dis.dis(compile('MINUS a MINUS b','','eval')) 0 0 LOAD_NAME 0 (MINUS) 3 LOAD_NAME 1 (a) 6 LOAD_NAME 0 (MINUS) 9 LOAD_NAME 2 (b) 12 EVAL_EXPR_SEQ 4 15 RETURN_VALUE >>> dis.dis(compile('MINUS (a MINUS b)','','eval')) 0 0 LOAD_NAME 0 (MINUS) 3 LOAD_NAME 1 (a) 6 LOAD_NAME 0 (MINUS) 9 LOAD_NAME 2 (b) 12 EVAL_EXPR_SEQ 3 15 EVAL_EXPR_SEQ 2 18 RETURN_VALUE I think this might have some interesting possibilities ;-) I'm sure there can be some interesting ambiguities in the syntax of adjacent blank-separated expressions, but nothing parens couldn't overcome, IWT. Built-in operators with symbols such as +, -, *, / etc. would of course not be treated as as objects in the above sense. I.e., even if expr1 had a __unaryop__ method, expr1 - expr2 could not become expr1.__unaryop__(-expr2) unless you forced the issue with expr1 (-expr2) Ok, this should be fun ;-) Regards, Bengt Richter From bonono at gmail.com Thu Nov 10 11:19:36 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 08:19:36 -0800 Subject: Addressing the last element of a list In-Reply-To: <1131639368.806010.76080@o13g2000cwo.googlegroups.com> References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> Message-ID: <1131639576.624736.32800@z14g2000cwz.googlegroups.com> This mutable/immutable object and name/variable is confusing. Daniel Crespo wrote: > Well, I hope that newcomers to Python don't confuse himselves :) > > Daniel From steve at holdenweb.com Sun Nov 6 12:54:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 06 Nov 2005 17:54:23 +0000 Subject: mod_python In-Reply-To: References: <1131231120.914632.17790@g44g2000cwa.googlegroups.com> <1131249790.713791.186740@g14g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: [...] > > The second error message seems to imply that the database InventoryList > table doesn't have a column called "article". > > regards > Steve ^article^artist^ -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From mwm at mired.org Wed Nov 16 23:44:30 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 16 Nov 2005 23:44:30 -0500 Subject: python-mysqldb__debian_to_freebsd References: <1132181273_661@spool6-east.superfeed.net> Message-ID: <8664qropch.fsf@bhuda.mired.org> Damjan writes: >> Is there any at all chance that this will work >> with the proper configs or should I go ahead >> and beg the host for an installation ? > It seems to me very unlikely that a program compiled for FreeBSD would link > to a library compiled for Debian Linux which in turn was linked to a Debian > libmysql but now has to work with the FreeBSD libmysql... I just don't > beleive you can make this work. Arrgh. Damjan, you *really* should have left enough context for those reading what you have to say to figure out what that "this" was. I have as yet to see the original on my news server, so I chased it down on Google groups. For the interested, the OP (Stanley Kitching), wants to use a python-mysqldb module on his web host running FreeBSD. They don't have the that installed, so he tried getting the Debian binary distrubtion of the library to work, and failed. He's wondering if this is at all possible. Answer: yes, it might (key word - might) be made to work. Linux shared libraries have been made to work with native applications on FreeBSD before. I don't have the details, but would expect you'd have to install large chunks of a Debian system to make this work. If you really want to do this, let me know and I'll chase the details down for you. However, that's the wrong way to do this. First step - ask your hosting service to install databases/py-MySQLdb. That's the Python MySQLdb port in the FreeBSD ports tree. Installing it should be trivial. If they won't, I'd seriously consider changing services. I can recommend a FreeBSD-based hosting service that will install pretty much anything in the ports tree. The next thing to try is getting the MySQLdb pkg for FreeBSD. A pkg is the format that FreeBSD uses for binary distributions. Look in ftp://ftp.freebsd.org/pub/FreeBSD/ports//packages-/databases. Supported architectures are alpha, amd64, i386, ia64 and sparc64. Supported releases (for i386, anyway) include the last release version of FreeBSD 4, 5 and 6, the stable branch of 4 and 6, the development and stable branches of 5, and 7-current. Most of those should be for Python 2.4. The one I checked had MySQLdb 1.2.0 and 1.2.1c3 (a development branch). If that fails (because they don't have a binary for the right combination of OS and Python), get the version of the os (use the command "uname -pr") and the version of Python, and ask here and on questions at freebsd.org to see if someone with an appropriate installation will build you a binary. I'll do it if I have the appropriate version of FreeBSD installed. Or install FreeBSD on a spare system and build it yourself - once you get FreeBSD installed, the rest is trivial, and I'll be glad to provide pointers for that. If all that fails, *then* it's time to look into getting the debian version of the library to work. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mwm at mired.org Sun Nov 27 21:38:33 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 27 Nov 2005 21:38:33 -0500 Subject: New docs for set elements/dictionary keys References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> <863bljf1o8.fsf@bhuda.mired.org> <4388f6ce$0$22897$9b622d9e@news.freenet.de> <86mzjqew8l.fsf_-_@bhuda.mired.org> <43896474$0$22007$9b622d9e@news.freenet.de> <86k6etd8p2.fsf@bhuda.mired.org> <438A3896.7020501@v.loewis.de> Message-ID: <86wtitbiom.fsf@bhuda.mired.org> "Martin v. L?wis" writes: > Me, personally, I had your definition in mind: hashable should indicate > "returns a value constant over time and consistent with comparison". > > I suggested that most people would consider "hashable" to mean: > hash() returns a value. To those people, it is a minor detail whether > you get the fallback implementation of hash() or whether there is a > default __hash__ implementation for all objects that don't otherwise > define __hash__. True. I think we ought to leave the behavioral requirements up to the __hash__ docs, as it's already there. We can use hashable that way, and maybe define it by implication: Any object for which hash() returns an appropriate value(1) can be used as a dictionary key/set element. Lists, sets and dicts are not hashable, and can not be used. Tuples can be used if all the things they contain are hashable. instances of all other builin types can be used. Instances of most classes written in Python can be used(2). 1) See the __hash__ documentation for details on what an approriate value is. 2) Instances that have a __hash__ method that returns an appropriate value can be used. Instances that don't have a __cmp__ or an __eq__ method can be used even if they don't have a __hash__ method. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From spamproof at walla.com Thu Nov 17 16:00:04 2005 From: spamproof at walla.com (=?UTF-8?Q?=4A=6F=68=6E=20=44=6F=65?=) Date: Thu, 17 Nov 2005 23:00:04 +0200 Subject: =?UTF-8?Q?=4E=65=77=62=69=65=20=71=75=65=73=74=69=6F=6E=3A=20=64=6F=65=73=20=66=69=6C=65=28=22=74=65=78=74=2E=74=78=74=27=2C=20=22=77=22=29=2E=77=72=69=74=65=28=22=73=74=75=66=66=22=29=20=65=76=65=72=20=67=65=74=20=63=6C=6F=73=65=64=3F?= Message-ID: <1132261192.858000-81686986-16815@walla.com> An HTML attachment was scrubbed... URL: From norman at littletank.org Sun Nov 6 17:30:30 2005 From: norman at littletank.org (Norman Silverstone) Date: Sun, 06 Nov 2005 22:30:30 +0000 Subject: Using Which Version of Linux References: <1131309594.772570.44120@f14g2000cwb.googlegroups.com> Message-ID: On Sun, 06 Nov 2005 12:39:54 -0800, Steve M wrote: > > Max wrote: > >> (Mark Shuttleworth, ... >> really loves Python - he gave me quite a lot of money for using it). > > Please elaborate. Mark Shuttleworth is a very wealthy man who is supporting the development of Ubuntu. His wealth came from Linux and Python I believe. He was the second civilian to visit the International Space Station, travelling on a Russian Soyuz, for which he paid 20 million American dollars. If you want to know more look at the Ubuntu web site or, if you wish, I may be able to find you some more references. Norman From lists at andreas-jung.com Wed Nov 2 11:32:23 2005 From: lists at andreas-jung.com (Andreas Jung) Date: Wed, 02 Nov 2005 17:32:23 +0100 Subject: [Subprocess/Windows] subprocess module under Windows 98 Message-ID: Hi, I am using subprocess.Popen() to start Java processes (converters) from within Zope under Windows 98 (sorry, we have to support the platform). The call looks like this: P = Popen('java.exe arguments...', stdout=PIPE, stderr=PIPE, stdin=open('nul:')). stdin=open('nul:') is required to make Popen() actually running under Windows 98 (stdin=None works fine on XP). However for every Popen() call Windows 98 opens an empty DOS box that disappear after completion of the converter process. The Popen() has some 'startupinfo' and 'creationflags' attributes but I could not find any documentation. Is there a way to suppress the DOS boxes somehow using these attributes or is there another way to get rid of them? Thanks in advance, Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From bokr at oz.net Sun Nov 13 18:12:51 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 13 Nov 2005 23:12:51 GMT Subject: Multikey Dict? References: <437682b5$0$2108$edfadb0f@dtext02.news.tele.dk> Message-ID: <4377bc89.412871607@news.oz.net> On Sun, 13 Nov 2005 01:03:05 +0100, David Rasmussen wrote: >If I have a collection of dicts like: > >john = {'id': 1, 'name': "John Cleese", 'year': 1939} >graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} > Why do you use dicts for what looks like fixed-format records? Why not just tuples? E.g., john = (1, "John Cleese", 1939) graham = (2, "Graham Chapman", 1941) >I could store all of them in a list. But for easy lookup, I might store >all these in a dict instead, like > >people = {'1': john, '2': graham} > >or maybe > >people = {'John Cleese': john, 'Graham Chapman': graham} > >or whatever key I might choose. Now, first of all, it seems a bit >annoying that I have to keep that redundant data in the second dict that ISTM you are confusing equivalent references with redundant data. The people dict does not "contain" its own copy of john and graham objects, it just refers to them, and you get to look up the reference by key name. >is already in the individual dicts within people. Secondly (and this is >my question), it is annoying that I have to choose one of several >unambiguous keys as a key. Keys in the same dict have to be unambiguous, or how could you retrieve an associated value? > >I would like to be able to say: > >people['1'].year > >in some case and in other cases I want to say > >people['John Cleese'].year > >That is, sometimes I have the name at hand and would like to look up >data based on that. Other times, I have the ID at hand and would like to >look up data based on that instead. No prob. So long as no one has a name like '1' or an id like 'John Cleese' you can keep both '1':john and 'John Cleese':john key:value associations in the same dict. Referring to the same value with different keys is no prob. Of course, using tuples for john and graham you can't get year as an attribute. Recalling from above john = (1, "John Cleese", 1939) you'd have to write people['1'][2] or people['John Cleese'][2] Or you could define some handy mnemonic constants to match the tuple, e.g., ID, NAME, YEAR = range(3) and then you could write people['1'][YEAR] or people['John Cleese'][YEAR] Or you could define an object giving you the attribute access you wanted. Not as efficient spacewise though, unless you define __slots__. Of course, you can use dicts for john and graham if you need the ability to add arbitrary fields. If this happens rarely, you could conceivably gain efficiency in storage by using slots for the normal data and a single slot initialized to None for extra data, and then create a dict for that slot only if you need to extend with new field names. > >Also, I would like if I didn't have to keep the key data both in the >dict of dicts and in the dicts :) IIUC I guess you don't have to. > >If I could just say to Python: john and graham (and ...) are all a part >of a "superdict" and either their id or their name can be used as keys. > >Can I do that somehow? Sure. What API would you like for your superdict? Defining requirements is usually the hardest part, because newbies often imagine limitations that don't exist in Python ;-) Others will have proposed many variants by now, I assume ;-) Regards, Bengt Richter From tdwdotnet at gmail.com Fri Nov 25 19:51:11 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Sat, 26 Nov 2005 00:51:11 +0000 Subject: [Forged?] Re: How to find the port a server is listening on (from within the server) In-Reply-To: References: <9afea2ac0511251433o5a93718ci@mail.gmail.com> Message-ID: <9afea2ac0511251651q4d3bbe62l@mail.gmail.com> On 26/11/05, jepler at unpythonic.net wrote: > > > > If I understand correctly, you're looking for the socket method > getsockname(), documented at > http://docs.python.org/lib/socket-objects.html > > Jeff > > Many thanks Jeff, self.server.socket.getsockname() did the trick. -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From cito at online.de Fri Nov 25 04:02:25 2005 From: cito at online.de (Christoph Zwerschke) Date: Fri, 25 Nov 2005 10:02:25 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <1132900750.956510.16320@o13g2000cwo.googlegroups.com> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <1132900750.956510.16320@o13g2000cwo.googlegroups.com> Message-ID: bonono at gmail.com schrieb: > And this, again from the doc(about mapping objects): > A mapping object maps immutable values to arbitrary objects. > Seems that is questionable too. > a=(1,[]) > d={} > d[a]=1 > again would give TypeError, list object are unhashable. That's a good example showing that the term 'mutable' is not so well-defined as it may seem. If you set b=[]; a=(1,b); should a be considered mutable (because you can change its value by changing b), or should it be considered immutable (because it is a tuple)? -- Christoph From blahman Wed Nov 2 06:18:28 2005 From: blahman (blah@blah.blah) Date: Wed, 02 Nov 2005 05:18:28 -0600 Subject: About the Python Expert Message-ID: Hey, i didnt say i need an expert. wel i did... anyways, i m just saying that Fan is not a good python programmer, he doesnt know enough python to help those who have joined his group, i know its askin a lot, and i m not askin for a private tutor, just someone(s), to pop into the group, see the discussions and help the people. but it is ur decision. -- * Posted with NewsLeecher v3.0 Beta 7 * http://www.newsleecher.com/?usenet From steve at holdenweb.com Tue Nov 22 13:38:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 22 Nov 2005 18:38:15 +0000 Subject: Hot to split string literals that will across two or more lines ? In-Reply-To: References: Message-ID: <43836597.6040607@holdenweb.com> Paul McGuire wrote: > "Ben Finney" wrote in message > news:dljic3$rpv$1 at rose.polar.local... > >>Xiao Jianfeng wrote: >> >>>I need to print a long sting, which is two long so it must expand >>>two lines. >> >>How is this string being constructed in the source? If it exists as a >>single long string, why must it be so long? >> >>Some techniques you may not be aware of: >> >> >>> chunks = ["abc", "def", "ghi"] >> >>> s = ''.join(chunks) >> >>> print s >> abcdefghi >> >> >>> s = "#" * 10 >> >>> print s >> ########## >> >>You can, of course, modify the above so that they join or multiply to >>create much longer strings. >> >>-- >> \ "Everything is futile." -- Marvin of Borg | >> `\ | >>_o__) | >>Ben Finney > > > Or for a large literal string: > > """ > lots of text hundreds of characters long > more text on another line but we really don't want any line breaks > in our final string > so we replace newlines in this multiline string > with an empty string thus > """.replace('\n','') > Of course there's also the alternative of escaping the newlines out in the literal. The replace result above is exactly """\ lots of text hundreds of characters long\ more text on another line but we really don't want any line breaks\ in our final string\ so we replace newlines in this multiline string\ with an empty string thus\ """ 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 rpdooling at gmail.com Fri Nov 25 06:36:34 2005 From: rpdooling at gmail.com (BartlebyScrivener) Date: 25 Nov 2005 03:36:34 -0800 Subject: Python book for a non-programmer In-Reply-To: References: Message-ID: <1132918594.675130.206660@f14g2000cwb.googlegroups.com> Simon Brunning wrote: > I have a non-programming friend who wants to learn Python. It's been > so long since I've been in her shoes that I don't feel qualified to > judge the books aimed at people in her situation. I know of two such > books: > > > > > Any recommendations, or otherwise? > > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ If you want real (dead-tree) books, you will find Chris Fehily's Visual Quickstart Guide recommended by others here (though it's ageing - 2002). I'm about 2/3 through and it's been great for me: http://www.amazon.com/exec/obidos/asin/0201748843/richarddooling/ And a brand new one which I just ordered: Beginning Python (Programmer To Programmer) which despite the title has a great intro to programming before it quickly accelerates: http://www.amazon.com/exec/obidos/asin/0764596543/richarddooling/ Cheers, bs From pmartin at snakecard.com Tue Nov 22 09:17:57 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Tue, 22 Nov 2005 08:17:57 -0600 Subject: Python install minimum requirements References: <0zsgf.12765$ih5.9671@dukeread11> Message-ID: Thanks I'll take a look. PS: www.u3.com Regards, Philippe jepler at unpythonic.net wrote: > If I found the right "U3" when I googled, then maybe this is relevant: > http://www.voidspace.org.uk/python/movpy/ > > Jeff From fumanchu at amor.org Wed Nov 16 12:53:16 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 16 Nov 2005 09:53:16 -0800 Subject: Reinvent no more forever Message-ID: Ben Finney wrote: > I hold up all existing public source code repositories as evidence > against your prediction. Reinventing the wheel is distressingly > common, and a dependency tool isn't going to stop that. Is there ever a point at which one decides that "unusable dependency tools" are distressingly common, and cost more than reinvention? Robert Brewer System Architect Amor Ministries fumanchu at amor.org From mwm at mired.org Thu Nov 10 23:20:42 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 23:20:42 -0500 Subject: Abstract Base Classes References: Message-ID: <861x1n6cit.fsf@bhuda.mired.org> Ben Finney writes: > I've tried doing this in the __init__(): > > class FooException(Exception): > """ Base class for all FooModule exceptions """ > def __init__(self): > raise NotImplementedError, \ > "%s is an abstract class for exceptions" % self.__class__ > > When I use this, I discovered to my horror that the subclasses were > calling FooException.__init__ -- which I though wasn't supposed to > happen in Python! > It's also rather semantically weird, to my eye. Calling __init__ is handled just like any other method (this is a good thing), so if your subclasses fail to define __init__, the version in the superclass gets called. If it were otherwise, every class would have to declare __init__ just to call super(cls, self).__init__. > Can I do something tricky with checking base classes in the > FooException.__init__() ? Untested: class FooException(Exception): def __init__(self): if self.__class__ == FooException: raise NotImplementedError, "FooException is an abstract class for exceptions" Personally, I find this unpythonic. FooException doesn't contribute anything, and has no real reason for existing. If Python did static type checking, it would make sense, but python doesn't, so it doesn't. If you hadn't referenced interfaces, I'd suspect you might be planing on catching all FooExceptions in a try:/except:. I'm not sure you'll be able to list an interace in an except clause when they come to exist, though. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tdwdotnet at gmail.com Wed Nov 2 13:23:33 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Wed, 2 Nov 2005 18:23:33 +0000 Subject: Spambayes modifications with web services In-Reply-To: References: <1130486425.402338.123720@g49g2000cwa.googlegroups.com> <1130939781.817460.142120@g49g2000cwa.googlegroups.com> Message-ID: <9afea2ac0511021023x68f1a0e4h@mail.gmail.com> On 02/11/05, Steve Holden wrote: > Personally I didn't regard the reply as unhelpful, and I believe the > replier was honestly trying to get you to see that your rather naive > suggestion was most unlikely to make things better. > To the OP A tip for curing your own problem - remove your catchall. Only allow incoming email and bounces to valid in-use addresses - not to an infinite number of unused addresses. Repeat after me "Catchalls are lazy !!! " :) Catchalls are a spammer's best friend and contribute greatly to the internet's spam problem AND to the increasingly harsh attempts by ISPs and other mail providers to reduce their load and spam throughput. Not to mention the slow lingering death of services that provide a catchall that can be forwarded. You used a real domain name in your original post !! Anyone marking your post as spam using your criteria would have blacklisted that unfortunate domain. HTH :) From keesvanschaik at gmail.com Tue Nov 1 18:12:26 2005 From: keesvanschaik at gmail.com (KvS) Date: 1 Nov 2005 15:12:26 -0800 Subject: wxPython: updating style of StaticText from event generated by button Message-ID: <1130886746.328723.109570@f14g2000cwb.googlegroups.com> Hi all, I'm pretty new to (wx)Python so plz. don't shoot me if I've missed something obvious ;). I have a panel inside a frame, on which a Button and a StaticText is placed: self.panel = wx.Panel(self,-1) self.button = wx.Button(self.panel,-1,"Klikkerdeklik") self.button.SetPosition((200,40)) self.Bind(wx.EVT_BUTTON, self.VeranderLabel, self.button) self.text1 = wx.StaticText(self.panel, -1, "Dikke Henk en gekke Greetje", size=(100,50), pos=(15,20), style=wx.RAISED_BORDER) and via the even handler I try to give StaticText a different style: def VeranderLabel(self, event): if self.text1.GetWindowStyle() == wx.SUNKEN_BORDER: self.text1.SetWindowStyle(wx.RAISED_BORDER) self.text1.Refresh() self.text1.Update() else: self.text1.SetWindowStyle(wx.SUNKEN_BORDER) self.text1.Refresh() self.text1.Update() Although the style is indeed updated (checked by printing style to console) the appearance of the StaticText stays the same. What am I missing here? Thanks in advance. - Kees From luca.tavoletti at gmail.com Tue Nov 15 13:46:48 2005 From: luca.tavoletti at gmail.com (lux) Date: 15 Nov 2005 10:46:48 -0800 Subject: python and VisualFox dbf Message-ID: <1132080408.157794.129920@g14g2000cwa.googlegroups.com> Hi, I've a dfb written in VisualFox, I need to send a "pack" and "reindex" but in odbc is not supported... Anybody know how to do this? TIA, Luca From mwm at mired.org Thu Nov 3 15:52:47 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 03 Nov 2005 15:52:47 -0500 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <1131049615.656278.24270@g47g2000cwa.googlegroups.com> Message-ID: <864q6tihcw.fsf@bhuda.mired.org> "Graham" writes: > I just seems to me that . shouldn't defer to the class > variable if > an instance variable of the same name does not exists, it should, at > least how i > understand it raise an exception. > > Is my thinking way off here? Yes. This behavior is how you get inheritted access to class variables. Consider: class Counter(object): "A mutable counter." # implementation elided class A(object): instance_count = Counter() def __init__(self): self.instance_count.increment() class B(A): instance_count = Counter() This is sufficient to count instances of A and B. If self.instance_count raised an exception, you'd have to do something like A.instance_count in A.__init__, which would mean the __init__ B inherited from A would do the wrong thing. Currently, you can either reference class variables by explicit class, or via inheritance, and both behaviors are desirable. If you're going to disallow self.class_variable, you need to come up with a mechanism to replace the latter behavior. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fredrik at pythonware.com Tue Nov 15 17:40:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Nov 2005 23:40:54 +0100 Subject: Configure failing why? References: Message-ID: Samuel M. Smith wrote: >I am trying to build python2.4.2 on an arm 9 running Debian 3 Sarge > configure:1842: ./a.out > ./configure: line 1: ./a.out: Permission denied > configure:1845: $? = 126 > configure:1854: error: cannot run C++ compiled programs. > If you meant to cross compile, use `--host'. > See `config.log' for more details. > > It appears that for some reason the a.out file that the configure > script is making is not getting execute permissions enable by the > configure script on a sane standard Unixoid system, the compiler is required to set the following permission flags S_IRWXO | S_IRWXG | S_IRWXU if and only if the program was successfully compiled and linked. what happens if you do $ cat >foo.cpp int main(){ return 0; } $ c++ foo.cpp $ ls -l a.out ? From msoulier at digitaltorque.ca Sun Nov 6 09:40:22 2005 From: msoulier at digitaltorque.ca (Michael P. Soulier) Date: Sun, 6 Nov 2005 09:40:22 -0500 Subject: Can't instantiate class In-Reply-To: <436E124B.7000003@dbmdata.com> References: <436E124B.7000003@dbmdata.com> Message-ID: On 11/6/05, David Mitchell wrote: > import DataUtil > > File "C:\Apache2\htdocs\Intranet\addLink.py", line 42, in getCategories > db = DataUtil() > > TypeError: 'module' object is not callable You've imported module DataUtil, and by calling DataUtil(), you're trying to call the module, hence the error. I think you want db = DataUtil.DataUtil() Or, from DataUtil import DataUtil And then your code will work. Mike -- Michael P. Soulier From lycka at carmen.se Thu Nov 3 12:45:37 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 03 Nov 2005 18:45:37 +0100 Subject: Learning multiple languages (question for general discussion) In-Reply-To: References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: > LOL. As weird as it sounds, that's what I *don't* want to happen with > C#! I've spent a lot of time with it, and I love it, but I don't want > Python to take over! :) Then it might be better to keep away from Python. It *will* spoil you. Python is a good team player. It's excellent to use in large projects where different languages fit better for different parts of the final system,and it's excellent as a programmers tool even if all production code is written in C# or whatever. Given a free choice, you'll probably shift more and more of the code to Python though,since it's faster to write and easier to maintain that way. From jeff at schwabcenter.com Mon Nov 21 08:27:16 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Mon, 21 Nov 2005 13:27:16 GMT Subject: ownership problem? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Jeffrey Schwab wrote: > > >>>the problem isn't determining who owns it, the problem is determining >>>who's supposed to release it. that's not a very common problem in a >>>garbage-collected language... >> >>Yes it is. Memory is only one type of resource. > > > Python's garbage collector deals with objects, not memory. But you don't want to spin and wait for the garbage collector to release the object that happens to be holding a thread lock... >>I am not a Python Guru > > > from the sound of it, you haven't written serious programs in any of the > languages you mention. You would be wrong there. :) From robert.kern at gmail.com Wed Nov 2 18:34:47 2005 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 02 Nov 2005 15:34:47 -0800 Subject: lists <-> tuple In-Reply-To: References: Message-ID: Peter Notebaert wrote: > I am new to Python and have to create an import library in C that uses > matrices. > > These matrices can be one-dimensional (vectors) or two-dimensional. If I > look in the ActivePython 2.4 documentation at data structures, then I see at > least 2 posibilities to represent them: Lists and Tuples. > > The documention doesn't give me much information on what the best choice is > for the data type to provide/return these matrices. > > So my question is, should I use lists or tuples to represent my matrices in > and why? You'll probably want to use scipy_core. It's a package designed specifically to deal with multidimensional arrays of homogeneous, (usually) numeric data. http://numeric.scipy.org -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fredrik at pythonware.com Thu Nov 24 05:07:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Nov 2005 11:07:07 +0100 Subject: Why is dictionary.keys() a list and not a set? References: <1132820426.374743.51410@g49g2000cwa.googlegroups.com> <1132823626.230657.56570@g44g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > > creates just over one million objects. In your "equivalent" example, > > you're calling d.items() twice to produce two million objects, none > > of which you really care about. > > This is what I get from the doc : > a.items() a copy of a's list of (key, value) pairs (3) > a.keys() a copy of a's list of keys (3) > a.values() a copy of a's list of values > > I can't derive what you mean by "two list objects" vs "million > objects". The "copy of a's list of" is a list object. The "pairs" are tuples, which are objects too. For a dictionary with one million items, the "items" method has to create one million "pair" tuples before it can return them to you... (the difference between "items" and "iteritems" is that the latter doesn't create all of them up front; it still has to create them, though). In Python, everything that you can put in a variable or otherwise save for a later time is an object. All objects must be created. Creating a new object is often very cheap, but the cost is never zero. From dcrespo at gmail.com Wed Nov 9 07:58:12 2005 From: dcrespo at gmail.com (dcrespo) Date: 9 Nov 2005 04:58:12 -0800 Subject: append to non-existing list In-Reply-To: References: Message-ID: <1131541092.150307.313700@z14g2000cwz.googlegroups.com> Hi I think there's no way to append to a non existing list. Sorry about my question, but the English is my second language, and I don't know what is the meaning of IHMO (or IMHO). I googled and found that it means "In My Humbled Opinion", is that true? Thanks and accept my appologies for not talking entirely about your problem. Daniel From simon.brunning at gmail.com Wed Nov 16 06:28:24 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 16 Nov 2005 11:28:24 +0000 Subject: Can anyone tell me if pygame and Tkinter can work together? In-Reply-To: <437ab8b5$0$20233$88260bb3@news.atlantisnews.com> References: <437ab8b5$0$20233$88260bb3@news.atlantisnews.com> Message-ID: <8c7f10c60511160328x1f86780fn@mail.gmail.com> On 16/11/05, Nathan Pinno wrote: > It worked, but unfornately I can't use this line as it brings up errors: > > from Tkinter (or pygame) import * > > Anyway around this little bug? What's the error? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From skip at pobox.com Fri Nov 11 09:22:52 2005 From: skip at pobox.com (skip at pobox.com) Date: Fri, 11 Nov 2005 08:22:52 -0600 Subject: output buffering In-Reply-To: References: Message-ID: <17268.43324.947998.208056@montanaro.dyndns.org> jd> When reading a large datafile, I want to print a '.' to show the jd> progress. This fails, I get the series of '.'s after the data has jd> been read. Is there a trick to fix this? As Fredrik indicated, you need to flush the output buffer. You might also want to check out the progress module available from my Python Bits page: http://orca.mojam.com/~skip/python/ Skip From steve at REMOVETHIScyber.com.au Thu Nov 10 09:13:15 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 11 Nov 2005 01:13:15 +1100 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> Message-ID: On Thu, 10 Nov 2005 06:47:41 +0000, Donn Cave wrote: > Quoth Steven D'Aprano : > ... > | So when working with ints, strs or other immutable objects, you aren't > | modifying the objects in place, you are rebinding the name to another > | object: > | > | py> spam = "a tasty meat-like food" > | py> alias = spam # both names point to the same str object > | py> spam = "spam spam spam spam" # rebinds name to new str object > | py> print spam, alias > | 'spam spam spam spam' 'a tasty meat-like food' > > The semantics of assignment are like that, period. If the right hand > side is an int, a string, a class instance, a list, whatever, doesn't > matter at all. The question of mutability at this point can be a red > herring for someone who doesn't already understand these matters. Yes, but in the context we were discussing, the original poster was specifically asking to do something that is only possible with mutable objects. He wanted to do something like this: data = [0, None, 2, ["hello"]] ref = data[-1] ref.append("world") and end up with [0, None, 2, ["hello", "world"]]. That will work, because the last item in data is mutable. But this will NOT work: data = [0, None, 2, 0] ref = data[-1] ref = 1 assert data[-1] == 1 because ints are immutable. So the distinction between modifying a mutable object in place and assigning is important. -- Steven. From thorsten at thorstenkampe.de Tue Nov 1 04:40:24 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 1 Nov 2005 09:40:24 +0000 Subject: OpenSSL in Python References: <1130425810.431748.39660@g14g2000cwa.googlegroups.com> <1130808294.188603.169680@g47g2000cwa.googlegroups.com> Message-ID: <1h9eygeghma$.nse7hduxq3j2$.dlg@40tude.net> * dcrespo (2005-11-01 01:24 +0100) > First, is the PYTHON OpenSSL C wrapper what I need to get running. You want to install OpenSSL under Windows. Get a grip: that's not related to Python in any way. > Second, if you don't know how to answer, then limit your opinion to > yourself. You /got/ a sufficient answer. If you had followed Sybren's advice you'd already got a solution... From casevh at comcast.net Wed Nov 9 01:18:32 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 8 Nov 2005 22:18:32 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> In-Reply-To: <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> Message-ID: <1131517112.247477.35030@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > wrote: > > > Everything works fine with v1.16. I'm sure I was doing something wrong. > > I shouldn't be testing that late at night. ;-) > > > > It looks like the warning about "tp_compare" has been fixed. > > I didn't touch tp_compare specifically, so the fix must have been a side > effect (?). > > > > > I will try to build a version for Windows, but that may take me a day > > or two. > > Great, pls let me know when you do (particularly if you're willing to > make your build available to others -- if you send it to me I can make > it downloadable from sourceforge). > > > > Thanks for the updates to gmpy! > > You're welcome, and thank YOU for the feedback &c. > > > Alex I made a successful installer for Windows using Mingw32 and Python 2.4. I needed to edit setup.py to list gmp as a required library. if sys.version.find('MSC')==-1: gmpy_ext = Extension('gmpy', sources=['src/gmpy.c'], # library_dirs=['/usr/local/lib'], libraries=['gmp']) else: gmpy_ext = Extension('gmpy', sources=['src/gmpy.c'], include_dirs=['./src'], libraries=['gmp']) # I added libraries! Will you be updating the information in setup.py file? Tomorrow, I'll recreate my build process on another computer. I am willing to create Windows installers. Which versions of Python do you want to support? Do you want versions that include GMP tailored for specific processors? With GMP 4.1.4 compiled for pentium3, and running on a 1.8Ghz Pentium M, I'm able to calculate the decimal form of 2^25964951 (the 43rd Mersenne prime) in 10 seconds. The prior gmpy release takes just over 14 seconds. Without gmpy, Python takes 25.4 seconds. On an Athlon MP2800+ (2.133Ghz) with GMP compiled for that processor, I can do it in 6.6 seconds using gmpy and 22.4 seconds without gmpy. I'm working with blocks of 1000 digits and using a combination of Toom-Cook and Nussbaumer convolution to perform the multiplies and squares. I did very that the tp_compare errors are fixed. I removed the warnings filter in my code and the warning did occur with the old gmpy but did not occur with my version. Case From lmaycotte at gmail.com Tue Nov 15 17:06:17 2005 From: lmaycotte at gmail.com (lmaycotte at gmail.com) Date: 15 Nov 2005 14:06:17 -0800 Subject: is parameter an iterable? In-Reply-To: <8dgkn1d8k28ibttdfoe3b5c392gi36uijn@4ax.com> References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> <8dgkn1d8k28ibttdfoe3b5c392gi36uijn@4ax.com> Message-ID: <1132092377.695554.117840@g49g2000cwa.googlegroups.com> Maybe this helps: >>> import types >>> def foo(inputVal): inValType = type(inputVal) if inValType==types.ListType or inValType==types.TupleType: for val in inputVal: print val else: print 'Wrong input Type' >>> list = [1,2,3,4] >>> foo(list) 1 2 3 4 >>> tup = ('a', 'b', 'c') >>> foo(tup) a b c >>> foo(9) Wrong input Type >>> From saint.infidel at gmail.com Thu Nov 3 10:02:03 2005 From: saint.infidel at gmail.com (infidel) Date: 3 Nov 2005 07:02:03 -0800 Subject: Learning multiple languages (question for general discussion) In-Reply-To: References: Message-ID: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> Python has spoiled me. I used to periodically try out new languages just for fun, but since learning Python, it's become a lot less interesting. I find myself preferring to just try new ideas or techniques in Python rather than searching for new languages to dabble in. The last few I've downloaded were, in no particular order: Perl, Ruby, Lisp, Io, and Scheme. I usually get as far as installing the necessary interpreters/compilers and opening up a tutorial or two before I lose interest. From bokr at oz.net Tue Nov 22 15:54:56 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 20:54:56 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> Message-ID: <43837d3d.486161733@news.oz.net> On Tue, 22 Nov 2005 14:28:56 GMT, "David Isaac" wrote: > >"Duncan Booth" wrote in message >news:Xns971671CB0DA43duncanbooth at 127.0.0.1... >> >>> aList = ['a', 1, 'b', 2, 'c', 3] >> >>> it = iter(aList) >> >>> zip(it, it) >> [('a', 1), ('b', 2), ('c', 3)] > >That behavior is currently an accident. >http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1121416 >Alan Isaac > That says """ ii. The other problem is easier to explain by example. Let it=iter([1,2,3,4]). What is the result of zip(*[it]*2)? The current answer is: [(1,2),(3,4)], but it is impossible to determine this from the docs, which would allow [(1,3),(2,4)] instead (or indeed other possibilities). """ IMO left->right is useful enough to warrant making it defined behaviour, not an accident. Isn't it(),it() well defined for a given iterator? So is the question whether zip will access its referenced input iterators in some peculiar order? Is the order of zip(a,b) accesses to a and b undefined? If, so, IMO it's reasonable to make it defined as if >>> def zip(*args): ... return list(tuple([it.next() for it in its]) ... for its in [[iter(a) for a in args]] ... for _ in iter(lambda:0,1)) ... >>> aList = ['a', 1, 'b', 2, 'c', 3] >>> it = iter(aList) >>> zip(it, it) [('a', 1), ('b', 2), ('c', 3)] >>> it = iter(aList) >>> zip(it, it, it) [('a', 1, 'b'), (2, 'c', 3)] >>> it = iter(aList) >>> zip(it) [('a',), (1,), ('b',), (2,), ('c',), (3,)] >>> zip(range(3), range(4)) [(0, 0), (1, 1), (2, 2)] >>> zip(range(4), range(3)) [ (0, 0), (1, 1), (2, 2)] (I just hacked this out, so maybe it's not bullet-proof, but the point is, I think there's no reason not to define the behaviour of zip to cycle through its arguments in the intuitive way). Regards, Bengt Richter From mwm at mired.org Mon Nov 28 15:53:38 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 28 Nov 2005 15:53:38 -0500 Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: <8664qcv6i5.fsf@bhuda.mired.org> Peter Hansen writes: > Mike Meyer wrote: >> It seems that the distinction between tuples and lists has slowly been >> fading away. What we call "tuple unpacking" works fine with lists on >> either side of the assignment, and iterators on the values side. IIRC, >> "apply" used to require that the second argument be a tuple; it now >> accepts sequences, and has been depreciated in favor of *args, which >> accepts not only sequences but iterators. >> Is there any place in the language that still requires tuples instead >> of sequences, except for use as dictionary keys? > Would it be possible to optimize your "frozenlist" so that the objects > would be created during compilation time and rather than only during > runtime? If not then tuples() have a distinct performance advantage > in code like the following where they are used as local constants: No, because I want to change the definition. Tuples have the problem that they are immutable, except when they're not (or for proper values of immutable, your choice). They're hashable, except when they're not. Or equivalently, they can be used as dictionary keys - or set elements - except when they can't. I want frozenlists to *not* be that way. A frozenlist should *always* be valid as a dictionary key. This changes the semantics significantly - and means that creating a frozenlist from a list could be very expensive. Doing this requires extending the "frozen" concept, adding two new types, a new magic method, and maybe a new builtin function. Right now, a "frozenset" is always valid as a dictionary key. The concept extension is to provide facilities to freeze nearly everything. New types: frozenlist: a tuple with count/index methods, and the constraint that all the elements are frozen. frozendict: A dictionary without __setitem__, and with the constraint that all values stored in it are frozen. New magic method: __freeze__(self): returns a frozen version of self. Possibe new builtin: freeze(obj) - returns the frozen form of obj. For lists, it returns the equivalent frozenlist; for a set, it returns the equivalent frozenset. For dicts, it returns the equivalent frozendict. For other built-ins, it returns the original object. For classes written in Python, if the instance has __freeze__, it returns the result of calling that. Otherwise, if the instance has __hash__, or does not have __cmp__ and __eq__ (i.e. - if the class is hashable as is), it returns the instance. If all of that fails, it throws an exception. While not strictly required, it appears to be handy, and it makes thinking about the new types much less simler. You can't always create a frozenlist (or frozendict) at compile time. I.e.: a = [] foo(a) fa = frozenlist([a]) You don't know at compile time what a is going to be. Since you can't change the frozenlist after creation, you have to wait until you know the value of a to create fa. This version is *not* suitable as an alias for tuple. It might work as a replacement for tuple in Py3K, but a number of issues have to be worked out - most notable tuple packing. % on strings is easy - you make it accept either a list or a frozenlist (or, if we're going to change it, maybe an arbitary sequence). But tuple unpacking would need some real work. Do we blow off the comma syntax for creating tuples, and force peole to write real lists? Doesn't seem like a good idea to me. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fredrik at pythonware.com Tue Nov 22 16:34:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 22:34:54 +0100 Subject: Questions on embedding Python References: Message-ID: Kenneth McDonald wrote: > 1) When Python is embedded, is it typically compiled statically into > the program, or provided as a dynamic library? if your application is compatible with the Python (i.e. uses /MD on Windows, etc), using the DLL is a lot easier. > 2) If provided as a dynamic library, does/should Python be recompiled > into a tweaked dynamic library, or do we just use the python > executable 'straight up', so to speak. the DLL, yes. if you're embedding, your application will take over the role of python.exe. > 3) We would of course want to make sure that 'our' Python (so to > speak) would have access only to 'our' library of Python code (which > would include most of the standard Python libraries), so that it > can't be confused by the presence of some other version of Python on > the system. Is this normally done by compiling in the Python search > path, making it relative to the main application? if you ship the Python DLL with your application, you can easily set things up so it uses a Python library relative to the DLL (on Windows, use GetModuleFileName to locate your application, extract the dir name, and call Py_SetPythonHome to set PYTHONHOME to your application directory. Python will take care of the rest). if you want to steal some code (windows-specific, but the relevant portions shouldn't be too hard to port), the exemaker sources con- tains a lot of stuff to search for DLL:s, set up paths, control loading of the site module, etc. http://effbot.org/zone/exemaker.htm (if you're really adventurous, turn your entire application into a Python extension, and use an exemaker EXE to start it...) > 4) I've never done this myself, but I understand that Python can > import code from zip files in much the same way that Java can import > from jar files. Is it possible to lump all of the python code we > provide for use with the embedded Python into one big zip file, or > would that cause problems such as slow loading when a module is > imported? This would be nice because the fewer files we distribute, > the better. instead of adding directory "foo" to the path, zip it up, and add the ZIP file to the path. using ZIP files should be more efficient, since Python caches the ZIP directory, and won't have to scan the disk all the time. From robert.kern at gmail.com Tue Nov 8 09:43:51 2005 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 08 Nov 2005 06:43:51 -0800 Subject: any python module to calculate sin, cos, arctan? In-Reply-To: References: Message-ID: Matt Feinstein wrote: > On Tue, 08 Nov 2005 12:30:35 GMT, "Raymond L. Buvel" > wrote: >>http://calcrpnpy.sourceforge.net/clnumManual.html > > Unless you're using Windows. Why? Have you tried compiling it and failed? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From duncan.booth at invalid.invalid Wed Nov 30 03:41:51 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2005 08:41:51 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> <86u0dvowzo.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: >>> An object is compatible with an exception if it is either the object >>> that identifies the exception, or (for exceptions that are classes) >>> it is a base class of the exception, or it is a tuple containing an >>> item that is compatible with the exception. >> >> Requiring a tuple here means that the code doesn't have to worry >> about a possible recursive data structure. > > How so? > > except ExceptType1, (ExceptType2, ExceptType3, (ExceptType4, > ExceptType5): > > I suspect this won't work, but meets the description. > > Lists could be used here with the same restrictions as tuples. I think you meant: except (ExceptType1, (ExceptType2, ExceptType3, (ExceptType4, ExceptType5))): otherwise the first comma separates the exception specification from the target and you get a syntax error even before the syntax error you might expect from the unmatched parentheses. And yes, that works fine. e.g. You can do this: >>> ExcGroup1 = ReferenceError, RuntimeError >>> ExcGroup2 = MemoryError, SyntaxError, ExcGroup1 >>> ExcGroup3 = TypeError, ExcGroup2 >>> try: raise ReferenceError("Hello") except ExcGroup3, e: print "Caught",e Caught Hello >>> ExcGroup3 (, (, , (, ))) >>> The exception tuple has the same sort of nesting as your example, and no matter how deeply nested the system will find the relevant exception. Now consider what happens if you used a list here: >>> ExcGroup1 = [ReferenceError, RuntimeError] >>> ExcGroup2 = MemoryError, SyntaxError, ExcGroup1 >>> ExcGroup3 = TypeError, ExcGroup2 >>> ExcGroup1.append(ExcGroup3) >>> ExcGroup3 (, (, , [, , (, (, , [...]))])) >>> try: raise ReferenceError("Hello") except ExcGroup3, e: print "Caught",e Traceback (most recent call last): File "", line 2, in -toplevel- raise ReferenceError("Hello") ReferenceError: Hello >>> As it currently stands, the exception is not caught because anything in the exception specification which is not a tuple is considered to be a (potential) exception. With lists is suddenly becomes possible to have a recursive data structure. repr goes to a lot of effort to ensure that it can detect the recursion and replace that particular part of the output with ellipses. The exception handling code would have to do something similar if it accepted lists and that would slow down all exception processing. By only traversing inside tuples we can be sure that, even if the data structure as a whole is recursive, the part which is traversed is not. (Note that the repr code also fails to detect the recursive tuple, it isn't until it hits the list a second time that it spots the recursion.) From fernando.lujan at terra.com.br Thu Nov 17 22:13:31 2005 From: fernando.lujan at terra.com.br (Fernando Lujan) Date: Fri, 18 Nov 2005 01:13:31 -0200 Subject: Zope vs Php In-Reply-To: <87hdaa3brc.fsf@jupiter.g2ctech> References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> <86br0in877.fsf@bhuda.mired.org> <87hdaa3brc.fsf@jupiter.g2ctech> Message-ID: <437D46DB.4090004@terra.com.br> Jorge Godoy wrote: >Mike Meyer writes: > > >>That said, I have to confess that lately I've been using Cheetah >>templates, because the syntax for inserting values is simpler, and the >>way Cheetah templates work naturally in the Python inheritance >>hierarchy. >> In this article you will have a great overview about Zope and Zope 3. http://www.zopemag.com/Issue010/Section_Articles/article_WhyZope3.html Fernando Lujan From bhwithun at gmail.com Thu Nov 17 13:56:23 2005 From: bhwithun at gmail.com (Brian Herbert Withun) Date: 17 Nov 2005 10:56:23 -0800 Subject: catch dbi.program-error ? Message-ID: <1132253783.446415.18920@z14g2000cwz.googlegroups.com> I'm having difficulty catching dbi.program-error which occurs this way: import dbi, odbc [...] self.__cur.execute(sql) >>> dbi.program-error: [Sybase][ODBC Driver][Adaptive Server Anywhere]Table 'depfile' not found in EXEC but try: self.__cur.execute(sql) except dbi.program-error,e: print " caught " raise causes >>> except dbi.program-error, e: >>> AttributeError: 'module' object has no attribute 'program' What, in general, is the offender here? The hyphen in "dbi.program-error" or the dot? From paul at boddie.org.uk Wed Nov 23 12:15:24 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Nov 2005 09:15:24 -0800 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> Message-ID: <1132766124.891749.162010@o13g2000cwo.googlegroups.com> Ed Jensen wrote: > Try this little experiment: Walk up, at random, to 100 people on the > street. Show them a software CD-ROM -- a game, a word processor, > whatever. Tell them it's free. Then ask them what they think that > means. It's interesting that you bring this tired thought experiment up in the context of the original remark: "Its license is far more "free" than GPL is." If we were focusing on the "vox pop" interpretation of the word "free", that remark wouldn't make any sense at all: after all, what's more gratis than gratis (to use a less ambiguous word)? [...] > The success of things like Python -- which is not GPL licensed, afaik > -- pretty much proves the GPL is unnecessary for the success of free > projects. Python is moderately successful, yes, but the GPL is a useful tool to ensure that certain freedoms are preserved. I've been made aware of a certain level of dissatisfaction about whether organisations porting Python to other platforms would choose to share their modifications and improvements with anyone, or whether binary downloads with restrictive usage conditions would be the best even the customers of such organisations would be able to enjoy. Ensuring some of those freedoms can be an effective way of making open source software projects successful. > The GPL is just some bizarre social agenda being pushed by some crazies, and a lot > of programmers (who are not lawyers) fell for the hippie nonsense. At least when it comes to software licensing, what probably upsets the anti-GPL "pragmatic licensing" crowd the most is that Stallman is quite often right; the BitKeeper debacle possibly being one of the more high-profile cases of some group's "pragmatism" (or more accurately, apathy) serving up a big shock long after they'd presumably dismissed "the hippie nonsense". > So, you may like to bandy around the mildly offensive "free as in freeloading", Well, from what I've seen of open source software usage in business, a key motivation is to freeload, clearly driven by people who neither see nor understand any other dimension of software freedom than your "vox pop" definition. Such users of open source software could make their work a lot easier if they contributed back to the projects from which they obtained the software, but I've seen little understanding of such matters. Of course, businesses prefer to use euphemisms like "cost reduction" or "price efficiency" rather than the more accurate "freeloading" term, and they fail to see any long-term benefits in anything other than zero cost, zero sharing acquisition and redistribution of code. But then in some sectors, the game is all about selling the same solution over and over again to the same customers, so it's almost understandable that old habits remain. > but then that gives me the right to refer to GPL'd software as "free as in pushing my > personal social agenda". Pushing on whom, though? No-one makes you use GPL'd software by, for example, installing it on almost every computer you can buy from major vendors. If, on the other hand, you mean that some social agenda is being imposed on you because, in choosing to redistribute someone's work, you are obliged to pass on those freedoms granted to you by the creator (or distributor) of that work, then complaining about it seems little more than a foot-stamping exercise than anything else. Paul From scott.daniels at acm.org Thu Nov 24 08:05:15 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 24 Nov 2005 05:05:15 -0800 Subject: return in loop for ? In-Reply-To: References: <4384F705.31CEC951@valid.org><86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: <4385b8ee$1@nntp0.pdx.net> Fredrik Lundh wrote: > Steve Holden wrote: >>sepcifications > did you mean: sceptifications ? QOTW! I love it. I need to insert this in my vocabulary instantly! --Scott David Daniels scott.daniels at acm.org From mwm at mired.org Wed Nov 23 19:18:32 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 19:18:32 -0500 Subject: Making immutable instances References: Message-ID: <861x163nl3.fsf@bhuda.mired.org> "Giovanni Bajo" writes: > Ben Finney wrote: >> How can a (user-defined) class ensure that its instances are >> immutable, like an int or a tuple, without inheriting from those >> types? >> >> What caveats should be observed in making immutable instances? > > In short, you can't. I usually try harder to derive from tuple to achieve this > (defining a few read-only properties to access item through attributes). Using > __slots__ is then required to avoid people adding attributes to the instance. Note that this property of __slots__ is an implementation detail. You can't rely on it working in the future. I'm curious as to why you care if people add attributes to your "immutable" class. Personally, I consider that instances of types don't let me add attributes to be a wart. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From qwweeeit at yahoo.it Mon Nov 7 16:12:25 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 7 Nov 2005 13:12:25 -0800 Subject: Web automation (was: Pressing a Webpage Button) References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> Message-ID: <1131397945.832762.71070@g47g2000cwa.googlegroups.com> Hi all, I must correct myself: > With such a method you can bypass the Google's restrictions, because > you are using the browser (only building automatically the query). Of course that's not correct because you are using a program (twill) different from a browser and if google controls from where the query arrives... I must thank calfdog for his reply, but the tool he suggest (pamie) is only working in Windows and with the browser Internet Explorer. I didn't explicity refer to Linux, but I supposed the everyone knew that web automation (and in general "automation") is only a problem in Linux. Bye. From igouy at yahoo.com Wed Nov 30 10:50:13 2005 From: igouy at yahoo.com (igouy at yahoo.com) Date: 30 Nov 2005 07:50:13 -0800 Subject: Computer Language Shootout In-Reply-To: <1133299669.010298.283100@g14g2000cwa.googlegroups.com> References: <1133298307.938958.186070@f14g2000cwb.googlegroups.com> <1133299669.010298.283100@g14g2000cwa.googlegroups.com> Message-ID: <1133365813.818232.205020@o13g2000cwo.googlegroups.com> bearophileHUGS at lycos.com wrote: > This is a direct translation of the D code, maybe it's not the faster > Python implementation, and surely it's not the shorter one. But Psyco > makes it much faster (Psyco likes "low level" style code). And if you contributed the program like this http://shootout.alioth.debian.org/gp4/faq.php#contribute we could run the program with Psyco http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=psyco&lang2=python best wishes, Isaac From duncan.booth at invalid.invalid Wed Nov 23 03:44:49 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Nov 2005 08:44:49 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <438379e0.485300825@news.oz.net> Message-ID: Bengt Richter wrote: > On Tue, 22 Nov 2005 13:26:45 +0100, "Fredrik Lundh" > wrote: >>Duncan Booth wrote: >> >>> >>> it = iter(aList) >>> >>> zip(it, it) >>> [('a', 1), ('b', 2), ('c', 3)] >> >>is "relying on undefined behaviour" perhaps the new black ? > Is it really undefined? If so, IMO it should be defined to > do what it apparently does. > > Hm, actually, something tells me I've seen some variation of this > before, but I can't think of the context off hand. > Yes, the subject does come up occasionally. Perhaps you are thinking of this thread: http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/83baa4bd42fc9b69/d933c7333d3863ce In that thread, I was the one arguing that the behaviour was undefined. My memory was that I was forced to back down on that one, but looking back at the thread I now think it was only itertools.izip I was forced to admit defines its behaviour as working that way. More googling will show that it was proposed that zip should be defined as working with this, but that proposal was rejected. See: http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/a6ba37b0fb0fa69e/f8a3d3b6d1a9fcbd So scratch my original suggestion and substitute this for defined behaviour: >>> it = iter(aList) >>> list(itertools.izip(it, it)) [('a', 1), ('b', 2), ('c', 3)] From danb_83 at yahoo.com Sun Nov 20 03:51:11 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Nov 2005 00:51:11 -0800 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: <1132476670.992305.106250@o13g2000cwo.googlegroups.com> Roy Smith wrote: > Steven D'Aprano wrote: > > That's a tad unfair. Dealing with numeric literals with lots of digits is > > a real (if not earth-shattering) human interface problem: it is hard for > > people to parse long numeric strings. > > There are plenty of ways to make numeric literals easier to read without > resorting to built-in language support. One way is: > > sixTrillion = 6 * 1000 * 1000 * 1000 * 1000 > > Or, a more general solution might be to write a little factory function > which took a string, stripped out the underscores (or spaces, or commas, or > whatever bit of punctuation turned you on), and then converted the > remaining digit string to an integer. You could then write: > > creditCardNumber = myInt ("1234 5678 9012 3456 789") Or alternatively, you could write: creditCardNumber = int('1234''5678''9012''3456''789') From damonwischik at gmail.com Fri Nov 25 06:43:20 2005 From: damonwischik at gmail.com (damonwischik at gmail.com) Date: 25 Nov 2005 03:43:20 -0800 Subject: Stealing focus: emacs, and PIL, in Windows Message-ID: <1132919000.250236.196090@g43g2000cwa.googlegroups.com> I'm using GNU Emacs 21.3.1 with python-mode 1.0alpha under Windows XP. Whenever I execute a command in an edit window (with py-execute-region), the output window steals the focus. How can I stop this happening? I don't know any lisp, but I hacked together this routine so that that when I press ctrl+return the entire current block is executed. (defun py-execute-paragraph (vis) "Send the current paragraph to Python Don't know what vis does." (interactive "P") (save-excursion (forward-paragraph) (let ((end (point))) (backward-paragraph) (py-execute-region (point) end )))) (global-set-key [(ctrl return)] 'py-execute-paragraph) It seems to me (though I could well be wrong) that the focus stays in the edit window during the execution of this command (thanks to save-excursion); but the focus shifts to the command window whenever there is output, in this case a new prompt ">>>", in the routine py-comint-output-filter-function. I commented out the command (pop-to-buffer (current-buffer)) and now the command window no longer steals focus. But I don't know if this has any other side effects, or it there's a better way to prevent focus being stolen. Damon. From apardon at forel.vub.ac.be Mon Nov 28 05:22:57 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2005 10:22:57 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1133155122.587903.237140@g44g2000cwa.googlegroups.com> Message-ID: Op 2005-11-28, Serge Orlov schreef : > Antoon Pardon wrote: >> No it wasn't. From what I have picked up, the ternary operator >> was finaly introduced after one of the developers tripped over >> the commonly used idiom to simulate a ternary operator, which >> can fail in certain cases. > >> >> Anyway, when I was arguing for a ternary operator in python, >> those who opposed me, certainly gave me the impression that >> they thought I wanted to mangle the language, the mere idea >> of a ternary operator was against the spirit of python. >> >> When I argued for a more general loop construct similar >> objections were made and the proposal was fiercely fought. >> Someone even started a PEP, with the intention to bury >> the idea. (That can be from before I argued for it) >> >> Now I have read about both that they will be introduced in >> Python 2.5 without a whisper of protest. > > Protesting BDFL is absolutely useless by definition even if you > disagree. Tim Peters wanted generators for 10 years > > and he has much more power of convincing Guido than you. Why do you > think your proposal should be immediately accepted? I don't think that. I was just illustrating that using: "That is unpythonic" isn't really an argument, because things that were thought unpythonic before are now accepted as the pythonic way. > By the way, I don't see the features you mentioned neither in > > nor among PEPs. Perhaps they are not final? There were people who annouced these features in this newsgroup for version 2.5 with a rather clear titles and those from the dev-list that frequent this newsgroup didn't protest. Among the PEP's I see that at least PEP 308 is accepted. So although it may not be implemented for version 2.5 a ternary operator is now an accepted as being pythonic. -- Antoon Pardon From hancock at anansispaceworks.com Wed Nov 2 18:46:46 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 2 Nov 2005 17:46:46 -0600 Subject: An FAQ Please Respond In-Reply-To: References: Message-ID: <200511021746.46397.hancock@anansispaceworks.com> On Wednesday 02 November 2005 04:58 pm, clinton Brandt wrote: > Hey I am Learning Blender for 3D mesh design and the current Relese doesnt > recognize my python 2.4.1 it stopped at python 2.3. there alpha test of > their next release supports py 2.4 but as a noob id like to learn an a less > buggy release. so my question is can i install 2 versions of python and if i > do, does the newer version hold rank when running .py files. or should i axe > the version i have and the start with 2.3 then load 2.4 or what? thanks Yes, you can have more than one Python installed at once. The trouble is all with making sure you start the right one when you need it (so you have to be explicit). You really should ask this question on a Blender forum, though. I can recommend: http://www.elysiun.com/ -- users' forum (this is your best bet for a simple installation problem). http://www.blender.org/ -- blender site and developers' forum Since Blender embeds its own Python interpreter, there is some question as to what exactly it means by "recognizing" an installed Python. I'm guessing it only uses the library. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From s99999999s2003 at yahoo.com Tue Nov 15 20:30:24 2005 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 15 Nov 2005 17:30:24 -0800 Subject: generate HTML In-Reply-To: References: <1131962200.216285.307760@g44g2000cwa.googlegroups.com> <4378dc0c$1@nntp0.pdx.net> <1132051974.733119.184010@f14g2000cwb.googlegroups.com> Message-ID: <1132104624.381739.204160@f14g2000cwb.googlegroups.com> thanks i will check out the example you have given.actually my html output is a bit dynamic in the sense that i may have different number of rows depending on some inputs. so i am putting everything into a list and using 'extend' to append to that list for every dynamically generated rows using for/while loops. then at the end of the code, i use writelines() to output to the file. From __peter__ at web.de Mon Nov 28 03:43:04 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Nov 2005 09:43:04 +0100 Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <1132708265.941224.186550@g44g2000cwa.googlegroups.com> <1133138659.140291.220970@g14g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: >> def ireduce(op, iterable, *init): >> ????iterable?=?chain(init,?iterable) >> ????accu?=?iterable.next() >> ????yield?accu >> ????for?item?in?iterable: >> ????????accu?=?op(accu,?item) >> ????????yield?accu > I believe there is only one initializer in reduce. Throw in a if len(init) > 1: raise TypeError for increased similarity to reduce(). > Also it is possible to not provide it. Try it. Peter PS: Did I mention that I prefer for-loops over reduce() most of the time? From python-url at phaseit.net Sat Nov 26 16:40:45 2005 From: python-url at phaseit.net (Cameron Laird) Date: Sat, 26 Nov 2005 21:40:45 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 26) Message-ID: QOTW: "... '[B]ut assume that I have some other use case' isn't a valid use case". - Fredrik Lundh "Rolling your own solution, on the other hand, can end in a long road discovering what those CORBA people were doing for all those years." - Paul Boddie NOTW: sceptifications. Steven D'Aprano carefully details a common confusion among newcomers about empty lists and initialization: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8480fae54a64fc15/ Inyeol Lee and others illustrate use of regular expression syntax having to do with repeated patterns: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b5e7abb4ff1e156c/ Metakit 2.4.9.5 corrects a potential disk-full error, and improves performance greatly in certain circumstances: http://www.equi4.com/pub/mk/CHANGES http://www.equi4.com/metakit.html William Peterson jokes that, "[i]f you ask ten people on this newsgroup [about GUI construction newcomers] you'll probably get twelve opinions"--and then the community promptly proves him right: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6fd1ea6b4a2d31f8/ Having arrived in the twenty-first century, clp now has its own (provisional) podcast: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b39581f59dce9191/ David Wahler cogently perverts^H^H^H^H^H^H^H^Hextends pickle to serialize *classes* (as opposed to their instances): http://groups.google.com/group/comp.lang.python/browse_thread/thread/10a03f094303a91c/ Fully-general backward-compatibility has substantial costs, often greater than the version migration it's supposed to spare us. Several of the regulars discuss this seriously: http://groups.google.com/group/comp.lang.python/browse_thread/thread/423d9dfa80456966/ __slots__ are only a (memory) optimization, restricted to well-defined circumstances, explains the martellibot: http://groups.google.com/group/comp.lang.python/browse_thread/thread/1cc68de7af477386/ A good thing about Cheetah is that it cooperates with Python's inheritance: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f063406b648c7d0c/ ======================================================================== 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/topics/pythonurl/ (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 fdu.xiaojf at gmail.com Sun Nov 20 22:28:09 2005 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Mon, 21 Nov 2005 11:28:09 +0800 Subject: How to install python2.4.2 on IRIX6.5 ? Message-ID: <43813EC9.9000601@gmail.com> Hello, I am trying to install python2.4.2 on a SGI origin3200 machine running IRIX6.5. The native c compiler was used to compile python. "./configure --prefix=/my/path/to/install" runs ok, then, "smake OPT= " runs ok but "smake test" gets errors, here is the output: ------------------------------------------------ 247 tests OK. 2 tests failed: test_fpformat test_locale 41 tests skipped: test_aepack test_al test_applesingle test_bsddb test_bsddb185 test_bsddb3 test_bz2 test_cd test_cl test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_curses test_dl test_gdbm test_gl test_gzip test_imgfile test_ioctl test_linuxaudiodev test_macfs test_macostools test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_scriptpackages test_socket_ssl test_socketserver test_sunaudiodev test_tcl test_timeout test_urllib2net test_urllibnet test_winreg test_winsound test_zipimport test_zlib Ask someone to teach regrtest.py about which tests are expected to get skipped on irix6. *** Error code 1 smake: Error: 1 error ------------------------------------------------ I also tried regrtest.py according the above instruction, -------------------------------------------------------- origin3200% ./Lib/test/regrtest.py -s test_fpformat test_fpformat test test_fpformat failed -- Traceback (most recent call last): File "/disk2/jfxiao/local/source/Python-2.4.2/Lib/test/test_fpformat.py", line 51, in test_reasonable_values self.checkFix(realVal, d) File "/disk2/jfxiao/local/source/Python-2.4.2/Lib/test/test_fpformat.py", line 28, in checkFix self.assertEquals(result, expected) AssertionError: '-0' != '0' 1 test failed: test_fpformat origin3200% ./Lib/test/regrtest.py -s test_locale test_frozen 1 test OK. --------------------------------------------------------- Can somebody tell me what's the problem ? Thanks! Regards, xiaojf From chris.atlee at gmail.com Mon Nov 21 21:50:05 2005 From: chris.atlee at gmail.com (chris.atlee at gmail.com) Date: 21 Nov 2005 18:50:05 -0800 Subject: path module / class References: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> <8u6dnWEcZ6-6AuPeRVn-gg@powergate.ca> Message-ID: <1132627805.946339.59280@f14g2000cwb.googlegroups.com> Peter Hansen wrote: > Okay, granted. I guess this is the same as in any other case of > deprecation (e.g. some people still have to work with code that uses > apply() or string module methods). Yup, this is exactly what will have to happen. Most or all of os.path and maybe some of os/glob/fnmatch/stat will have to be deprecated and kept around for a release or two. Perhaps a large section of the PEP-to-come should deal with this. > > Peter Hansen: > >> We've mandated use of path.py internally for all projects because > >> we've noticed (especially with non-expert Python programmers... i.e. > >> junior and intermediate types, and senior types new to Python) a > >> decrease in errors. My personal experience has always been that when it comes time to write the part of the project that interacts with the filesystem, I have to decide once again if I want to use the standard library, or use path.py. And I usually decide against using path.py; not because I don't like it, but because I don't like bundling code that I didn't write as part of my project. A lot of the programs that I write in python are pretty simple single file scripts that help manage machines on an intranet. I like to be able to simply copy these scripts around and run them without worrying about their dependencies. Another personal observation is that the current os.path / fnmatch / glob / stat modules give a very C-like interface to the filesystem. There's a lot of repetition of things like os.path.join(), os.path.splitext(), as well as repetition of the reference to the string object which defines the path being operated on. This seems to violate the DRY principle to a small degree, and it also makes code that much harder to maintain. Cheers, Chris From jasvo77 at gmx.net Sun Nov 20 07:24:16 2005 From: jasvo77 at gmx.net (Jan Voges) Date: Sun, 20 Nov 2005 13:24:16 +0100 Subject: about polygon References: Message-ID: Hi! Am Sun, 20 Nov 2005 03:55:21 -0800 schrieb Shi Mu: > Why I got a black polygon in the following code? > How can I make it no-color filled? Use create_line instead: c.create_line(60,60,100,60,100,100,60,120,60,60) Jan From frank at chagford.com Tue Nov 1 01:12:44 2005 From: frank at chagford.com (Frank Millman) Date: 31 Oct 2005 22:12:44 -0800 Subject: looking for a good python module for MS SQL server In-Reply-To: References: Message-ID: <1130825563.963453.162120@f14g2000cwb.googlegroups.com> Anat wrote: > Hi, > Does anyone know a good python mudule that works with MS SQL server? > Thanks, > Anat I use the odbc module from pywin32. I believe that it is not 100% DB-API 2.0 compliant, but it works fine for me. It has the advantage that if you have installed pywin32 (which is advisable on MSW anyway) you do not have to install anything else. I tried adodbapi a few years ago, and it seemed slow in returning results. I don't know if it has improved in the meantime. There is one thing I have not figured out how to do with MS-SQL - I would be interested if anyone has a solution. I use 'scrollable cursors' a lot. DB-API does not seem to define any methods to facilitate this, so I construct them and manage them myself with a series of cur.execute(...) commands. PostgreSQL allows you to 'fetch' multiple rows at a time. MS-SQL in its normal mode does not. This is taken from the on-line help - "Transact-SQL cursors are limited to fetching one row at a time. API server cursors support fetching blocks of rows with each fetch. A cursor that supports fetching multiple rows at a time is called a block cursor." It goes on to say that API's which support block cursors are OLE DB, ODBC, ADO, and DB-Library, and that each one has its own syntax. Do adodbapi, mxODBC, or any other modules allow you to do this? Thanks Frank From steve at REMOVETHIScyber.com.au Mon Nov 14 16:50:42 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 15 Nov 2005 08:50:42 +1100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> Message-ID: On Mon, 14 Nov 2005 17:15:04 +0100, Pierre Barbier de Reuille wrote: > The problem is not about having something constant ! > The main point with symbols is to get human-readable values. > Let say you have a symbol "opened" and a symbol "closed". The state of a > file may be one of the two. > > If you have these symbols, you can ask for the state at any point and > get something readable. If you use constants valued, typically, to > integers, the state of your file will we 0 or 1, which does not mean > anything. ??? Why does the byte string "\x6f\x70\x65\x6e\x65\x64" have intrinsic meaning when the int 0 doesn't? It certainly doesn't mean anything to non-English speakers. If all you want is human readable byte strings, then just use them: class MyFile: def open(self): self.state = "opened" def close(self): self.state = "closed" You don't need special syntax to use strings as symbols, you get them for free without all the overhead you are proposing. > Now, if you're using an object with more than two states, and moreover > if the number of states is likely to increase during developpement, it's > much more convenient to directly get the *meaning* of the value rather > than the value itself (which does not mean anything). How do you expect this to work in practice? You have an object which has states: obj = SomeThingComplex() Now you want to operate on it according to the state. What do you do? if obj.state is $closed$: obj.open() elif obj.state is $opened$: obj.close() elif obj.state is $full$: obj.make_empty() elif obj.state is $empty$: obj.make_full() else: # some other symbol raise ValueError("Unexpected state %s") % obj.state Replace "is" with "==" and $ with " and you have strings. You still need to know what the object state is, and the way you do that is by comparing it to something. Whether you call that something a symbol, an enum, a string, an int, a class, whatever, the comparison still needs to be done. > The key point that, I think, you misunderstand is that symbols are not > *variables* they are *values*. Python doesn't have variables. It has names and objects. > Well, I think a new syntax will promote the use of symbols. And as I > think they are good practice (much better than meaningless constants) > they should be promoted. Needless to say that in every language I know > implementing symbols (or something close to symbols), there is an > easy-to-use syntax associated. Why is $closed$ better practice than "closed"? Why is "closed" a meaningless constant and $closed$ a good symbol? > Well, one *big* difference between short string and symbols is that the > identity between short strings are implementation dependant, Then don't use identity. Who cares whether the state you are testing against points to the same chunk of memory or not? What possible difference will that make, except some unnecessary optimization _possibly_ saving you one millionth of a second at runtime? > while > between symbols it has to be in all implementations as you will rely on > this identity. Then, once more, strings are just one possible > implementation for symbols and I wouldn't like to tie that much symbols > to strings. And ints are another possible implementation for symbols, or classes, or enums. obj.state = 42 is not an ideal implementation, because it is not self-documenting, and self-documenting code is good code. But in some contexts, it may be the right thing to do: class MutablePolygon: """Define a polygon object that can grow or lose sides.""" def __init__(self, n): """Create a new polygon with n sides.""" self.state = n def grow_side(self): self.state += 1 def lose_side(self): self.state -= 1 Compare that with something like this: class MutablePolygon: """Define a polygon object that can grow or lose sides.""" def __init__(self, n): """Create a new polygon with n sides.""" if n == 1: self.state = $one$ elif n == 2: self.state = $two$ elif n == 3: self.state = $three$ elif n ... -- Steven. From fdu.xiaojf at gmail.com Thu Nov 17 23:23:40 2005 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Fri, 18 Nov 2005 12:23:40 +0800 Subject: install python2.4 on FreeBSD and keep using python2.3 In-Reply-To: <437D0840.3090004@bullseye.apana.org.au> References: <130df1930511170322n6b001072j@mail.gmail.com> <437D0840.3090004@bullseye.apana.org.au> Message-ID: <437D574C.7000202@gmail.com> Andrew MacIntyre wrote: >[posted & mailed] >Ksenia Marasanova wrote: > > > >>I have python2.3, installed from port /lang/python long time ago. The >>current version is 2.4, but I'd rather have two python versions, >>instead of upgrading. >>Is there maybe a way to somehow link installed python to >>/lang/python2.3 port, and then upgrade ports and install /lang/python >>as a new (2.4) version, without upgrading? >>Or am I missing something and the things are much easier? I am not a >>FreeBSD guru and it's my first python upgrade... thanks! >> >> > >As far as I know, the FreeBSD ports versions of python don't interfere >with python's default strategy of installing based on major.minor version >numbers (eg /usr/local/lib/python2.[3|4] & /usr/local/bin/python2.[3|4]). >/usr/local/bin/python will be linked to the most recently installed >python port. > > > Can I install python2.4.2 and keep using python2.4.1 on IRIX? >Its been a while since I looked, but I thought that the ports collection >would contain 2.3(.5) as well as 2.4(.2, default "python" port), so I >expect that the ports collection has support for multiple versions >anyway. > >So you should be able to update the ports collection, change into >lang/python and "make install". A quick review of the port makefiles >should confirm this. Any scripts that are 2.3 only will need to be >doctored to use /usr/local/bin/python2.3 instead of >/usr/local/bin/python. > >------------------------------------------------------------------------- >Andrew I MacIntyre "These thoughts are mine alone..." >E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 > andymac at pcug.org.au (alt) | Belconnen ACT 2616 >Web: http://www.andymac.org/ | Australia > > From fuzzyman at gmail.com Wed Nov 23 10:21:20 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Nov 2005 07:21:20 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <438258f2.411334718@news.oz.net> <4383635b.479535916@news.oz.net> <1132734447.104113.99140@o13g2000cwo.googlegroups.com> Message-ID: <1132759280.221030.210460@g44g2000cwa.googlegroups.com> Rick Wotnaz wrote: > "Fuzzyman" wrote in > news:1132734447.104113.99140 at o13g2000cwo.googlegroups.com: > > > > > Christoph Zwerschke wrote: > >> - the internal keys list should be hidden > > > > I disagree. It is exposed so that you can manually change the > > order (e.g. to create a "sorted" dict, rather than one ordered > > by key insertion). > > > > What do you *gain* by hiding it ? > > The internal list should be 'hidden' in the sense that it itself > would not be modifiable, though it should be routine to obtain a > copy of it at any time. That copy could then be arranged as needed. > Any rearrangement of the original list's order destroys the reason > for having an entry- or change-ordered dict in the first place. > That's not the only use case. Other use cases are to have a specific order, not based on entry time. Simple example : d1 = OrderedDict(some_dict.items()) d1.sequence.sort() d1 is now an ordered dict with the keys in alphabetic order. If you don't want to modify sequence, don't. If you want a copy do : seq = d1.sequence[:] All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -- > rzed From smithsm at samuelsmith.org Thu Nov 17 19:58:40 2005 From: smithsm at samuelsmith.org (Samuel M. Smith) Date: Thu, 17 Nov 2005 17:58:40 -0700 Subject: Configure failing why? In-Reply-To: References: Message-ID: Thanks for your help. Your confirmation that gcc should be setting the execute permissions gave me something easy to test against. I finally discovered the problem. It was nfs. The file system was nfs mounted and nfs is causing the aberrant behavior. If I did the test on the onboard flash file system it worked. I finally used a different nfs server and the problem went away. I was serving nfs from a Mac OS X 10.4.3 machine. The problem did not occur on OS X 10.4.2 not does it occur when serving nfs from OS X 10.3.9 It something new introduced in 10.4.3. I don't have a fix for it. Anyone have a suggestion it would help. On 15 Nov, 2005, at 15:40, Fredrik Lundh wrote: > Samuel M. Smith wrote: > >> I am trying to build python2.4.2 on an arm 9 running Debian 3 Sarge > >> configure:1842: ./a.out >> ./configure: line 1: ./a.out: Permission denied >> configure:1845: $? = 126 >> configure:1854: error: cannot run C++ compiled programs. >> If you meant to cross compile, use `--host'. >> See `config.log' for more details. >> >> It appears that for some reason the a.out file that the configure >> script is making is not getting execute permissions enable by the >> configure script > > on a sane standard Unixoid system, the compiler is required to set the > following permission flags > > S_IRWXO | S_IRWXG | S_IRWXU > > if and only if the program was successfully compiled and linked. > > what happens if you do > > $ cat >foo.cpp > int main(){ return 0; } > $ c++ foo.cpp > $ ls -l a.out > > ? > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list ********************************************************************** Samuel M. Smith Ph.D. 2966 Fort Hill Road Eagle Mountain, Utah 84043 801-768-2768 voice 801-768-2769 fax ********************************************************************** "The greatest source of failure and unhappiness in the world is giving up what we want most for what we want at the moment" ********************************************************************** From grante at visi.com Sat Nov 5 18:30:33 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 05 Nov 2005 23:30:33 -0000 Subject: Using Which Version of Linux References: <861x1v72um.fsf@bhuda.mired.org> Message-ID: <11mqg4pml76r947@corp.supernews.com> On 2005-11-05, Mike Meyer wrote: > "Programmer-friendly" is pretty vague. Gentoo is the only Linux distro > I've run into (which excludes a *lot* of Unix distros) that I'd > consider programmer friendly, because it doesn't split packages up > into "user stuff" and "developer stuff". That means you have to > install two packages instead of one if you want to build things > against that software. On the other hand, it uses it's own "package" > manager - emerge - so you can't take advantage of rpms/debs from other > systems (or you couldn't last time I looked into it). It also installs > the least amount of "bundled" software, which I consider a programmer > friendly behavior. I just switched one of my computers to gentoo, and I like it a lot. It's very no-nonsense, but there are alot of available packages and everything (so far) just works. However, it's not for the impatient (or at least not for the poor and impatient). Since it compiles packages from source, a full-featured desktop install on a slow machine can take days to finish. -- Grant Edwards grante Yow! if it GLISTENS, at gobble it!! visi.com From steve at REMOVETHIScyber.com.au Mon Nov 28 17:10:17 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 29 Nov 2005 09:10:17 +1100 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: On Mon, 28 Nov 2005 12:40:07 -0600, Rocco Moretti wrote: > Gaak! No! The Python license you point to contains horrible amounts of > cruft due to the ownership ping-pong game. (And just using the hyperlink > like you did leaves it vauge as to who is doing the liscensing - Steven > D'Aprano? the PSF? BeOpen? CNRI? Stichting Mathematisch Centrum?) As I > understand it, the PSF's official position is that the Python license > (even just the top most one) is not appropriate for any program besides > Python itself. > > http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq Well, I've just learnt something. Thank you. I'll be having a long talk with the experience Python developer who advised me to do that... -- Steven. From steve at REMOVETHIScyber.com.au Thu Nov 3 07:25:45 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 03 Nov 2005 23:25:45 +1100 Subject: OT - Re: Microsoft Hatred FAQ References: Message-ID: On Thu, 03 Nov 2005 04:34:20 -0500, Tim Daneliuk wrote: > A) I don't much care if people wander off topic from time to time - > that's what filters are for. But as a matter of general courtesy > is it too much to ask that the subject line be so marked? Fair enough. > B) Rhetoric is not Reality. "Crime" has a very specific definition. > It always has one or more of Fraud, Force, or Threat. Nonsense. Jaywalking is a crime. So is littering. So is merely belonging to certain organisations, such as the German Nazi party or any number of allegedly terrorist groups. Walking around naked in public is a crime, and in many places in the world, including the USA, you then become a "registered sex offender" for the rest of your life. (So much for doing time and wiping the slate clean.) Possession of many substances is a crime in the USA, and not just drugs of addiction. There is no Fraud, Force or Threat involved in growing cannabis in your backyard, or selling pornography to teenagers, or driving without a licence. Possession of banned books is a crime in many countries, and yes even in the 21st century there are many, many banned books. If legislation being urged on the US Senate by the MPAA is passed, manufacturing, selling and possibly even possession of analog to digital devices will become a crime -- not just a civil offense, or a misdemeanor, but a felony. Even *accidents* can be crimes, if the circumstances are right (or perhaps I should say wrong). The act of manslaughter is still a crime, even if it does not include Fraud, Force or Threat. "Failing to do you job" can land you in jail, if people die because of your negligence. > No such > case against Microsoft has ever been levied. That is, if you ignore all the dozens of times Microsoft has either settled out of court or been found guilty of crimes by juries. > Just because *you* > don't like market outcomes doesn't make it a "crime". In civilizations that believe in freedom for human beings, freedom is not unlimited. There are actions which remain forbidden, even though that limits individual freedom. Bill Gates is not permitted to lock you up against your will: his freedom to restrict others' freedoms is severely curtailed. In civilizations that believe in free markets, freedom is also not unlimited. There are actions which are forbidden, because those actions restrict the freedom of others. Microsoft has been found guilty of deliberately committing those illegal acts, in Japan, Europe and even the USA. Just as Bill Gates can't legally hire henchmen to drag you away and lock you up in his basement, so he can't legally use economic punishment against anyone who would buy your goods or services, and for the same reason: his actions will infringe your freedoms. Those who believe in free markets understand that unrestricted freedom leads to the biggest bully limiting the freedoms of others. But then there are those that defend the right of bullies to limit the freedom of others. > C) Hate Microsoft all you want. But those of us old enough to have > actually done this for than 10 minutes recall the days where every single > hardware vendor was also a unique software and systems vendor. > Absent a Microsoft/Intel-style de facto standard, you'd never have > seen the ascent of Linux or Open Source as it exists today. Nonsense again. Real standards, like TCP/IP which is the backbone of the Internet, aren't controlled by any one company. Anyone can create a TCP stack. Nobody but Microsoft can create a competing version of Windows. TCP/IP became a standard long before Microsoft even acknowledged it's existence. So did ASCII, the IBM BIOS, and serial ports, to name just a few. Does the term "ISO standard" mean anything to you? Intel-compatible hardware is a true de facto standard, because there are actual competitors to Intel who product compatible but different hardware. AMD CPUs are different from Intel, but you can run the same copy of Windows on either and get the same results. The same can't be said of the Windows "standard" -- there is Microsoft Windows, and there is nothing else. While OS X or Linux or Solaris might do much the same sort of things as Windows, they aren't Windows-compatible in the same way that AMD and Intel CPUs are compatible. At best they can interoperate with Windows, or share data with Windows. You do your argument no favours by trying to confabulate the Microsoft monopoly in software with Intel's lack of monopoly. Intel has to compete in a free market, and hardware costs have fallen hugely: my first PC cost me AUD$4000 in 1986. Today I can get a machine a thousand times more powerful for $800. The first time I bought Microsoft Word and Excel, I paid around $100 each for them. MS Office retails at over $800 today, and you get very little extra functionality that didn't exist in 1986, lots more meaningless bells and whistles, and no printed documentation. In the same time that hardware has fallen in price by 80%, Microsoft's software has increased in price by 300%. Even if you argue that nobody pays full retail price, and use the OEM price, the software has increased in price by 50% in the same time that hardware has fallen by 80%. > Drivers > are painful to write, so oddball or vendor-specific systems don't > get them very rapidly. Microsoft/Intel commoditized the space whether > you like it or not. They (perhaps unintentionally) created the > computer equivalent of "standard connectors" as found in audio systems. In any mass market, hardware always becomes a commodity. It happened in automobiles, it happened in consumer electronics, it happened in audio and video systems. Trying to give Microsoft credit for something that had already started before Microsoft Corporation even existed is either dishonest or ignorant -- and in any case, if you were going to give credit to any single vendor, it should be IBM. Some of us remember when PCs were called IBM Compatible, not "Microsoft Compatible" and not "Intel Compatible". > F) There are *more* choices than ever today for both systems and applications > software. Stop foaming, and go do something useful with them ... Really? In 1990 or thereabouts, on the Macintosh alone, I had bought or trialled WriteNow, MacWrite, WordPerfect, FullWrite, Nisus, as well as Microsoft Word and Works. For spreadsheets, there was Excel, Works, Wingz, FullImpact, and Lotus Jazz. They varied in marketshare, of course, but none of them controlled the market. And that was just the Macintosh. Today, there is... Microsoft Word and Excel. Perhaps a few percent of the market uses WordPerfect or StarOffice on Windows, OpenOffice on Linux, ClarisWorks on Macintosh, maybe a handful of other niche products. Now Microsoft can't be entirely blamed for that, companies like Ashton-Tate have to shoulder a goodly share of the blame for their own misfortune. But Microsoft's criminal behaviour is directly to blame for the lack of competition in the desktop PC operating system market. I say "criminal behaviour" advisedly: they have been found guilty of breaking laws in Japan, Europe and the USA. It might be argued by some that they broke bad laws, but it is dishonest and factually wrong to argue that they did not break laws. Perhaps it is true that there is more PC software *in total* today than 20 years ago. That would hardly come as a surprise: the PC market is at least an order of magnitude bigger today than it was in 1985. There may even be markets where Microsoft has *not* been able -- or cared to -- capture a monopoly. Accounting software comes to mind. But just because Microsoft did not, or was unable to, illegally squelch competition in one market does not excuse them for doing so in another. -- Steven. From kxroberto at googlemail.com Fri Nov 4 17:15:35 2005 From: kxroberto at googlemail.com (Robert) Date: 4 Nov 2005 14:15:35 -0800 Subject: Bugfix release 2.3.6 ? Message-ID: <1131142535.411611.30550@g44g2000cwa.googlegroups.com> A bugfix release 2.3.6 would also be a good idea. I suffered at once from 2 severe bugs pending in 2.3 (fixed in 2.4) when going back to 2.3.5 (because of the monster python24.dll issue): * httplib.HTTP(x)Connection inserts still double Content-length headers whichs breaks on many servers. * _ssl.pyd has not the recent fixes. Robert From christopherlmarshall at yahoo.com Thu Nov 10 21:50:57 2005 From: christopherlmarshall at yahoo.com (christopherlmarshall at yahoo.com) Date: 10 Nov 2005 18:50:57 -0800 Subject: derived / base class name conflicts References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> Message-ID: <1131677456.966817.147470@g44g2000cwa.googlegroups.com> Fredrik Lundh wrote: > christopherlmarshall at yahoo.com wrote: > > > Now, 'i' might have already been defined by A or by the call to > > A.__init__() so if you define it without knowing that, you could be > > changing the behavior of A's methods in unknown ways, which is > > obviously a bad thing. > > http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 > > I see. Thanks for the link. So putting two underscores in front of an instance variable (or any identifier used inside the scope of a class statement) invokes a name mangling mechanism ( __x becomes __classname_x internally) so the following would not result in any conflicts class A: def __init__(self): self.__i= 0 class B(A): def __init__(self): A.__init__(self) self.__i= 1 Is it commonplace to use underscores when defining derived class instance variables, or is this considered against the grain of python? Chris Marshall From amhoov at gmail.com Wed Nov 30 12:53:17 2005 From: amhoov at gmail.com (amhoov@yahoo.com) Date: 30 Nov 2005 09:53:17 -0800 Subject: wxPython installation issues on Debian In-Reply-To: References: <1132795557.301034.92000@o13g2000cwo.googlegroups.com> Message-ID: <1133373197.812027.135740@g44g2000cwa.googlegroups.com> Hi Robert, Thanks for the suggestion, but an apt-cache search python2.4-wxgtk2.4 returns no results for a package with that name. Aaron From UrsusMaximus at gmail.com Mon Nov 28 07:52:51 2005 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: 28 Nov 2005 04:52:51 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1133178691.615662.101760@g43g2000cwa.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> <1133178691.615662.101760@g43g2000cwa.googlegroups.com> Message-ID: <1133182371.068785.278330@z14g2000cwz.googlegroups.com> I agree with Paron, using HTML forms and such as a minimal GUI front end meant to be run in a browser is often a good way to go. But I just want to mention, again, Stephen Ferg's "Easygui" at http://www.ferg.org/easygui/index.html which is a very easy way to go for desktop GUI's. You know, I just had a thought: I wonder if Easygui could be used on handhelds like Pocket PC's, Zaurus, Palm etc? If it could just be imported as a module it might be an awfully simple way to create GUI's for handhelds. Ron Stephens http://www.awaretek.com/plf.html From gdamjan at gmail.com Wed Nov 23 22:24:38 2005 From: gdamjan at gmail.com (Damjan) Date: Thu, 24 Nov 2005 04:24:38 +0100 Subject: Unicode in MIMEText References: Message-ID: > Why doesn't this work: > > from email.MIMEText import MIMEText > msg = MIMEText(u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430') > msg.set_charset('utf-8') > msg.as_string() ... > UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: > ordinal not in range(128) It's a real shame that unicode support in the python library is very weak sometimes... Anyway I solved my problem by patching email.Charset --- Charset.py~ 2005-11-24 04:20:09.000000000 +0100 +++ Charset.py 2005-11-24 04:21:02.000000000 +0100 @@ -244,6 +244,8 @@ """Convert a string from the input_codec to the output_codec.""" if self.input_codec <> self.output_codec: return unicode(s, self.input_codec).encode(self.output_codec) + elif isinstance(s, unicode): + return s.encode(self.output_codec) else: return s -- damjan From thakadu at gmail.com Tue Nov 22 23:56:50 2005 From: thakadu at gmail.com (thakadu) Date: 22 Nov 2005 20:56:50 -0800 Subject: bsddb185 question In-Reply-To: <4383c362$0$15583$9b622d9e@news.freenet.de> References: <1132611401.426797.143120@g47g2000cwa.googlegroups.com> <4382a563$0$8870$9b622d9e@news.freenet.de> <1132666914.659909.315550@g49g2000cwa.googlegroups.com> <4383c362$0$15583$9b622d9e@news.freenet.de> Message-ID: <1132721810.411702.50890@g47g2000cwa.googlegroups.com> Thanks Martin However the line: del db[key] results in an error: (1, 'Operation not permitted') (only tested on Python 2.3.5) Could this be because the .del() method of the dictionary has not been implemented either? In fact in my tests any attempt at altering the db by use of normal dictionary methods fails with the same error. e.g. db['newkey']='newvalue' causes the same error. (again, only tested on Python 2.3.5) So it seems only those methods listed by dir() have been implemented, which is what I would expect. Thanks for your info on the rules for interface implementation in Python. That is an interesting difference. I have grown to like the rules for java interface implementation because you are guaranteed that all defined methods for the interface have been implemented. That is what is meant by "implementing" an interface in java. Although I dont deny the Python way may also have its advantages, just different ones! From apardon at forel.vub.ac.be Mon Nov 7 08:27:12 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 13:27:12 GMT Subject: Threading-> Stopping References: <1131117582.259001.224930@g44g2000cwa.googlegroups.com> Message-ID: Op 2005-11-04, Tuvas schreef : > Is there a way to stop a thread with some command like t.stop()? Or any > other neat way to get around it? Thanks! What do you mean with stop? Pauze it or make it finish. In the latter case, if you really want it you could use the following. It requires ctypes. It also wont stop a thread while it is in a C extention. In that case the exception will be raised when it returns from the extention. import os import ctypes from time import sleep from random import randint class TimeOut(Exception): pass class Alarm(Exception): pass import threading class Xthread(threading.Thread): def start(self): self.__original_run = self.run self.run = self.__run threading.Thread.start(self) def __run(self): self.__thrd_id = threading._get_ident() try: self.__original_run() finally: self.run = self.__original_run def raize(self, excpt): Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, ctypes.py_object(excpt)) while Nr > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, None) sleep(0.1) Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, ctypes.py_object(excpt)) def alarm(self, tm): alrm = threading.Timer(tm, self.raize, (TimeOut,)) alrm.start() return alrm if __name__ == "__main__": class Continue(Xthread): def run(self): self.id = os.getpid() print self.id, "Begin" i = 0 try: for _ in xrange(randint(0,20)): for e in xrange(4 * 100000): i = i + e print self.id, "Finished" except Alarm: print self.id, "Interupted" lst = [Continue() for _ in xrange(10)] for T in lst: T.start() try: sleep(10) finally: for T in lst: T.raize(Alarm) From codecraig at gmail.com Tue Nov 1 07:42:34 2005 From: codecraig at gmail.com (py) Date: 1 Nov 2005 04:42:34 -0800 Subject: yapsnmp - on windows In-Reply-To: <1130790206.442561.244400@o13g2000cwo.googlegroups.com> References: <1130790206.442561.244400@o13g2000cwo.googlegroups.com> Message-ID: <1130848954.014300.231000@o13g2000cwo.googlegroups.com> anyone? py wrote: > I have installed net-snmp and of course python on windows xp. I > downloaded yapsnmp (http://yapsnmp.sourceforge.net/) and I can't seem > to use it. It has a swig interface...but I get errors when trying to > swig it.. > > C:\yapsnmp-0.7.8\src>"c:\Program Files\swigwin-1.3.25\swig.exe" -python > net-snmp.i > net-snmp.i(29): Error: Unable to find 'asn1.h' > net-snmp.i(30): Error: Unable to find 'snmp_api.h' > net-snmp.i(31): Error: Unable to find 'snmp.h' > net-snmp.i(32): Error: Unable to find 'snmp_client.h' > net-snmp.i(33): Error: Unable to find 'mib.h' > net-snmp.i(34): Error: Unable to find 'default_store.h' > > C:\yapsnmp-0.7.8\src> > > ...Any ideas? Anyone have this working on windows? From steven.bethard at gmail.com Wed Nov 2 10:51:05 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 02 Nov 2005 08:51:05 -0700 Subject: Attributes of builtin/extension objects In-Reply-To: <1130922856.013081.172770@g47g2000cwa.googlegroups.com> References: <1130922856.013081.172770@g47g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > - Where do the attributes of a datetime.date instance live if it has > neither a __dict__ nor __slots__ ? > - How does dir() determine them ? py> from datetime import date py> d = date(2003,1,23) py> dir(date) == dir(d) True py> for attr_name in ['day', 'month', 'year']: ... attr_val = getattr(date, attr_name) ... print attr_name, type(attr_val) ... day month year So all the instance "attributes" are actually handled by descriptors on the type. So datetime.date objects don't really have any instance attributes... > - dir() returns the attributes of the instance itself, its class and > its ancestor classes. Is there a way to determine the attributes of > the instance alone ? I'm just guessing now, but perhaps if no __dict__ or __slots__ is available, all instance "attributes" are managed by descriptors on the type? STeVe From duncan.booth at invalid.invalid Tue Nov 29 08:55:00 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Nov 2005 13:55:00 GMT Subject: Why I need to declare import as global in function References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> <1133265470.979764.157620@g14g2000cwa.googlegroups.com> Message-ID: Peter Otten wrote: >> Traceback (most recent call last): >> File "../tu.py", line 21, in run_tu >> execfile( filename ) >> File "TU_05_010.py", line 8, in ? >> import TU_05_tools >> File "./TU_05_tools.py", line 4, in ? >> f() >> File "./TU_05_tools.py", line 2, in f >> print math.pi >> NameError: global name 'math' is not defined >> >> I have remarq that this problem is raised when I execute code in an >> imported module (during importation) >> >> I think I will be able to isolate it and have a simple sample soon .... > > Random guess: change the execfile() call to > > execfile(filename, globals()) > > or > > exec file(filename).read() That is unlikely to help. The execfile target seems to have been TU_05_010.py, but the file which cannot access math is TU_05_tools.py accessed by a normal import, so adding some globals to the execfile call won't really do anything useful. Isn't it fun trying to guess the problem in the absence of the code? From khemkaamit at gmail.com Tue Nov 22 07:18:26 2005 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 22 Nov 2005 17:48:26 +0530 Subject: matching a string to extract substrings for which some function returns true In-Reply-To: References: Message-ID: <1360b7230511220418q6ede018bhcd80655f8a4f1530@mail.gmail.com> Well actually the problem is I have a list of tuples which i cast as string and then put in a html page as the value of a hidden variable. And when i get the string again, i want to cast it back as list of tuples: ex: input: "('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), ('foo2', 2, 'foobar2', (3, 2))" output: [('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), ('foo2', 2, 'foobar2', (3, 2))] I hope that explains it better... cheers, On 11/22/05, Steven D'Aprano wrote: > On Tue, 22 Nov 2005 16:57:41 +0530, Amit Khemka wrote: > > > Hello All, > > > > say you have some string: "['a', 'b', 1], foobar ['d', 4, ('a', 'e')]" > > Now i want to extract all substrings for which > > "isinstance(eval(substr), list)" is "True" . > > That's an awfully open-ended question. Is there some sort of structure to > the string? What defines a substring? What should you get if you extract > from this string? > > "[[[[[]]]]]" > > Is that one list or five? > > > > now one way is to walk through the whole sample string and check the > > condition, > > Yes. Where does the string come from? Can a hostile user pass bad strings > to you and crash your code? > > > -- > Steven. > > -- > 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 steveha at localhost.localdomain Tue Nov 22 19:08:41 2005 From: steveha at localhost.localdomain (Steve R. Hastings) Date: Tue, 22 Nov 2005 16:08:41 -0800 Subject: user-defined operators: a very modest proposal References: Message-ID: > if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation' > Since it contains ']+[' I assume it must now be parsed as a user-defined > operator, but this code currently has a meaning in Python. Yes. I agree that this is a fatal flaw in my suggestion. Perhaps there is no syntax that can be done inside the bounds of ASCII that will please everyone and not break existing code. Your suggestion of Unicode makes a lot of sense. There are glyphs for math operators, and if Python can accept Unicode source files, that seems to me like a much better solution than hacks involving ASCII characters. I didn't notice it before, but PEP 263 allows Python source files to be Unicode: http://www.python.org/peps/pep-0263.html So the latest versions of Python already have support for Unicode source files! Could such Unicode sources be exported to ASCII for porting code to platforms that don't allow Unicode Python files? Yes: just replace the Unicode character with a symbol like __op__, where op is the operator. Actually, that's a better syntax than the one I proposed, too: __+__ # __add__ # this one's already in use, so not allowed __outer*__ -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From amk at amk.ca Wed Nov 9 08:39:56 2005 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 9 Nov 2005 08:39:56 -0500 Subject: PyCon 2006 Call for Tutorials Message-ID: <20051109133956.GB26994@rogue.amk.ca> PyCon 2006 Call for Tutorials ------------------------------------------ Enjoy teaching classes or tutorials? PyCon 2006 is looking for proposals for a pre-conference tutorials day. PyCon 2006 will be held February 24-26 in Addison, Texas (near Dallas). Tutorials will be held on February 23, at the same location. Tutorial sessions will be a half day (3 hours, with a 15-minute break); presenters may request two sessions in order to make up a full day. Tutorials may be on any topic, but obviously should be instructional in nature. Providing take-home materials for attendees is encouraged, and tutorial presenters will receive $50 per student registered for theirsession (with a minimum payment of $500, and a maximum of $1500). Extra consideration will be given to presenters with prior experience teaching classes or giving conference tutorials. Please provide one reference or evidence of such prior experience (sessions taught at OSCON, EuroPython, local user groups, etc.). PyCon attendees will register for tutorials. We reserve the right to cancel tutorials with low attendance; presenters will not be paid for cancelled tutorials. Example tutorial topics can be found at: http://us.pycon.org/TX2006/Tutorials Important Dates =============== * Submission deadline: November 15, 2005 * Acceptance deadline: November 22, 2005 * Cancellation date: January 15, 2006 (for inadequate attendance) Submission Format ================================ Proposals should be 250 to 1000 words long (i.e., one to four pages in manuscript format), containing the following information: * Author name(s) * Contact Information * (Recommended) At least one previous presentation/teaching engagement reference * Summary of proposed presentation * Presentation outline * Intended audience (non-programmers, beginning programmers, advanced users, CPython developers, etc.) E-mail your proposal to . ASCII format is preferred (plain or reST), with HTML as a secondary alternative. If you have any questions about submission, please send mail to the conference organizers at pycon at python.org. From bignose+hates-spam at benfinney.id.au Sun Nov 20 16:34:17 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 21 Nov 2005 08:34:17 +1100 (EST) Subject: Why are there no ordered dictionaries? References: Message-ID: [restored my attribution line so we know who said what] Christoph Zwerschke wrote: > Ben Finney wrote: > > In what cases do you find yourself needing a dict that preserves > > its key order? Can you present a use case that would be improved > > by an ordered dict? > > There are too many different situations and it would be too much to > explain them here, usually in the case mentioned above where the > keys are not sorted alphabetically. Without an example, it's hard to know what you want to do and whether an ordered dictionary is the best way to do it. > > For my part, I consider it a virtue of Python that the standard > > library doesn't change rapidly. It allows many competing > > implementations to be shaken out before everyone starts depending > > on any one of them. > > Ok, but this can be used as an argument to not add anything to the > standard lib any more. I hope not. Rather, it's an argument not to add something to the standard library until it's proven (to the BDFL's criteria) that it's better in than out. > There are already enough competing > implementations. Have they been sufficiently shaken out to show a clearly superior version? Is any version sufficiently beneficial to write a PEP for its inclusion in the standard library? > I simply wanted to ask why it is not available in the standard lib, > since I simply don't know > > - has it not been demanded loud enough? Loud demands don't count for much. PEPs with popular working implementations do. > - is it really not needed (if you need it it shows you are doing > something wrong)? You dismissed a request for your use cases with handwaving. How can we know? > - because nobody presented a satisfying implementation yet? I'm not sure what you mean by "satisfying". > - are there hidden difficulties or controversial issues? Another possibility: ordered dictionaries are not needed when Python 2.4 has the 'sorted' builtin. -- \ "Those who will not reason, are bigots, those who cannot, are | `\ fools, and those who dare not, are slaves." -- "Lord" George | _o__) Gordon Noel Byron | Ben Finney From lycka at carmen.se Wed Nov 23 06:03:29 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 23 Nov 2005 12:03:29 +0100 Subject: Hot to split string literals that will across two or more lines ? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > cursor.execute( > 'select * from foo' > ' where bar=%s' > ' limit 100', > bar > ) The disavantage with this is that it's easy to make a mistake, like this... cursor.execute( 'select * from foo ' 'where bar=%s' 'limit 100', bar ) That might be a reason to prefer triple quoting instead: cursor.execute( '''select * from foo where bar=%s limit 100''', bar ) This last version will obviously contain some extra whitespace in the SQL text, and that could possibly have performance implications, but in general, I prefer to reduce the risk of errors (and I've made mistakes with missing spaces in adjacent string literals). From tony.meyer at gmail.com Mon Nov 21 00:17:38 2005 From: tony.meyer at gmail.com (Tony Meyer) Date: Mon, 21 Nov 2005 18:17:38 +1300 Subject: python-dev Summary for 2005-10-01 through 2005-10-15 Message-ID: <6c63de570511202117o75ce3b66l148945ad29e0ee82@mail.gmail.com> Title: python-dev Summary for 2005-10-01 through 2005-10-15 Content-type: text/x-rst Encoding: utf-8 python-dev Summary for 2005-10-01 through 2005-10-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2005-10-01_2005-10-15.html] ============= Announcements ============= ---------------------------- QOTF: Quote of the Fortnight ---------------------------- >From Phillip J. Eby: So, if threads are "easy" in Python compared to other langauges, it's *because of* the GIL, not in spite of it. Contributing thread: - `Pythonic concurrency < http://mail.python.org/pipermail/python-dev/2005-October/057062.html>`__ [SJB] ---------------------------------------- GCC/G++ Issues on Linux: Patch available ---------------------------------------- Christoph Ludwig provided the previously `promised patch`_ to address some of the issues in compiling Python with GCC/G++ on Linux. The patch_ keeps ELF systems like x86 / Linux from having any dependencies on the C++ runtime, and allows systems that require main() to be a C++ function to be configured appropriately. .. _promised patch: http://www.python.org/dev/summary/2005-07-01_2005-07-15.html#gcc-g-issues-on-linux .. _patch: http://python.org/sf/1324762 Contributing thread: - `[C++-sig] GCC version compatibility < http://mail.python.org/pipermail/python-dev/2005-October/057230.html>`__ [SJB] ========= Summaries ========= --------------------- Concurrency in Python --------------------- Michael Sparks spent a bit of time descibing the current state and future goals of the Kamaelia_ project. Mainly, Kamaelia aims to make concurrency as simple and easy to use as possible. A scheduler manages a set of generators that communicate with each other through Queues. The long term goals include being able to farm the various generators off into thread or processes as needed, so that whether your concurrency model is cooperative, threaded or process-based, your code can basically look the same. There was also continued discussion about how "easy" threads are. Shane Hathaway made the point that it's actually locking that's "insanely difficult", and approaches that simplify how much you need to think about locking can keep threading relatively easy -- this was one of the strong points of ZODB. A fairly large camp also got behind the claim that threads are easy if you're limited to only message passing. There were also a few comments about how Python makes threading easier, e.g. through the GIL (see `QOTF: Quote of the Fortnight`_) and through threading.threads's encapsulation of thread-local resources as instance attributes. .. _Kamaelia: http://kamaelia.sourceforge.ne Contributing threads: - `Pythonic concurrency - cooperative MT < http://mail.python.org/pipermail/python-dev/2005-October/056898.html>`__ - `Pythonic concurrency < http://mail.python.org/pipermail/python-dev/2005-October/057023.html>`__ [SJB] ------------------------------------- Organization of modules for threading ------------------------------------- A few people took issue with the current organization of the threading modules into Queue, thread and threading. Guido views Queue as an application of threading, so putting it in the threading module is inappropriate (though with a deeper package structure, it should definitely be a sibling). Nick Coghlan suggested that Queue should be in a threadtools module (in parallel with itertools), while Skip proposed a hierarchy of modules with thread and lock being in the lowest level one, and Thread and Queue being in the highest level. Aahz suggested (and Guido approved) deprecating the thread module and renaming it to _thread at least in Python 3.0. It seems the deprecation may happen sooner though. Contributing threads: - `Making Queue.Queue easier to use < http://mail.python.org/pipermail/python-dev/2005-October/057184.html>`__ - `Autoloading? (Making Queue.Queue easier to use) < http://mail.python.org/pipermail/python-dev/2005-October/057216.html>`__ - `threadtools (was Re: Autoloading? (Making Queue.Queue easier to use)) < http://mail.python.org/pipermail/python-dev/2005-October/057262.html>`__ - `Threading and synchronization primitives < http://mail.python.org/pipermail/python-dev/2005-October/057269.html>`__ [SJB] ------------------------- Speed of Unicode decoding ------------------------- Tony Nelson found that decoding with a codec like mac-roman or iso8859-1 can take around ten times as long as decoding with utf-8. Walter D?rwald provided a patch_ that implements the mapping using a unicode string of length 256 where undefined characters are mapped to u"\ufffd". This dropped the decode time for mac-roman to nearly the speed of the utf-8 decoding. Hye-Shik Chang showed off a fastmap decoder with comparable performance. In the end, Walter's patch was accepted. .. patch: http://www.python.org/sf/1313939 Contributing thread: - `Unicode charmap decoders slow < http://mail.python.org/pipermail/python-dev/2005-October/056958.html>`__ [SJB] ------------------ Updates to PEP 343 ------------------ Jason Orendorff proposed replacing the __enter__() and __exit__() methods on context managers with a simple __with__() method instead. While Guido was unconvinced that __enter__() and __exit__() should be dropped, he was convinced that context managers should have a __with__() method in parallel with the __iter__() method for iterators. There was some talk of special-casing the @contextmanager decorator on the __with__() method, but no conclusion. Contributing threads: - `Proposed changes to PEP 343 < http://mail.python.org/pipermail/python-dev/2005-October/057040.html>`__ - `PEP 343 and __with__ < http://mail.python.org/pipermail/python-dev/2005-October/056931.html>`__ [SJB] ---------------------- str and unicode issues ---------------------- Martin Blais wanted to completely disable the implicit conversions between unicode and str, so that you would always be forced to call either .encode() or .decode() to convert between one and the other. This is already available through adding ``sys.setdefaultencoding('undefined')`` to your sitecustomize.py file, but the suggestion started another long discussion over unicode issues. Antoine Pitrou suggested that a good rule of thumb is to convert to unicode everything that is semantically textual, and to only use str for what is to be semantically treated as a string of bytes. Fredrik Lundh argued against this for efficiency reasons -- pure ASCII text would consume more space as a unicode object. There were suggestions that in Python 3.0, opening files in text mode will require an encoding and produce string objects, while opening files in binary mode will produce bytes objects. The bytes() type will be a mutable array of bytes, which can be converted to a string object by specifying an encoding. Contributing threads: - `Divorcing str and unicode (no more implicit conversions). < http://mail.python.org/pipermail/python-dev/2005-October/056916.html>`__ - `unifying str and unicode < http://mail.python.org/pipermail/python-dev/2005-October/056934.html>`__ - `bytes type < http://mail.python.org/pipermail/python-dev/2005-October/056945.html>`__ [SJB] ---------------------------------------------------------------------- Allowing \*args syntax in tuple unpacking and before keyword arguments ---------------------------------------------------------------------- Gustavo Niemeyer propsed the oft-seen request for allowing the \*args syntax in tuple unpacking, e.g.:: for first, second, *rest in iterator: Guido requested a PEP, saying that he wasn't convinced that there was much of a gain over the already valid:: for item in iterator: (first, second), rest = item[2:], item[:2] Greg Ewing and others didn't like Guido's suggestion as it violates DRY (Don't Repeat Yourself). Others also chimed in with some examples in support of the proposal, but no one has yet put together a PEP. In a related matter, Guido indicated that he wants to be able to write keyword-only arguments after a \*args, so that you could, for example, write:: f(a, b, *args, foo=1, bar=2, **kwds) People seemed almost unanimously in support of this proposal, but, to quote Nick Coghlan, it has still "never bugged anyone enough for them to actaully get around to fixing it". Contributing thread: - `Extending tuple unpacking < http://mail.python.org/pipermail/python-dev/2005-October/057056.html>`__ [SJB] ---------- AST Branch ---------- Guido gave the AST branch a three week ultimatum: either the branch should be merged into MAIN within the next three weeks, or the branch should be abandoned entirely. This jump-started work on the branch, and the team was hoping to merge the changes the weekend of October 15th. Contributing threads: - `Python 2.5a1, ast-branch and PEP 342 and 343 < http://mail.python.org/pipermail/python-dev/2005-September/056449.html>`__ - `Python 2.5 and ast-branch < http://mail.python.org/pipermail/python-dev/2005-October/056986.html>`__ - `AST branch update < http://mail.python.org/pipermail/python-dev/2005-October/057281.html>`__ [SJB] ----------------------------------- Allowing "return obj" in generators ----------------------------------- Piet Delport suggested having ``return obj`` in generators be translated into ``raise StopIteration(obj)``. The return value of a generator function would thus be available as the first arg in the StopIteration exception. Guido asked for some examples to give the idea a better motivation, and felt uncomfortable with the return value being silently ignored in for-loops. The idea was postponed until at least one release after a PEP 342 implementation enters Python, so that people can have some more experience with coroutines. Contributing threads: - `Proposal for 2.5: Returning values from PEP 342 enhanced generators < http://mail.python.org/pipermail/python-dev/2005-October/056957.html>`__ - `PEP 342 suggestion: start(), __call__() and unwind_call() methods < http://mail.python.org/pipermail/python-dev/2005-October/057042.html>`__ - `New PEP 342 suggestion: result() and allow "return with arguments" in generators (was Re: PEP 342 suggestion: start(), __call__() and unwind_call() methods) < http://mail.python.org/pipermail/python-dev/2005-October/057116.html>`__ [SJB] ----------------------------- API for the line-number table ----------------------------- Greg Ewing suggested trying to simplify the line-number table (lnotab) by simply matching each byte-code index with a file and line number. Phillip J. Eby pointed out that this would make the stdlib take up an extra megabyte, suggesting two tables instead, one matching bytecodes to line numbers, and one matching the first line-number of a chunk with its file. Michael Hudson suggested that what we really want is an API for accessing the lnotab, so that the implementation that is chosen is less important. The conversation trailed off without a resolution. Contributing thread: - `Simplify lnotab? (AST branch update) < http://mail.python.org/pipermail/python-dev/2005-October/057285.html>`__ [SJB] ------------------------------ Current directory and sys.path ------------------------------ A question about the status of `the CurrentVersion registry entry`_ led to a discussion about the different behaviors of sys.path across platforms. Apparently, on Windows, sys.path includes the current directory and the directory of the script being executed, while on Linux, it only includes the directory of the script. .. _the CurrentVersion registry entry: http://www.python.org/windows/python/registry.html Contributing thread: - `PythonCore\CurrentVersion < http://mail.python.org/pipermail/python-dev/2005-October/057095.html>`__ [SJB] ---------------------------------- Changing the __class__ of builtins ---------------------------------- As of Python 2.3, you can no longer change the __class__ of any builtin. Phillip J. Eby suggested that these rules might be overly strict; modules and other mutable objects could probably reasonably have their __class__s changed. No one seemed really opposed to the idea, but no one offered up a patch to make the change either. Contributing thread: - `Assignment to __class__ of module? (Autoloading? (Making Queue.Queueeasier to use)) < http://mail.python.org/pipermail/python-dev/2005-October/057253.html>`__ [SJB] ------------------------------------------ exec function specification for Python 3.0 ------------------------------------------ In Python 3.0, exec is slated to become a function (instead of a statement). Currently, the presence of an exec statement in a function can cause some subtle changes since Python has to worry about exec modifying function locals. Guido suggested that the exec() function could require a namespace, basically dumping the exec-in-local-namespace altogether. People seemed generally in favor of the proposal, though no official specification was established. Contributing thread: - `PEP 3000 and exec < http://mail.python.org/pipermail/python-dev/2005-October/057135.html>`__ [SJB] ------------------------------------ Adding opcodes to speed up self.attr ------------------------------------ Phillip J. Eby experimented with adding LOAD_SELF and SELF_ATTR opcodes to improve the speed of object-oriented programming. This gained about a 5% improvement in pystone, which isn't organized in a very OO manner. People seemed uncertain as to whether paying the cost of adding two opcodes to gain a 5% speedup was worth it. No decision had been made at the time of this summary. Contributing thread: - `LOAD_SELF and SELF_ATTR opcodes < http://mail.python.org/pipermail/python-dev/2005-October/057321.html>`__ [SJB] -------------------------------------- Dropping support for --disable-unicode -------------------------------------- Reinhold Birkenfeld tried unsuccessfully to make the test-suite pass with --disable-unicode set. M.-A. Lemburg suggested that the feature should be ripped out entirely, to simplify the code. Martin v. L?wis suggested deprecating it to give people a chance to object. The plan is now to add a note to the configure switch that the feature will be removed in Python 2.6. Contributing threads: - `Tests and unicode < http://mail.python.org/pipermail/python-dev/2005-October/056897.html>`__ - `--disable-unicode (Tests and unicode) < http://mail.python.org/pipermail/python-dev/2005-October/056920.html>`__ [SJB] ----------------------------------------- Bug in __getitem__ inheritance at C level ----------------------------------------- Travis Oliphant discovered that the addition of the mp_item and sq_item descriptors and the resolution of any comptetion for __getitem__ calls is done *before* the inheritance of any slots takes place. This means that if you create a type in C that supports the sequence protocol, and tries to inherit the mapping protocol from a parent C type which does not support the sequence protocol, __getitem__ will point to the parent type's __getitem__ instead of the child type's __getitem__. This seemed like more of a bug than a feature, so the behavior may be changed in future Pythons. Contributing thread: - `Why does __getitem__ slot of builtin call sequence methods first? < http://mail.python.org/pipermail/python-dev/2005-October/056901.html>`__ [SJB] ================ Deferred Threads ================ - `Early PEP draft (For Python 3000?) < http://mail.python.org/pipermail/python-dev/2005-October/057251.html>`__ - `Pythonic concurrency - offtopic < http://mail.python.org/pipermail/python-dev/2005-October/057294.html>`__ =============== Skipped Threads =============== - `PEP 350: Codetags < http://mail.python.org/pipermail/python-dev/2005-October/056894.html>`__ - `Active Objects in Python < http://mail.python.org/pipermail/python-dev/2005-October/056896.html>`__ - `IDLE development < http://mail.python.org/pipermail/python-dev/2005-October/056907.html>`__ - `Help needed with MSI permissions < http://mail.python.org/pipermail/python-dev/2005-October/056908.html>`__ - `C API doc fix < http://mail.python.org/pipermail/python-dev/2005-October/056910.html>`__ - `Static builds on Windows (continued) < http://mail.python.org/pipermail/python-dev/2005-October/056976.html>`__ - `Removing the block stack (was Re: PEP 343 and __with__) < http://mail.python.org/pipermail/python-dev/2005-October/057001.html>`__ - `Removing the block stack < http://mail.python.org/pipermail/python-dev/2005-October/057008.html>`__ - `Lexical analysis and NEWLINE tokens < http://mail.python.org/pipermail/python-dev/2005-October/057014.html>`__ - `PyObject_Init documentation < http://mail.python.org/pipermail/python-dev/2005-October/057039.html>`__ - `Sourceforge CVS access < http://mail.python.org/pipermail/python-dev/2005-October/057051.html>`__ - `__doc__ behavior in class definitions < http://mail.python.org/pipermail/python-dev/2005-October/057066.html>`__ - `Sandboxed Threads in Python < http://mail.python.org/pipermail/python-dev/2005-October/057082.html>`__ - `Weekly Python Patch/Bug Summary < http://mail.python.org/pipermail/python-dev/2005-October/057092.html>`__ - `test_cmd_line failure on Kubuntu 5.10 with GCC 4.0 < http://mail.python.org/pipermail/python-dev/2005-October/057094.html>`__ - `defaultproperty (was: Re: RFC: readproperty) < http://mail.python.org/pipermail/python-dev/2005-October/057120.html>`__ - `async IO and helper threads < http://mail.python.org/pipermail/python-dev/2005-October/057121.html>`__ - `defaultproperty < http://mail.python.org/pipermail/python-dev/2005-October/057129.html>`__ - `Fwd: defaultproperty < http://mail.python.org/pipermail/python-dev/2005-October/057131.html>`__ - `C.E.R. Thoughts < http://mail.python.org/pipermail/python-dev/2005-October/057137.html>`__ - `problem with genexp < http://mail.python.org/pipermail/python-dev/2005-October/057175.html>`__ - `Python-Dev Digest, Vol 27, Issue 44 < http://mail.python.org/pipermail/python-dev/2005-October/057207.html>`__ - `Europeans attention please! < http://mail.python.org/pipermail/python-dev/2005-October/057233.html>`__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from October 01, 2005 through October 15, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the 5th summary written by the python-dev summary taskforce of Steve Bethard and Tony Meyer (thanks Steve!). To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com ) - Tony Meyer (tony.meyer at gmail.com ) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/2005-09-01_2005-09-15.html .. _original text file: http://www.python.org/dev/summary/2005-10-01_2005-10-15.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf -------------- next part -------------- An HTML attachment was scrubbed... URL: From sw at wordtech-software.com Wed Nov 23 08:44:52 2005 From: sw at wordtech-software.com (Kevin Walzer) Date: Wed, 23 Nov 2005 08:44:52 -0500 Subject: Mac OSX oddities (compiling Python plus tkinter) In-Reply-To: <1132729971.363701.153440@o13g2000cwo.googlegroups.com> References: <1132729971.363701.153440@o13g2000cwo.googlegroups.com> Message-ID: <43847254.8050409@wordtech-software.com> MichaelW wrote: > I've been Python (2.3.4) plus Tkinter happily under MacOX 10.3, having > compiled them from scatch. (Tkinter is based on tcl/tk 8.4.1, which > were compiled from source via Fink). > > I then moved my laptop over the 10.4, and things are now breaking. > Using the Python shipped with 10.4 (which has Tkinter based on tcl/tk > 8.4.7) the window in a particular application looks completely > different (more Apple-like) and the buttons no longer work properly. > (Oddly, some icons have fallen off the buttons.) I therefore thought I > might compile Python from scratch and that fell over with messages: > > sem_init: Function not implemented > sem_wait: Bad file descriptor > sem_post: Bad file descriptor > > reported at intervals. I assume the odd Tkinter behaviour is due to > problems Apple created Apple-ising it? Is that correct, or has there > been a major change to the API between 8,4 and 8.7?. Is there any > work-around? Secondly, can I assume that the compiler messages indicate > a problem with the compiler (gcc select 3.3 makes no difference, BTW). > > Your ideas would be appreciated. > > Cheers > MichaelW > There were not huge changes between Tk 8.4.1 and 8.4.7. However, if you were using Tk from Fink before and now are using the Apple version of Tk, that may account for the difference. Tk from Fink is targeted for X11, while the Apple-installed Tk is targeted to the Aqua windowing environment. Tk itself is portable, but some of the extension packages for it (such as BLT, and presumably any Pythonesque wrappers for them) do not work on Aqua. Similarly, some bugs have arisen in Aqua's implementation of Tk (pixmaps do not display in menus, tearoff menus do not work properly), etc. Also, did you compile Python as a Carbon framework build (makes use of the Apple's windowing environment)? What version are you now running? -- Cheers, Kevin Walzer, PhD WordTech Software - "Tame the Terminal" http://www.wordtech-software.com sw at wordtech-software.com From bearophileHUGS at lycos.com Wed Nov 30 10:24:16 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 30 Nov 2005 07:24:16 -0800 Subject: Computer Language Shootout In-Reply-To: <1133337250.062705.80240@g44g2000cwa.googlegroups.com> References: <1133298307.938958.186070@f14g2000cwb.googlegroups.com> <1133299669.010298.283100@g14g2000cwa.googlegroups.com> <1133337250.062705.80240@g44g2000cwa.googlegroups.com> Message-ID: <1133364256.422459.202840@z14g2000cwz.googlegroups.com> malv: >Hi bearophileH, bearophile is enough :-) >Could you post some more information about ShedSkink? ShedSkin (SS) is a Python -> C++ compiler (or translator) written in Python, created by Mark Dufour. Its development was initially "financed" by the summer of code by Google. It contains some smart algorithms that allow it to infer the type of most variables, and to compile everything statically (but with a garbage collector). This produces a very fast executable, usually like a C++ one. SS has some limits, some of them are temporary, and some of them are here to stay (it cannot be used on really dynamic stuff). It's not intended to compile every Python program, but mostly for "algorithmic" code that has to go fast, often the same code Psyco is used for. It can be seen as complementary to Psyco, and not really like something to substitute it, Psyco is a very good software. I am helping Mark as I can, in different ways, because I think SS is a very interesting software. At the moment SS is in the Alpha stage still, this means: - It has a lot of bugs still, but Mark fixes some of them almost every week. That problem in that fannkuch code is relative to the version 0.0.5, a successive version may compile it correctly. - Some common things aren't possible yet, like inheritance, but Mark is probably going to implement this in the following days. - The code produced is C++, and it calls functions of the SS library. CPython source code contains some very fast routines (by Raymond Hettinger and other people), so sometimes CPython is faster (example: sometimes Python dicts are faster). This is mostly a "tuning/implementation" problem, it's not a limit of SS or the C++ and its compiler. It's a matter of knowing lot of complex C++ "tricks" and implementing/copying faster routines. Another developer can probably help Mark improve most of those algorithms (I think that sometimes the CPython source code itself may be adapted and used). - If another developer helps Mark, a future version of SS can probably be used to automatically produce compiled modules that can be imported into normal Python programs (it may call something like SIP/SWIG by itself), a very simple single-click command can be used (on Windows in a contex menu). The info about the input types of the functions/methods may be expressed with some very simple syntax inside the module docstring, or simply it may be contained in the part of the module that isn't executed when then module is called. - There are lot of ways to improve SS still, some people in the Blender group have already shown interest in SS, but it contains too much bugs still to be used in serious projects. Helping hands can speed up its development a lot. The project on Sourceforge, it contains more information and documentation: http://sourceforge.net/projects/shedskin/ SS blog: http://shed-skin.blogspot.com/ The last version is 0.0.5.1, it contains an important memory bugfix and other minor bugfixings. Some timings for version 0.0.5: http://sourceforge.net/mailarchive/forum.php?thread_id=9040577&forum_id=46397 (small_dict_fp test is probably faster in version 0.0.5.1). Bear hugs, bearophile From fredrik at pythonware.com Wed Nov 16 16:29:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 22:29:48 +0100 Subject: subprocess terminate help References: <1132175068.069738.299430@o13g2000cwo.googlegroups.com> Message-ID: Ernesto wrote > I've been searching for ways to terminate this process so I can exit my > program. program.exe is a text based interface which I'm running with > python subprocess in a DOS command window. I tried using 'sys.exit()' > to end my program, but nothing works. I think I have to somehow > terminate the subprocesses I create. Any suggestions? someone calling himself "Ernesto" posted this link yesterday: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462 From claudio.grondi at freenet.de Wed Nov 16 14:34:28 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 16 Nov 2005 19:34:28 -0000 Subject: newbie - How do I import automatically? References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> <3u0el9Fum367U1@individual.net> <1132154531.395649.168870@g14g2000cwa.googlegroups.com> Message-ID: <3u1ce5Fv1b5jU1@individual.net> schrieb im Newsbeitrag news:<1132154531.395649.168870 at g14g2000cwa.googlegroups.com>... > I tried to put the line > from btools import * > in several places in PyShell.py > but to now avail. It does not work, IDLE does not execute it??? > Bob I have to give up here :-( . The best solution I am able to come up with is: def runsource(self, source): if(source == ''): source = 'from btools import *' "Extend base class method: Stuff the source in the line cache first" filename = self.stuffsource(source) which performs 'from btools import *' each time you hit return on the command line without typing anything in the interpreter. Maybe someone knowledgable in IDLE can share here a better way how to initialize IDLE with any code valid in the interpreter itself. Inbetween the above can maybe serve as workaround. Claudio From jaco at neottia.net Sun Nov 13 16:52:28 2005 From: jaco at neottia.net (Eric Jacoboni) Date: Sun, 13 Nov 2005 22:52:28 +0100 Subject: strip not working on strings? References: <1131916607.467166.207550@g14g2000cwa.googlegroups.com> Message-ID: In article <1131916607.467166.207550 at g14g2000cwa.googlegroups.com>, dan.j.weber at gmail.com wrote: > I'm using Python 2.3.5 and when I type the following in the interactive > prompt I see that strip() is not working as advertised: > > >>>s = 'p p:p' > >>>s.strip(' :') > 'p p:p' > > Is this just me or does it not work? I want to get rid of all ' ' and > ':' in the string. I've checked the doc and from what I can tell this > is what strip() is supposed to do. In /my/ docs, s.strip return a copy of s where all /leading/ and /heading/ spaces are removed. s.strip(x) does the same but removing chars of x. So, what you're asking for by s.strip(' :') is "remove heading or leading space or ':' chars", /not/ "remove space or ':' chars". If you want to get rid of ' ' and ':' anywhere in s, i think that string.maketrans and s.translate will do the job: >>> import string >>> s = 'p p:p' >>> ident = string.maketrans('', '') >>> s.translate(ident,' :') 'ppp' -- Jaco From briot at nospam.fr.invalid Fri Nov 25 08:08:13 2005 From: briot at nospam.fr.invalid (Emmanuel Briot) Date: Fri, 25 Nov 2005 14:08:13 +0100 Subject: Singleton and C extensions Message-ID: <43870caf$0$17254$4d4eb98e@read.news.fr.uu.net> I am participating in the development of a GPL IDE https://libre2.adacore.com/gps/ It is written in Ada, but provides an extensive extensibility through Python. I am not really good at python, but I was trying to implement the singleton design pattern in C, so that for instance calling the constructor ed = Editor ("foo") would either return an existing instance of Editor currently editing "foo", or would create a new instance. Basically, one python instance is stored inside each of the visual windows representing an editor, and I want to get that instance if it already exists, instead of creating a new one each time. I basically would like ed = Editor ("foo") ed.attribute = "whatever" print Editor ("foo").attribute to print "whatever" Has any one an example on how to do that in C, or maybe even at the python level itself, and I will try to adapt it ? Thanks in advance Emmanuel From sszmidt at netwvcom.com Fri Nov 25 18:41:25 2005 From: sszmidt at netwvcom.com (sszmidt at netwvcom.com) Date: Fri, 25 Nov 2005 18:41:25 -0500 Subject: vb2py question Message-ID: <200511251841.25970.sszmidt@netwvcom.com> Hi, Has anyone looked at or used vb2py lately? I'm looking at doing some conversion work and it's awfully out of date. Any other information on the subject would be welcome. -- Steve From cito at online.de Sun Nov 20 16:19:55 2005 From: cito at online.de (Christoph Zwerschke) Date: Sun, 20 Nov 2005 22:19:55 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com schrieb: > By ordered dict, one usually wants order that is arbitary which cannot > be derived from the content, say insertion order(most ordered dict I > saw use this order). > I am writing a web applications(simple forms) which has a number of > fields. Each field naturally has a name and a number of > attributes(formatting etc.), like this : > d = {'a':{...}, 'b':{....}} Things like that are also my typical use case. The keys usually contain things like database fields or html form fields, the values contain the corresponding description, formatting, data type or data itself etc. The example above is a bit misleading, because using 'a', 'b' as keys can give the impression that you just have to sort() the keys to have what you want. So let's make it more realistic: d = { 'pid': ('Employee ID', 'int'), 'name': ('Employee name', 'varchar'), 'sal': ('Salary', 'float') } Now if I want these things to be presented in this order, I need to run through a separate list ('pid', 'name', 'sal') that holds the order. Ok, you could simply use a list instead of a dictionary: d = ( ('pid', 'Employee ID', 'int'), ('name', 'Employee name', 'varchar'), ('sal', 'Salary', 'float') ) This works as long as you *only* have to go through the list sequentially. But maybe you want to print the name with its description at some other place as well. Now how do you access its description 'Employee name' so easily? -- Christoph From _karlo_ at _mosor.net_ Tue Nov 1 12:22:02 2005 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Tue, 1 Nov 2005 17:22:02 +0000 (UTC) Subject: Flat file, Python accessible database? Message-ID: I've been Googling around for _small_, flat file (no server processes), SQL-like database which can be easily access from Python. Speed and perforamnce are of no issue, most important is that all data is contained within single file and no server binary has to run in order to use the dbase. Oh, and I'm using Python under Cygwin. Ofcourse, ease of use and simplicity is most welcomed :). I'm currently playing around SQLite+PySQLite and BerkeleyDB, but those two seem like an overkill :(. Thanks in advance... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From webraviteja at gmail.com Sun Nov 20 16:58:59 2005 From: webraviteja at gmail.com (Ravi Teja) Date: 20 Nov 2005 13:58:59 -0800 Subject: Is Python weak on the web side? In-Reply-To: References: Message-ID: <1132523939.004057.107130@f14g2000cwb.googlegroups.com> Too many options. Google: python web frameworks The first couple of links will point you to enough resources. From roy at panix.com Thu Nov 24 10:17:45 2005 From: roy at panix.com (Roy Smith) Date: Thu, 24 Nov 2005 10:17:45 -0500 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> Message-ID: "bonono at gmail.com" wrote: > Interestingly, I just saw a thread over at TurboGears(or is it this > group, I forgot) about this multiple return issue and there are people > who religiously believe that a function can have only one exit point. > > def f(): > r = None > for i in range(20): > if i > 10: > r = 10 > break > if r is None: something > else: return r "Single entrance, single exit" is a philosophy (religion?) that's been around for a while. The basic thought is that every code block should have a single entrance and a single exit. Back in the dark old days of gotos, there was a lot of spaghetti code written with gotos jumping all over the place, even in and out of the middle of loops. Then, in 1968, Dijkstra wrote his famous "Go To Statement Considered Harmful" (http://www.acm.org/classics/oct95/) which spawned the whole structured programming concept, and SESE is the logical outgrowth of that. The problem with SESE is that if you follow it strictly, you end up with things like the example given above where you have to invent some temporary variable, and an extra test at the end of the loop. The cure is worse than the disease. In any case, in a language which has exceptions, it's almost impossible to really have true SESE, since an exception could be thrown from almost anywhere. To be fair, there are those who use this to argue that exceptions themselves are a bad thing. In my last job, the official style guide said to not use exceptions in C++ because they generate confusing flow of control, but I think that's becomming the minority view these days. From http Mon Nov 28 16:38:03 2005 From: http (Paul Rubin) Date: 28 Nov 2005 13:38:03 -0800 Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> <8664qcv6i5.fsf@bhuda.mired.org> <7x64qcii9o.fsf@ruckus.brouhaha.com> <1133213623.305032.232740@z14g2000cwz.googlegroups.com> Message-ID: <7xfypgh2ro.fsf@ruckus.brouhaha.com> "Paddy" writes: > I would consider > t = ([1,2], [3,4]) > to be assigning a tuple with two list elements to t. > The inner lists will be mutable but I did not know you could change the > outer tuple and still have the same tuple object. Whether t is mutable is a question of definitions. Either way, you can't hash t or use it as a dictionary key. From erchamion.beren at gmail.com Tue Nov 22 08:28:53 2005 From: erchamion.beren at gmail.com (Sinan Nalkaya) Date: Tue, 22 Nov 2005 15:28:53 +0200 Subject: need help about time.sleep, timer In-Reply-To: <43825861.411189609@news.oz.net> References: <8u6dnWAcZ69AAuPeRVn-gg@powergate.ca> <6gbtn1h9i8rvhf1gp1gg0aoludvlfhuop0@4ax.com> <43825861.411189609@news.oz.net> Message-ID: <43831D15.3000206@gmail.com> Bengt Richter wrote: >On Mon, 21 Nov 2005 10:35:20 +0200, Sinan Nalkaya wrote: > > > >>Dennis Lee Bieber wrote: >> >> >> >>>On Fri, 18 Nov 2005 22:45:37 -0500, Peter Hansen >>>declaimed the following in comp.lang.python: >>> >>> >>> >>> >>> >>>>It's quite unclear whether the last part, above, is one of your >>>>*requirements*, or a description of a problem you are having with your >>>>current approach. Do you *want* it to wait forever if you don't enter >>>>anthing? >>>> >>>> >>>> >>>> >>>> >>> As I understand it, he (?) wants to accumulate characters to be >>>passed to a certain function -- but the function is not to be invoked >>>until after a time period has expired; the time period resetting on each >>>character entered. >>> >>> Something I'd do with threads, queues, and sleep... >>> >>>PSEUDOCODE >>> >>>thread1: >>> while not Shutdown: >>> ch = getChar() >>> q.put(ch) >>> >>> >>>thread2: #or main >>> while not Shutdown: >>> chars = [] >>> while True: >>> sleep(max_interval) >>> if q.empty(): break #no input since start of sleep >>> while not q.empty(): #collect all input from sleep >>> chars.append(q.get()) >>> inp = "".join(chars) >>> function(inp) >>> >>> >>> >>> >>> >>> >>> >>i appreciate your comments and ideas. Dennis told exactly what i tried >>to say :), code seems to be fine but during sleep action i think the >>above code does not execute >> >>if q.empty(): break #no input since start of sleep >> while not q.empty(): >> chars.append(q.get()) >> >>i need something, while sleeping, executes the function that waits for >>input from keyboard. >>i imagined something like that, i have a queu, it both stores the keys >>that pressed and pressing times of these keys, then i`ll proccess these >>times. here is scenario >>input : 5 >>after 10 seconds later input 5 is being proccessed >>return back to main function >>input : 1 >>after 5 seconds , other input 5 >>after 5 more seconds , 15 is being proccessed >>Thanks. >> >> > >If I understand, you really don't want to sleep, you want to wait a max time of 5 seconds >for a character. You can get that from a queue.get(True,5) hence, you could try the >following as a start (untested, and I don't have much experience with python threading, >so will wait for bug reports ;-) > >Note that it uses getch for input, which doesn't echo. (Change to getche if you want echo) >You can run this from the command line with one arg: the number of seconds you want to >have the test continue. At the end of that time it will set the Shutdown event, and >thread2 should empty the queue and wait 5 seconds and then do its last function call and >see the shutdown event. > >----< tqinp.py >----------------------------------------------------------------------- ># tqinp.py -- test queued input of unechoed character input until a 5-second delay >import threading >import Queue >import msvcrt >queue = Queue.Queue(10) # 2 is prob enough for this thing >Shutdown = threading.Event() > >def getChar(): return msvcrt.getch() # blocks >def function(s): print 'function(%r)'%s > >def thread1(q): > while not Shutdown.isSet(): > ch = getChar() > q.put(ch) > >def thread2(q): #or main > while not Shutdown.isSet(): > chars = '' > try: > while True: chars += q.get(True, 5) > except Queue.Empty, e: > print 'No input for 5 seconds. Using %r'%chars > function(chars) > >import time >def test(trial_time): > thr1 = threading.Thread(target=thread1, args=(queue,)) > thr1.start() > thr2 = threading.Thread(target=thread2, args=(queue,)) > thr2.start() > t0 = time.clock() > time.sleep(trial_time) > print 'Ending trial after %s seconds' % (time.clock()-t0) > Shutdown.set() > >if __name__ == '__main__': > import sys > if not sys.argv[1:]: raise SystemExit,'Usage: python tqinp.py' > test(float(sys.argv[1])) >--------------------------------------------------------------------------------------- > >Ok, in the following I'll type 123 abc > >[ 5:40] C:\pywk\clp\threadstuff>py24 tqinp.py 15 >No input for 5 seconds. Using '123' >function('123') >No input for 5 seconds. Using 'abc' >function('abc') >Ending trial after 14.9948775627 seconds >No input for 5 seconds. Using '' >function('') > >[ 5:41] C:\pywk\clp\threadstuff> > >Except it didn't die until I hit another key to let thread1 loop and see its Shutdown test. >But this is alpha 0.01, so you can fix that various ways. Or maybe get the real requirements down ;-) >HTH >(once I get it posted -- news reads ok now but news server is not accepting posts. >I suspect they do system-hogging chores Sun night wee hours ;-/ > >Regards, >Bengt Richter > > thanks for all replies especially via with code ones ;) steve`s codes works perfectly except time part (ill look investigate it), i had to do little edit because i`m unix user and dont have msvcrt but no problem. also i am noticed that, i have to study on threading much as you said. thanks again. From fredrik at pythonware.com Sat Nov 19 08:57:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Nov 2005 14:57:07 +0100 Subject: what happens when the file begin read is too big for all lines to beread with "readlines()" References: <000b01c5ecf9$e3cc3530$a100a8c0@reyesr2> Message-ID: Ross Reyes wrote: > When I use readlines, what happens if the number of lines is huge? I have > a very big file (4GB) I want to read in, but I'm sure there must be some > limitation to readlines and I'd like to know how it is handled by python. readlines itself has no limitation, but it reads all the lines into memory, so you'll probably run out of memory before the call returns. Python raises a MemoryError exception when this happens. > I am using it like this: > slines = infile.readlines() # reads all lines into a list of strings called > "slines" as others have pointed out, an iterator is the best way to solve this. the iterator code will read blocks of data from the file, and return the lines one by one. if you need to support older versions of Python, xreadlines or repeated calls to readlines(N) can be useful (see the third example on this page for an example: http://effbot.org/zone/readline-performance.htm ) From not at valid.org Wed Nov 23 19:03:46 2005 From: not at valid.org (yomgui) Date: Wed, 23 Nov 2005 16:03:46 -0800 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> Message-ID: <43850362.95E1D6A1@valid.org> Mike Meyer wrote: > > yomgui writes: > > is it legal to return inside a for loop > > or am I obliged to break out of the loop before returning ? > > Try it and see: it is not because it does work on an implementation of python that it will work on any other platform or in the futur. yomgui From bkhl at stp.lingfil.uu.se Fri Nov 25 15:39:25 2005 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Fri, 25 Nov 2005 21:39:25 +0100 Subject: Which license should I use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> <863blkijjv.fsf@bhuda.mired.org> Message-ID: <87sltklawy.fsf_-_@lucien.dreaming> Mike Meyer writes: > IANAL, but I don't believe the GPL helps in this situation. It places > conditions on redistributing the code; it doesn't force you to > redistribute modifieed code. Your employers could refuse to let you > take the code with you because they own partial copyright on it. They > couldn't sell it later because of the GPL on it, but that's not your > issue here. If they have the rights to the code, they can sell it, under the GPL or any license of their choosing. In addition, if you GPL it, your employer will be able to sell it, just like anyone else. -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From rschroev_nospam_ml at fastmail.fm Thu Nov 24 09:34:53 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 24 Nov 2005 14:34:53 GMT Subject: Making immutable instances In-Reply-To: References: <0I6dncrRuNnuxBjeRVn-ig@comcast.com> Message-ID: Antoon Pardon wrote: > Op 2005-11-24, Mike schreef : >>and many a time. I've been annoyed (in Java and MS christelijke vorm er van. >>frameworks) Antoon, I don't think Mike wrote it like that :) I don't even know how I spotted that, since I didn't really read that part of the text. I guess the Dutch words caught my attention somehow. It even took a while for me to realize that it must have been an error; the first few seconds I was trying to find the relationship between christianity and Java, MS or frameworks. Without success, obviously. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From gnb at itga.com.au Wed Nov 16 01:04:18 2005 From: gnb at itga.com.au (Gregory Bond) Date: Wed, 16 Nov 2005 17:04:18 +1100 Subject: how to bypass firewall In-Reply-To: <1132107044.271546.185330@g43g2000cwa.googlegroups.com> References: <1132107044.271546.185330@g43g2000cwa.googlegroups.com> Message-ID: <25ield.ci.ln@lightning.itga.com.au> Parth wrote: > I need some help regrading byassing firewalls.My college has internet > aces but it prevents us from dowloading music(*.mp3,*.mid,etc.)from the > net. Hello everyone, I need help getting my college degree. I downloaded a hack to bypass the college internet firewall and the college system admins found out and I got expelled. From fredrik at pythonware.com Sat Nov 5 03:34:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 5 Nov 2005 09:34:07 +0100 Subject: re sub help References: <1131173343.954029.211530@o13g2000cwo.googlegroups.com><86br0z7e3w.fsf@bhuda.mired.org> <1131177215.248797.268670@f14g2000cwb.googlegroups.com> Message-ID: wrote: > i am still interested about using re, i find it useful. am still > learning it's uses. > so i did something like this for a start, trying to get everything in > between [startdelim] and [enddelim] > > a = > "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" > > t = re.compile(r"\[startdelim\](.*)\[enddelim\]") "*" is greedy (=searches backwards from the right end), so that won't do the right thing if you have multiple delimiters to fix this, use "*?" instead. > t.findall(a) > but it gives me []. it's the "\n" that prevents the results. > why can't (.*) work in this case? Or am i missing some steps to "read" > in the "\n"..? http://docs.python.org/lib/re-syntax.html (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline. to fix this, pass in re.DOTALL or re.S as the flag argument, or prepend (?s) to the expression. From kay.schluehr at gmx.net Mon Nov 21 14:53:43 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 21 Nov 2005 11:53:43 -0800 Subject: Why are there no ordered dictionaries? References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> Message-ID: <1132602823.072816.251210@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > huh? if you want a list, use a list. > > d = [('a', {...}), ('b', {....})] If one wants uniform access to a nested data structure like this one usually starts writing a wrapper class. I do not think the requirement is anyhow deeper than a standard wrapper around such a list ( as a model ) but the implementation may be different with respect to optimal time complexitiy of element access. But the interface of the wrapper class of d might resemble that of a dict. While the interface is that of a dict the implementation is closer to a nested list. An "ordered dict" would lower the impedance between a dict and a list. Kay From fredrik at pythonware.com Mon Nov 7 06:08:37 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 7 Nov 2005 12:08:37 +0100 Subject: can i tar and untar using python References: <1131361164.221810.95150@g43g2000cwa.googlegroups.com> Message-ID: "sumi" wrote: > can i tar and untar using python http://docs.python.org/lib/module-tarfile.html From deets at web.de Tue Nov 1 08:23:34 2005 From: deets at web.de (Diez B. Roggisch) Date: 1 Nov 2005 05:23:34 -0800 Subject: cx_Oracle, is anything selected? In-Reply-To: References: <3snp20Foku05U1@uni-berlin.de> Message-ID: <1130851414.048608.213990@g47g2000cwa.googlegroups.com> > > I don't understand your problem - if your select doesn't return > > anything, the fetch* methods on the cursor will tell you if there is any > > data to expect at all. Additionally there is teh rowcount-property that > > holds the number of rows the last execute* yielded. > > This is a simplification of the program > > c = db.cursor() > while 1: > c.execute('select ....') > smtp = SMTP(MAIL_HOST, 25, 'localhost') > for address, subject, body in c: > smtp.sendmail(....) > smtp.quit() > time.sleep(60) > > now if the select doesn't return any rows, there's no need to connect to the > mail server. I'd like to avoid that unnecessary step. > > c.rowcount will not give me the number of rows selected, it will only give > me the number of rows already fetched. then lazy-initialize the smpt object inside the loop. Or use c.fetchone for the first entry, and loop over the remaining results. Apart from that: what harm does the connection to the smpt do? If it works - keep it that way. Regards, Diez From aleax at mail.comcast.net Wed Nov 23 11:24:40 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 08:24:40 -0800 Subject: Why are there no ordered dictionaries? References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <1132531775.399671.93120@o13g2000cwo.googlegroups.com> <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383d564.508728452@news.oz.net> <1132735428.485669.153090@g43g2000cwa.googlegroups.com> Message-ID: <1h6h08u.5v642xndgfj2N%aleax@mail.comcast.net> Fuzzyman wrote: > There is already an update method of course. :-) > > Slicing an ordered dictionary is interesting - but how many people are > actually going to use it ? (What's your use case) I detest and abhor almost-sequences which can't be sliced (I consider that a defect of collections.deque). If the ordered dictionary records by its sequencing the time order of key insertion, being able to ask for "the last 5 keys entered" or "the first 3 keys entered" seem to me to be perfectly natural use cases, and most naturally accomplished by slicing of course, d[-5:] and d[:3] respectively. Alex From aleax at mail.comcast.net Thu Nov 24 13:42:53 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 24 Nov 2005 10:42:53 -0800 Subject: about sort and dictionary References: <1132493880.591426.224140@g49g2000cwa.googlegroups.com> <1132651818.348370.117450@g49g2000cwa.googlegroups.com> <1132653873.855348.265740@g47g2000cwa.googlegroups.com> <1132700747.794586.73170@g44g2000cwa.googlegroups.com> <1h6g1t6.qxc6tnag2skbN%aleax@mail.comcast.net> <1132719140.781847.251410@z14g2000cwz.googlegroups.com> <1h6gyxh.1bqns7v1lw2frwN%aleax@mail.comcast.net> <1h6iwje.127g54a1ltpvmfN%aleax@mail.comcast.net> Message-ID: <1h6j1fr.10qcqumwrgo1yN%aleax@mail.comcast.net> Magnus Lycka wrote: > Alex Martelli wrote: > > I don't think these headaches and difficulties justify dumping the whole > > field of reasoning about programs, nor the subfield of PbC. The concept > > of "immutable" is really just a tiny corner of these fields, and it's a > > long way from being the hardest or most problematic one in them;-). > > Agreed. I also think that it's good practice to make methods do *one* > thing, so when methods grow into both changing state and returning > some substantial value, I usually split them. While the distinction > between "functions" and "procedures" to speak Pascalese is a useful > guidline at times, it's still a generalization though, and I doubt > that it's very useful to have a syntactic marker for this distinction > such as e.g. Pascal has. The distinction is theoretically nice, but pragmatically it can get in your way when a result is a "natural side effect" of the state change. As a (perhaps overly) simple example, heapq.heapreplace is very natural for some use cases of heaps as priority queues, and frequent enough that having to replace it throughout with result = heapq.heappop... heapq.heappush... return result would be mildly annoying. At the other extreme, if Queue.Queue.get couldn't BOTH alter queue state (remove one item) AND return the removed item, within one threadsafe ("atomic") operation, that would be way more than just annoying... it would just about destroy the usefulness of Queue.Queue! Alex From didier.doussaud at gmail.com Tue Nov 29 06:57:51 2005 From: didier.doussaud at gmail.com (didier.doussaud at gmail.com) Date: 29 Nov 2005 03:57:51 -0800 Subject: Why I need to declare import as global in function In-Reply-To: References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> Message-ID: <1133265470.979764.157620@g14g2000cwa.googlegroups.com> the error message : EXCEPTION RAISED:: Traceback (most recent call last): File "../tu.py", line 21, in run_tu execfile( filename ) File "TU_05_010.py", line 8, in ? import TU_05_tools File "./TU_05_tools.py", line 4, in ? f() File "./TU_05_tools.py", line 2, in f print math.pi NameError: global name 'math' is not defined I have remarq that this problem is raised when I execute code in an imported module (during importation) I think I will be able to isolate it and have a simple sample soon .... From didier.doussaud at gmail.com Tue Nov 29 10:16:46 2005 From: didier.doussaud at gmail.com (didier.doussaud at gmail.com) Date: 29 Nov 2005 07:16:46 -0800 Subject: Why I need to declare import as global in function In-Reply-To: References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> <1133265470.979764.157620@g14g2000cwa.googlegroups.com> Message-ID: <1133277406.469703.58420@g49g2000cwa.googlegroups.com> You're right, the problem is around the usage of "execfile". But I have still difficulties to get a simple sample.... and have no enough time to work on it until end of week. I will post if I resolve my problem or if I can get a simple sample. From tim.tadh at gmail.com Mon Nov 28 00:31:03 2005 From: tim.tadh at gmail.com (Tim Henderson) Date: 27 Nov 2005 21:31:03 -0800 Subject: Newbie question: Tab key giving different output In-Reply-To: <1133155539.865554.216610@g14g2000cwa.googlegroups.com> References: <1133155539.865554.216610@g14g2000cwa.googlegroups.com> Message-ID: <1133155863.491129.278900@g44g2000cwa.googlegroups.com> i think it is telling you to use spaces btw i have no idea, it just sounds like a funny thing to happen From ex_ottoyuhr at hotmail.com Wed Nov 30 21:45:55 2005 From: ex_ottoyuhr at hotmail.com (ex_ottoyuhr) Date: 30 Nov 2005 18:45:55 -0800 Subject: Recursion bug... Message-ID: <1133405155.154823.134620@g47g2000cwa.googlegroups.com> To start with, I'm new at Python, so if this is something relatively ordinary or a symptom of thinking in C++, I apologize... Anyhow, I'm currently trying to write a means of generating genetic-programming functions in Python; the details would be a little much for a Usenet post, but suffice it to say that it would involve trees of objects with an opcode and a variable number, between in this case 0 and 3, of 'arguments' -- also objects of the same sort. As a function to implement them, I'm doing something to the effect of this: max_opcode = ( 20, ) max_with_arguments = ( 15, ) class TreeCommand: opcode = 0 children = [] def __init__(self, anOpcode) : opcode = anOpcode def MakeTreeCommand( maxdepth, currdepth ) : if ( currdepth == 0 ) : toRet = TreeCommand(random.randint(0, max_with_arguments[0]) elif ( maxdepth == currdepth ) : toRet = TreeCommand(random.randint(max_with_arguments[0]+1, max_opcode[0])) else : toRet = TreeCommand(random.randint(0, max_opcode[0])) if ( toRet.opcode <= max_with_arguments[0] ) : childrenRequired = something_greater_than_0 else : childrenRequired = 0 generated = 0 while ( generated < childrenRequired ) : toRet.children.append(MakeTreeCommand(maxdepth, currdepth + 1)) return toRet Sorry to have given such a long example... But anyways, the problem is that, while I think this should generate a number of children for each toRet equivalent to the required number of children, it's actually appending all children generated in the function to the 'root' toRet rather than to child functions -- so that if I ask for a tree with depth 2, and the root would have 2 arguments, the first child would have 1, and the second child would have 2, the result is a root with a 5-argument-long children and two child functions with 0-argument ones. There's some other strange stuff going on here, too; in particular, with one particular opcode, toRet is assigned a member 'value' which is randomly generated between 0 and 10,000. All toRets assigned value seem to be ending up with the same result... Could anyone explain what I'm doing wrong? I'm beginning to suspect that Python scope rules must not work like my native C++; have I made a common mistake? From claird at lairds.us Sat Nov 19 21:08:02 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 20 Nov 2005 02:08:02 GMT Subject: How to write an API for a Python application? References: <437af434@news.bezeqint.net> <1132233532.413086.7330@f14g2000cwb.googlegroups.com> Message-ID: In article , I mumbled: . . . >Pyro might be perfect. My own instinct is to start even more >primitively, with a minimal asynchat client and server. I've >looked through the *Cookbook*, and see that it doesn't have >what I want. Maybe it's time Phaseit donate one of the >little models we use ... Ah-ha! See Example 19-7, on page 447 of *Python in a Nutshell*: under two dozen lines that provide an echo server which correctly handles multiple concurrent clients. But that's also about as much as I've found publicly in that direction. The original questioner wanted, or thought he wanted, an object-capable protocol, so he could invoke methods remotely; for that, I return to Paul Boddie's correct observation that folks can use CORBA, or imitate CORBA badly (as much of this season's "SOA" does). What I don't see, though, is a nice client- server pair that are minimal, and exhibit *symmetric* event-oriented performance and scalability. Some people mistakenly regard this "peering" architecture as a dark secret. I think I'll write a model in under fifty lines of Python this week ... From codecraig at gmail.com Tue Nov 15 14:29:00 2005 From: codecraig at gmail.com (py) Date: 15 Nov 2005 11:29:00 -0800 Subject: subprocess.Popen - terminate Message-ID: <1132082940.699830.222370@z14g2000cwz.googlegroups.com> I am using subprocess.Popen to execute an executable, how can I terminate that process when I want? for example (on windows) p = subprocess.Popen("calc.exe") .... now say I want to kill calc.exe ...how can I do it? By the way, I am not looking for a windows only solution I need something that is universal (mac, *nix, etc) thanks From tim.golden at viacom-outdoor.co.uk Mon Nov 28 10:54:47 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 28 Nov 2005 15:54:47 -0000 Subject: Problem with exchange mail server Message-ID: <9A28C052FF32734DACB0A288A3533991044D2384@vogbs009.gb.vo.local> [Vinayakc] > I am new for python. Welcome to Python. > I have written one code which generates RFC2822 file. > I have header in string format. > i am using following code. [... snip code fragment ...] I'm afraid you're going to have to be a little more precise and give a more useful fragment of code. I can't work out from your description and your code where the data is coming from which you're managing, or even what you're trying to do with it. Can you produce a short *complete* (that someone can paste into an interpreter) piece of code which demonstrates what the problem is which you're encountering? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From scott.daniels at acm.org Fri Nov 11 11:51:40 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 11 Nov 2005 08:51:40 -0800 Subject: Import statements for timeit module In-Reply-To: <4374b8f8$0$31636$626a14ce@news.free.fr> References: <1131715618.580594.68630@z14g2000cwz.googlegroups.com> <4374b8f8$0$31636$626a14ce@news.free.fr> Message-ID: <4374cadd$1@nntp0.pdx.net> bruno at modulix wrote: > ChaosKCW wrote: > >>Hi >> >>I was wondering if someone could help with the import statements needed >>to use the timeit module in the following code. I need to access the >>"cur" object. >> >>Thanks, >> ...> > 'cur' is local to the function, so it's not an attribute of your module, > so you can't hope to import it anyway. Although you could change your code as follows: >>import cx_Oracle >>import timeit >> >>def VerifyTagIntegrity(con, TableOwner): global cur, sql ### >> cur = con.cursor() >> sql = 'select (select count(*) from %s.f4111) as F4111_COUNT, >>(select count(*) from %s.f4111_tag) as TAG_COUNT from dual;' % >>(TableOwner, TableOwner) >> print " SQL: %s" % (sql) XXX>> timer = timeit.Timer('cur.execute(sql)', 'from __main__ import >>cur') timer = timeit.Timer('cur.execute(sql)', ### 'from __main__ import cur, sql') ### >> print timer.timeit() -- -Scott David Daniels scott.daniels at acm.org From mwm at mired.org Sat Nov 26 07:55:47 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 07:55:47 -0500 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <86k6evg25c.fsf@bhuda.mired.org> Message-ID: <867javfu0c.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 26 Nov 2005 04:59:59 -0500, Mike Meyer wrote: >> Steven D'Aprano writes: >>> On Fri, 25 Nov 2005 23:20:05 -0500, Mike Meyer wrote: >>>> If you've got a use case, I'd be interested in hearing it. >>> frozenset perhaps? If it were needed once, it could be needed again. >> That's not a use case, that's an example. > Fine. "I want to use a set as a dictionary key, but dict keys must be > immutable." Except that dict keys don't have to be immutable. The docs say (or imply) that, but they're wrong. We're discussing new wording in another thread. >> And not a very good one, as >> it's not at all clear that the restriction is intentional in that >> case. After all, the same restriction applies to every builtin type, >> including the mutable version of frozenset. > Every builtin type, including mutable sets, is immutable??? No. I think you missed the entire second half the thread. > I think we're talking at cross purposes. I'm talking about immutable > instances. What are you talking about? I'm talking about being able to add attributes to an instance. You can't add an attribute to *any* builtin type. This is an implementation detail. I consider it to be a wart in the language, but an acceptable one, because the costs of fixing it are much worse than the costs of working around it, and practicality beats purity. >>> The obvious case would be for a class where distinct instances that >>> compare equal but not identical map to the same value in a dict. >> How does the ability to add attributes to the instances of the class >> change that behavior? > Er, who said it did? You did. We're looking for a use case for adding the ability to mark a class as having instances that you can't add an attribute to. You suggested this as such a use case. >> The best reason Ben could come up with is that it makes >> finding bugs a bit easier. > Are you sure that was Ben? Maybe I missed it. No, I'm no sure it was Ben - I didn't go chase down the reference. It's the best use case *from anyone* so far, though. > All joking aside, I think having immutable custom classes, with or without > restricting attribute creation, is no worse than (say) Python's name > mangling. There are well-defined facilities for creating read-only attributes. Is there a difference between an immutable object you can add attributes to, and an object that has nothing but read-only attributes? >> Of course, that a feature has a lot in common with features from >> un-Pythonic languages doesn't make it ipso facto unPythonic. After >> all, practicality beats purity. So what's the practical application >> for such a feature? What's the use case? > Class instances match by identity when used as keys, not equality. That's > over-strict: why should Parrot("Norwegian Blue") map to a different item > from Parrot("Norwegian" + " Blue") just because the first instance has a > different memory location to the second? Uh - HTH did we get here? > Please note, I do not expect -- and would not want -- the default > behaviour to change. Most class instances presumably should be mutable, > and therefore mapping by ID is the right behaviour. The default behavior is right for in many cases. For those that it's not right, you can fix it. Proper definition of the Parrot class will insure that Parrot("Norwegian Blue") == Parrot("Norwegian" + " Blue") always evaluates to True. > But some class instances shouldn't be mutable, and should match as keys by > equality not identity: we would expect Fraction(num=1, den=2) to match > Fraction(num=2, den=4) as a key. And you can do that with Python as it exists today (and one of these days I'll get back to my Rational class that does that...). There's no need for any changes to the language to deal with this case. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From cfbolz at gmx.de Sat Nov 5 20:39:40 2005 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 06 Nov 2005 02:39:40 +0100 Subject: Multiples of a number In-Reply-To: <17d4ae400511051621w718075d5i62ab1cd48748e3eb@mail.gmail.com> References: <17d4ae400511051621w718075d5i62ab1cd48748e3eb@mail.gmail.com> Message-ID: <436D5EDC.1000701@gmx.de> Hi! Ivan Shevanski wrote: > I've searched on google for a bit but I can't seem to find a way to get > multiples of a number. . .For instance what would I do if I wanted > something to happen every time x reached a multiple of 100 in this > sample code: > > x = 0 > while x < 2000: > x += 1 > The idea is to use to modulo operator % which gives you the residue of a number when divided by another number: x = 0 while x < 2000: x += 1 if x % 100 == 0: do_something() Note that it is probably more appropriate to use a for loop: for x in range(2000): if x % 100 == 0: do_something() Cheers, Carl Friedrich Bolz From twic at urchin.earth.li Thu Nov 17 18:29:16 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 17 Nov 2005 23:29:16 +0000 Subject: running functions In-Reply-To: <1132179612.759373.130900@g43g2000cwa.googlegroups.com> References: <1132179612.759373.130900@g43g2000cwa.googlegroups.com> Message-ID: On Wed, 16 Nov 2005, sjdevnull at yahoo.com wrote: > Gorlon the Impossible wrote: > >> Is it possible to run this function and still be able to do other >> things with Python while it is running? Is that what threading is >> about? > > Threading's a good answer if you really need to share all your memory. A > multiprocess solution is probably preferrable, though it depends on the > architecture. I'm really curious about this assertion, which both you and Ben Finney make. Why do you think multiprocessing is preferable to multithreading? I've done a fair amount of threads programming, although in java rather than python (and i doubt very much that it's less friendly in python than java!), and i found it really fairly straightforward. Sure, if you want to do complicated stuff, it can get complicated, but for this sort of thing, it should be a doddle. Certainly, it seems to me, *far* easier than doing anything involving multiple processes, which always seems like pulling teeth to me. For example, his Impossibleness presumably has code which looks like this: do_a_bunch_of_midi(do, re, mi) do_something_else(fa, so, la) All he has to do to get thready with his own bad self is: import threading threading.Thread(do_a_bunch_of_midi, (do, re, mi)).start() do_something_else(fa, so, la) How hard is that? Going multiprocess involves at least twice as much code, if not ten times more, will have lower performance, and will make future changes - like interaction between the two parallel execution streams - colossally harder. tom -- Remember when we said there was no future? Well, this is it. From s99999999s2003 at yahoo.com Thu Nov 3 22:02:00 2005 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 3 Nov 2005 19:02:00 -0800 Subject: reading a config file Message-ID: <1131073320.818969.303560@g43g2000cwa.googlegroups.com> hi i used ConfigParser to read a config file. I need the config file to have identical sections. ie : [server] blah = "some server" [destination] blah = "some destination" [end] end= '' [server] blah = "some other server" [destination] blah = "some other destination" [end] end='' and i need to check that every 'server' and 'destination' is followed by 'end' if i used the 'sections' method, it always show 'server' and 'destination' and 'end'. how can i iterate all the sections. ie.. for s in cfg.sections(): do something... or is naming all the sections with different names is a better option? thanks From roccomoretti at hotpop.com Mon Nov 28 13:54:10 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 28 Nov 2005 12:54:10 -0600 Subject: Which License Should I Use? In-Reply-To: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: mojosam wrote: > I've been watching the flame war about licenses with some interest. > There are many motivations for those who participate in this sector, so > disagreements over licenses reflect those agendas. One point that frequently gets ignored in licensing debates: The value of a license is directly proportional to the amount of time, effort, and money you are willing to spend enforcing it. It doesn't matter how fancy the legal wording is - it is up to you, as the copyright holder, to bring legal action against infringers (or at least send a cease-and-desist letter). If you're not going to bother, any and all clauses in the license, no matter how artfully crafted, won't do you any (legal) good. People using your program are left acting on the honor system. Which may be just fine - but you don't need a fancy, legalistic license to accomplish that. From finite.automaton at gmail.com Thu Nov 10 17:08:51 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Nov 2005 14:08:51 -0800 Subject: Python music interfaces In-Reply-To: <4373b647$0$355$da0feed9@news.zen.co.uk> References: <4373b647$0$355$da0feed9@news.zen.co.uk> Message-ID: <1131660531.237790.7320@g47g2000cwa.googlegroups.com> Are you talking about audio files (wav, mp3) or MIDI? Converting audio files into discrete notes ("music recognition") is seriously non-trivial, although there are some commercial products you might be able to use for this. On the other hand, you could draw a spectrographs without too much trouble. As For reading the audio file, you could start with the built-in wave module to read uncompressed WAV files, and worry about other formats later on. Any external audio converter will be able to save as WAV (sox on Linux is one such program) Tkinter's Canvas will work nicely for display, particularly because it's absurdly easy to convert Canvas contents into PostScript for printing. From projecktzero at yahoo.com Wed Nov 23 10:04:14 2005 From: projecktzero at yahoo.com (projecktzero) Date: 23 Nov 2005 07:04:14 -0800 Subject: Tutorials for Python + PostgreSQL References: <1132752765.953726.144150@g44g2000cwa.googlegroups.com> <1132757085.775762.3720@f14g2000cwb.googlegroups.com> Message-ID: <1132758254.656940.75590@f14g2000cwb.googlegroups.com> Michele Simionato wrote: > Steve: > > I want to learn more about enterprise-level programming using Python > > and PostgreSQL. From what I've searched, it seems that psycho is > > interesting to improve runtime too. Do you have tutorials, articles and > > tips to learn this combination? I've been working with PostgreSQL for 2 > > years, and with Python for 6 months. > > Thank you, > > Since Psyco is meant to speedup Python code, whereas the psycopg > adapter is > C-coded, I strongly doubt you will get any improvement from the > combination. > > Michele Simionato I think he's referring to psycopg, a python postgre database adapter http://initd.org/projects/psycopg1 From steve at holdenweb.com Wed Nov 2 20:27:12 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Nov 2005 01:27:12 +0000 Subject: Python and MySQL In-Reply-To: References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: Thomas Bartkus wrote: > "Steve Holden" wrote in message > news:mailman.44.1130970219.18701.python-list at python.org... > >>Thomas Bartkus wrote: >> >>>Well, I'm looking at the source for the ever popular MySQLdb library. It >>>appears to be nothing but straight up Python source code. I see no > > reason > >>>why you couldn't just take these modules and put them in your own > > private > >>>directory. There is nothing secret here. >>> >> >>I have a _mysql.c as a part of my distrbution of MySQLdb. Don't you? >> > > > You made me give that library a good hard stare. > > And no - everything is enunciated in clear Python (.py) code with > corresponding (.pyc) and (.pyo). It appears we have Python source for > everything. > > FWIW: > > >>>>print MySQLdb.version_info > > (1, 2, 0, 'final', 1) > OK. I saw that my own version was (1, 0, 0, 'final', 1), so I assumed Andy's updated the package somewhat. However, downloading the source of 1.2 I see that _mysql.c still appears, and that the package's __init__.py still includes the line include _mysql My C:\Python24\Lib\site-packages directory does contain a _mylsql.pyd file. Would you like to check that we are talking about the same module? 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 steve at REMOVETHIScyber.com.au Sun Nov 27 06:23:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 27 Nov 2005 22:23:04 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <4388385e$0$11063$e4fe514c@news.xs4all.nl> <4388c7f9$0$11080$e4fe514c@news.xs4all.nl> Message-ID: On Sat, 26 Nov 2005 21:39:13 +0100, Martin P. Hellwig wrote: > The software was sold in 3 separates modules requiring a yearly renewal, The software is hardly sold if you have to renew that "sale" every year. That's more like a lease. I'd call it revenue from licencing, not revenue from sales. Of course you're welcome to describe it as sales. It is an arbitrary choice one way or another -- the main thing is to not talk at cross-purposes, as we obviously have been doing. -- Steven. From keesvanschaik at gmail.com Fri Nov 18 18:29:43 2005 From: keesvanschaik at gmail.com (KvS) Date: 18 Nov 2005 15:29:43 -0800 Subject: Confused about namespaces In-Reply-To: References: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> Message-ID: <1132356583.703129.241070@g47g2000cwa.googlegroups.com> Ok, makes sense but didn't seem "natural" to me, although it is an obvious consequence of what you just pointed out, namely that modules are evaluated in their own namespace, something to keep in mind... On the other hand it does apparently work recursively "the other way around" since I didn't explicitly import wx in main.py but only indirect via importing GUIclasses in which wx is imported right? Thanks. :). From starmaven at gmail.com Wed Nov 2 07:24:05 2005 From: starmaven at gmail.com (starmaven at gmail.com) Date: 2 Nov 2005 04:24:05 -0800 Subject: SOCKS proxy in Python? Message-ID: <1130934245.496703.47570@g49g2000cwa.googlegroups.com> I'm looking for a way to implement socket connections through a SOCKS (4/5) proxy in Python. I don't want to use Twisted or anything complicated - just a simple replacement for the socket library. The only thing I could find was for Python 1.0.1, and I couldn't get that to compile. Apparently it's really trivial to rewrite the socket library (a manner of a few lines) but I am not a protocol or networking guru. Can anyone help me? From bignose+hates-spam at benfinney.id.au Wed Nov 16 16:39:42 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Nov 2005 08:39:42 +1100 (EST) Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> Message-ID: The Eternal Squire wrote: > The greatest theft of sales opportunities Utter poppycock. Who is to say that a particular entity holds an exclusive "sales opportunity" to a particular individual? Are we to protect the expectations of profit for some, at the expense of sharing things with each other? > Little can be done to stop it except through repeated education at > every grade level that copying without paying is as bad as > plagiarism and just as dangerous to one's career in school. Wonderful double-think. > Ourselves and our children are lost generations with respect to > ethics, manners, Ethics such as sharing, and helping one's neighbour? > and respect for authority When such "authority" demands that we enter unsigned contracts to protect their profits, they lose our respect, yes. > perhaps we can train our grandchildren to behave more proprely. I certainly hope our grandchildren will live in an environment that encourages helping each other, yes. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From swarnapsv at yahoo.co.in Sun Nov 6 15:56:21 2005 From: swarnapsv at yahoo.co.in (Swarna) Date: 6 Nov 2005 12:56:21 -0800 Subject: Modify HTML data In-Reply-To: References: <1131235132.163505.280600@g43g2000cwa.googlegroups.com> <1131298307.445951.63000@g49g2000cwa.googlegroups.com> Message-ID: <1131310581.533196.164710@o13g2000cwo.googlegroups.com> Peter Hansen wrote: > Swarna wrote: > > Peter Hansen wrote: > >>Swarna wrote: > >>>I am using scp in python to copy a html file on remote server, to my > >>>local machine. Now, i need to update this html file in my local machine > >>>( by adding a new Hyperlink to the existing table od hyperlinks ) and > >>>copy it back (overwriting the old copy ) to the remote server. > >> > >>If you are using scp to copy the file from the remote server in the > >>first place, what's stopping you from using scp to copy it back? > > > > I might be vague in expressing my problem.....the problem is not with > > scp. What i need is how to modify the html file in my local machine > > that i got from remote server. > > Ah, so all that stuff about scp was just to distract us from the real > problem? > > Okay, so Lorenzo's advice is fine: grab an HTML parser and use that to > figure out where things are. Or if the problem is defined simply > enough, you could use a regular expression (re module). BeautifulSoup > is often recommended when the HTML is not necessarily very clean... > > Personally, I'd start with an re and move on from there only if that was > for some reason not sufficient. > > -Peter hey........i got it worked with simple file object.....Thanks, for all your suggestions ! From bonono at gmail.com Thu Nov 24 03:13:46 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 00:13:46 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: References: <1132778601.776080.80100@g44g2000cwa.googlegroups.com> Message-ID: <1132820026.576494.262960@o13g2000cwo.googlegroups.com> Fredrik Lundh wrote: > rurpy at yahoo.com wrote: > > > > the thing that's in favour is "then-if-else", not "if-then-else". > > > > Sorry if I confused you, I though it was clear that I meant the > > concept, not a specific syntactical implementation. > > yup, but if you care readability about, the words order appear in > would to seem matter too. > Not in the context of this conversation though. From martin at v.loewis.de Mon Nov 21 16:52:10 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 21 Nov 2005 22:52:10 +0100 Subject: compiling Python under Windows In-Reply-To: References: <29pgf.12621$ih5.5110@dukeread11> Message-ID: <4382418A.2070902@v.loewis.de> Philippe C. Martin wrote: >>My mistake: The makefile (as written in the readme!) looks for bzip 1.0.2 >> > > PS: since bzip.org does not have 1.0.2 source anymore, can I just rename > 1.0.3 ? That should work; alternatively, you can change the project file. Regards, Martin From fredrik at pythonware.com Wed Nov 23 04:37:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 10:37:44 +0100 Subject: Hot to split string literals that will across two or more lines ? References: Message-ID: Mohammad Jeffry wrote: > I can always do this :- > --------------------------------------------------------------------------------- > #!/usr/bin/python > > > def print_sql(): > sql = '''aaaaaaaaaaaaaaaaaaaaaaa > bbbbbbbbbbbbbbbbbbbbbbb'''.replace("\n","") > print sql > > print_sql() > > --------------------------------------------------------------------------------- sql = ( 'aaaaaaaaaaaaaaaaaaaaaaa' 'bbbbbbbbbbbbbbbbbbbbbbb' ) print sql or, perhaps more realistic: cursor.execute( 'aaaaaaaaaaaaaaaaaaaaaaa' 'bbbbbbbbbbbbbbbbbbbbbbb', a, b, c ) e.g. cursor.execute( 'select * from foo' ' where bar=%s' ' limit 100', bar ) From apardon at forel.vub.ac.be Mon Nov 7 03:19:46 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 08:19:46 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: Op 2005-11-04, Steven D'Aprano schreef : > On Fri, 04 Nov 2005 09:03:56 +0000, Antoon Pardon wrote: > >> Op 2005-11-03, Steven D'Aprano schreef : >>> On Thu, 03 Nov 2005 13:01:40 +0000, Antoon Pardon wrote: >>> >>>>> Seems perfectly sane to me. >>>>> >>>>> What would you expect to get if you wrote b.a = b.a + 2? >>>> >>>> I would expect a result consistent with the fact that both times >>>> b.a would refer to the same object. >>> >>> class RedList(list): >>> colour = "red" >>> >>> L = RedList(()) >>> >>> What behaviour would you expect from len(L), given that L doesn't have a >>> __len__ attribute? >> >> Since AFAICT there is no single reference to the __len__ attribute that >> will be resolved to two different namespace I don't see the relevance. > > Compare: > > b.a += 2 > > Before the assignment, instance b does not have an attribute "a", so class > attribute "a" is accessed. You seem to be objecting to this inheritance. I object to the inheritance in a scope where b.a also refers to the instance. If there is no problem that a reference can refer to different objects in the same scope, then the following should work too. a = 0 def f(): a += 2 One can reason just the same that before the assignment f doesn't have a local variable yet, so the global should be accessed. People who don't agree don't want functions to have access to outer scope variables. > Do you object to import searching multiple directories? > > Why do you object to attribute resolution searching multiple namespaces? I don't. >> I don't see the relevance of these pieces of code. In none of them is >> there an occurence of an attribute lookup of the same attribute that >> resolves to different namespaces. > > Look a little more closely. In all three pieces of code, you have a > conflict between the class attribute 'ls' and an instance attribute 'ls'. No you look a little more clearly. > In the first scenario, that conflict is resolved by insisting that > instances explicitly define an attribute, in other words, by making > instance attribute ONLY search the instance namespace and not the class > namespace. No it isn't. You seem unable to make a difference between a resolution in general, and a resolution in a scope where an assignment has been made. -- Antoon Pardon From muttu2244 at yahoo.com Wed Nov 9 04:14:38 2005 From: muttu2244 at yahoo.com (muttu2244 at yahoo.com) Date: 9 Nov 2005 01:14:38 -0800 Subject: not able to HTTPS page from python Message-ID: <1131527678.640177.118930@g43g2000cwa.googlegroups.com> Hi all, Am trying to read a email ids which will be in the form of links ( on which if we click, they will redirect to outlook with their respective email ids). And these links are in the HTTPS page, a secured http page. The point is that am able to read some links with HTTP page, but am not able to read the same when I try with HTTPS. Using the following code from sgmllib am able to read the links, class MyParser(sgmllib.SGMLParser): def __init__(self): sgmllib.SGMLParser.__init__(self) self.inside_a = False self.address = '' def start_a(self,attrs): if DEBUG: print "start_a" print attrs for attr,value in attrs: if attr == 'href' and value.startswith('mailto:'): self.address = value[7:] self.inside_a = True def end_a(self): if DEBUG: print "end_a" if self.address: print '"%s" <%s>' % (self.nickname, self.address) mailIdList.append(self.address) self.inside_a = False self.address = self.nickname = '' def handle_data(self,data): if self.inside_a: self.nickname = data And for the proxy authentication and the https handler am using the following lines of code authinfo = urllib2.HTTPBasicAuthHandler() proxy_support = urllib2.ProxyHandler ({"http" : "http://user:password at proxyname:port"}) opener = urllib2.build_opener(proxy_support, authinfo, urllib2.HTTPSHandler) urllib2.install_opener(opener) Then am trying to call the parser for the links in a particular https page which will be given as a command line argument. Which will read me all the links in that page. p = MyParser() for ln in urllib2.urlopen( sys.argv[1] ): p.feed(ln) p.close() NOTE : I have installed python with _ssl support also. So with this code am able to read the links with HTTP page but not for the HTTPS page. AM NOT GETTING ANY ERRORS EITHER BUT ITS NOT READING THE LINKS, THAT ARE PRESENT IN THE GIVEN HTTPS PAGE Could you please tell me am I doing some thing wrong in the above code for any of the handlers. I have got struck here from so many days, please give me the solution for this. Thanks and regards YOGI From pythonic at gmail.com Fri Nov 25 05:31:43 2005 From: pythonic at gmail.com (pythonic) Date: Fri, 25 Nov 2005 16:01:43 +0530 Subject: How to use _ in interactive mode Message-ID: Hi, I use '_' for localization in my program. The problem is when testing the program using python intractive mode I lose _ function. One solution is put following in PYTHONSTARTUP file. -- import readline def __enforce_underscore__ (): __builtins__._ = str readline.set_pre_input_hook (__enforce_underscore__) -- My program in startup imports a module which customize the env. Putting above in that module doesn't solve the problem. Any cleaner/better way? Honestly, I was expecting once overriden _ in builtins it would be honored. This how I reproduce the problem. Python 2.3.3 (#1, May 7 2004, 10:31:40) >>> def localizer(s): return str(s) >>> __builtins__.__dict__['_'] = localizer >>> _ >>> _('some text') 'some text' >>> _ 'some text' >>> _('some text') Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable TIA. From steve at REMOVETHIScyber.com.au Sat Nov 5 23:20:35 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 06 Nov 2005 15:20:35 +1100 Subject: Multiples of a number References: <17d4ae400511051621w718075d5i62ab1cd48748e3eb@mail.gmail.com> Message-ID: On Sun, 06 Nov 2005 02:39:40 +0100, Carl Friedrich Bolz wrote: > Hi! > > Ivan Shevanski wrote: >> I've searched on google for a bit but I can't seem to find a way to get >> multiples of a number. . .For instance what would I do if I wanted >> something to happen every time x reached a multiple of 100 in this >> sample code: >> >> x = 0 >> while x < 2000: >> x += 1 >> > > The idea is to use to modulo operator % which gives you the residue of a > number when divided by another number: > for x in range(2000): > if x % 100 == 0: > do_something() Another way is, if you aren't doing anything *except* counting for the other 99 values of x, just skip them completely: fox x in range(20): do_something(x*100) Ivan, what are you trying to do? -- Steven. From grante at visi.com Mon Nov 14 15:56:36 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 14 Nov 2005 20:56:36 -0000 Subject: q: console widgets for *nix and windows? References: Message-ID: <11nhug4pgddchb4@corp.supernews.com> On 2005-11-14, aum wrote: > Can anyone please recommend a widget library for text console, > that works not only on *nix systems but windows /as well/? > > I'm looking for something a bit higher-level than pure curses, > preferably with a gui-like set of widgets, event loop, handler > methods etc. http://tvision.sourceforge.net/ -- Grant Edwards grante Yow! I'm using my X-RAY at VISION to obtain a rare visi.com glimpse of the INNER WORKINGS of this POTATO!! From kay.schluehr at gmx.net Tue Nov 22 09:32:25 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 22 Nov 2005 06:32:25 -0800 Subject: Application Plugin Framework References: Message-ID: <1132669945.192062.166900@g49g2000cwa.googlegroups.com> Ron wrote: > Hello, > > I'm attempting to develop a plugin framework for an application that I'm > working on. I wish to develop something in which all plugins exist in a > directory tree. The framework need only be given the root of the tree. The > framework then uses os.path.walk to search all for all files named > 'plugin.pyc'. These are then loaded using imp.load_compiled(). They need > contain only one variable called 'plugin' which is a reference to an > instance of the plugin object. This is extrated from the loaded module > using getattr. After that, the plugins are easy to work with since they > implement a standard interface. Or so the theory goes. And this does work > fine provided the plugin is implemented entirely within that one file. If > there are support modules that the main plugin module imports, which exist > in the plugin's directory, then I get problems. The imports fail. I get > "ImportError: No module named " > > Here's PluginManager.py: > #################### > > import os > > > class PluginManager( object ): > def __init__( self, pluginDir ): > self._plugins = { } > > os.path.walk( pluginDir, self._addPlugin, None ) > > def _addPlugin( self, arg, dirname, names ): > import imp > > for filename in names: > fullFilename = os.path.join( dirname, filename ) > if os.path.isfile( fullFilename ) and (filename == 'plugin.pyc'): > module = imp.load_compiled( 'plugin', fullFilename ) > self._plugins[ plugin.name ] = getattr( module, 'plugin' ) > return > > PM = PluginManager( r'C:\Personal\SWDev\ModuleTest' ) # Root of the > plugin directory tree > > print 'Plugin List: ', PM._plugins.keys() > > for name,plugin in PM._plugins.iteritems(): > plugin.doSomething( ) > > print 'done!' > > ####################### > My plugin.py file is in C:\Personal\SWDev\ModuleTest\Plugins\MyPlugin. It's > called plugin.pyc (which I compiled from the following source by importing > it into the interactive python shell. > ####################### > > import work > > > class MyPlugin( object ): > def __init__( self ): > self.name = 'MyPlugin' > > def doSomething( self ): > work.foo( ) > > > plugin = MyPlugin( ) > > ####################### > Finally, work.py is in the same directory as plugin.py > ####################### > > def foo( ): > print 'foo called' > > ###################### Hi Ron, the import directive does not lookup work.py in the same directory as plugin.py. It searches through the directory of PluginManager.py and otherwise searches through the directories of sys.path. The solution is referencing work.py relative to the dir of the PluginManager. MyFramework/ __init__.py PluginManager.py Plugins/ plugin.py work.py ####################### plugin.py ####################### import MyFramework.Plugins.work as work # do some stuff... If import still causes trouble add the path of MyFramework to sys.path. Regards, Kay From mensanator at aol.com Fri Nov 4 19:52:38 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 4 Nov 2005 16:52:38 -0800 Subject: GMPY: divm() memory leak revisited Message-ID: <1131151958.314488.310400@z14g2000cwz.googlegroups.com> Since the following discussion took place (unresolved), I've kept it in the back of my mind as I've been learning to use the base gmp library in c. Now I believe I know what the problem is. First, divm() is not a gmp function. It is a derived function created in gmpy. It is derived from the gmp invert() function (which I know from my testing does not leak memory). So it's a gmpy specific bug. Second, I learned from the gmp c library that temporary mpz objects must be freed to prevent memory leak. Aha! The gmpy source code is probably not freeing some temporary mpz it created. Third, we have the smoking gun: divm(a,b,m): returns x such that b*x==a modulo m, or else raises a ZeroDivisionError exception if no such value x exists (a, b and m must be mpz objects, or else get coerced to mpz) Of course, to "coerce" means to create temporary variables to pass to the gmp library. It would appear that these temporary variables are not being freed. Now if I'm right, then I can prove this by eliminating the need to coerce the operands by passing mpz's to the divm() function. # # if the parameters are already mpz's... # z = gmpy.mpz(81287570543) x = gmpy.mpz(8589934592) y = gmpy.mpz(3486784401) tot = 0 while True: n = input('How many more divm: ') if n<=0: break print '%d more...' % n, # # ...then they won't need to be coerced # for i in xrange(n): gmpy.divm(z,x,y) tot += n print '...total %d' % tot With coercing, I get C:\Python23\user\the_full_monty>python gmpytest.py How many more divm: 10000000 10000000 more...Fatal Python error: mp_allocate failure abnormal program termination peak Commit Charge (K): 792556 Without needing to coerce, the test ran to completion with flat memory usage. Unfortunately, c is still somewhat greek to me, but even so, the problem appears obvious. static PyObject * Pygmpy_divm(PyObject *self, PyObject *args) { PympzObject *num, *den, *mod, *res; if(!PyArg_ParseTuple(args, "O&O&O&", Pympz_convert_arg, &num, Pympz_convert_arg, &den, Pympz_convert_arg, &mod)) { return last_try("divm", 3, 3, args); } if(!(res = Pympz_new())) return NULL; if(mpz_invert(res->z, den->z, mod->z)) { /* inverse exists */ mpz_mul(res->z, res->z, num->z); mpz_mod(res->z, res->z, mod->z); if(options.ZM_cb && mpz_sgn(res->z)==0) { PyObject* result; if(options.debug) fprintf(stderr, "calling %p from %s for %p %p %p %p\n", options.ZM_cb, "divm", res, num, den, mod); result = PyObject_CallFunction(options.ZM_cb, "sOOOO", "divm", res, num, den, mod); if(result != Py_None) { Py_DECREF((PyObject*)res); return result; } } return (PyObject*)res; } else { PyObject* result = 0; if(options.ZD_cb) { result = PyObject_CallFunction(options.ZD_cb, "sOOO", "divm", num, den, mod); } else { PyErr_SetString(PyExc_ZeroDivisionError, "not invertible"); } Py_DECREF((PyObject*)res); return result; } } Note that 4 PympzObjects get created but only res gets passed to Py_DECREF (which seems to be the method by which it's freed, not 100% sure about this). But I notice that other functions that coerce variables call Py_DECREF on each of the coerced variables: static PyObject * Pygmpy_gcd(PyObject *self, PyObject *args) { PympzObject *a, *b, *c; TWO_ARG_CONVERTED("gcd", Pympz_convert_arg,&a,&b); assert(Pympz_Check((PyObject*)a)); assert(Pympz_Check((PyObject*)b)); if(!(c = Pympz_new())) { Py_DECREF((PyObject*)a); Py_DECREF((PyObject*)b); return NULL; } mpz_gcd(c->z, a->z, b->z); Py_DECREF((PyObject*)a); Py_DECREF((PyObject*)b); return (PyObject*)c; } Here the PympzObject c is not freed because it is returned as the result of the function, but the coerced variables a and b are. So the fix may be to simply add Py_DECREF((PyObject*)num); Py_DECREF((PyObject*)den); Py_DECREF((PyObject*)mod); to divm(). (Assuming it's that simple, I could have overlooked something.) Unfortunately, I don't have any means of testing this theory. I did see the reference to which I will be trying eventually, but in case I can't get that to work I wanted to have this posted in case someone else wants to take a crack at it. From pythonnew at gmail.com Tue Nov 15 06:16:08 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 15 Nov 2005 03:16:08 -0800 Subject: compare list In-Reply-To: <8c7f10c60511150305p29c7ab48u@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <1d987df30511142330t39b137fdpdc9eee56e73d6e1f@mail.gmail.com> <4379AA95.80806@cc.umanitoba.ca> <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> <8c7f10c60511150227v297140e1n@mail.gmail.com> <1d987df30511150258j7848d3d5o61905f5ac935a6b0@mail.gmail.com> <8c7f10c60511150305p29c7ab48u@mail.gmail.com> Message-ID: <8c11e4350511150316l3f35253dkd42f98842e55119a@mail.gmail.com> On 11/15/05, Simon Brunning wrote: > > On 15/11/05, Shi Mu wrote: > > Yes, i am using python 2.3, > > I have used from sets import * > > but still report the same error: > > > > Traceback (most recent call last): > > > > File "", line 1, in ? > > > > NameError: name 'set' is not defined > > I said analogous, not identical. try (untested): > > from sets import Set as set > > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ > -- > http://mail.python.org/mailman/listinfo/python-list > an error reported: Traceback (most recent call last): File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\temp\try.py", line 8, in ? from sets import Set as set ImportError: cannot import name Set >>> -- Thanks! Ben Bush -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwm at mired.org Sun Nov 20 21:12:03 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 20 Nov 2005 21:12:03 -0500 Subject: Why are there no ordered dictionaries? References: Message-ID: <861x1ahhqk.fsf@bhuda.mired.org> Christoph Zwerschke writes: > Ben Finney wrote: >> Another possibility: ordered dictionaries are not needed when Python >> 2.4 has the 'sorted' builtin. > The 'sorted' function does not help in the case I have indicated, > where "I do not want the keys to be sorted alphabetically, but > according to some criteria which cannot be derived from the keys > themselves." And how would an ordered dictionary help in this case? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From aleax at mail.comcast.net Thu Nov 3 10:24:13 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 07:24:13 -0800 Subject: weakrefs to functions for observer pattern References: <90265$436995f5$d8c4f6e6$28290@FUSE.NET> <1h5f4p9.1ttt5sz13qi83uN%aleax@mail.comcast.net> <436A24CA.9050202@fuse.net> Message-ID: <1h5fvjk.bxm5y71bpjidcN%aleax@mail.comcast.net> Michael Schneider wrote: ... > Thank you, I mis-read the docs. > > The mistake I made was having was using a weak reference as a key in > the dictionary. Rather than using a weakref.WeakKeyDictionary , I guess? > Weak references will be very useful for me. > > I really enjoy python. So many good things have been added to the > language without taking the fun away :-) Glad to hear this! Alex From __peter__ at web.de Tue Nov 29 07:46:35 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Nov 2005 13:46:35 +0100 Subject: Why I need to declare import as global in function References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> <1133265470.979764.157620@g14g2000cwa.googlegroups.com> Message-ID: didier.doussaud at gmail.com wrote: > the error message : > > EXCEPTION RAISED:: > > Traceback (most recent call last): > File "../tu.py", line 21, in run_tu > execfile( filename ) > File "TU_05_010.py", line 8, in ? > import TU_05_tools > File "./TU_05_tools.py", line 4, in ? > f() > File "./TU_05_tools.py", line 2, in f > print math.pi > NameError: global name 'math' is not defined > > I have remarq that this problem is raised when I execute code in an > imported module (during importation) > > I think I will be able to isolate it and have a simple sample soon .... Random guess: change the execfile() call to execfile(filename, globals()) or exec file(filename).read() If one of the above works, a minimal example of what happens could be file("tmp.py", "w").write(""" import math """) def f(): execfile("tmp.py") print locals()["math"].pi # 3.14159265359 print math.pi # Error, math looked up in the global namespace f() execfile() puts symbols into the local namespace but keeps the compiler clueless because it's just an ordinary function, whereas exec triggers the generation of slightly different bytecode for the enclosing function. Peter From AllenGnr at yahoo.com.cn Wed Nov 9 23:24:01 2005 From: AllenGnr at yahoo.com.cn (AllenDang) Date: 9 Nov 2005 20:24:01 -0800 Subject: ANN: Wing IDE for Python 2.0.4 released In-Reply-To: References: Message-ID: <1131596641.324127.185060@g43g2000cwa.googlegroups.com> Thanks! Learning how to write a template........I also think the macro script is a big fun. From bonono at gmail.com Thu Nov 24 01:06:37 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 22:06:37 -0800 Subject: return in loop for ? In-Reply-To: References: <4384F705.31CEC951@valid.org><86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> Message-ID: <1132812397.369787.214140@g47g2000cwa.googlegroups.com> Steve Holden wrote: > Yomgui: I am not a language lawyer, but I think you can feel safe > returning from inside a loop. Just as a matter of interest, how else > would you propose to implement the functionality Mike showed: > > > >>>def f(): > > > > ... for i in range(20): > > ... if i > 10: return i > > ... > > > > Python is supposed to cleanly express the programmer's intent. I can;t > think of a cleaner way that Mike's - can you? Interestingly, I just saw a thread over at TurboGears(or is it this group, I forgot) about this multiple return issue and there are people who religiously believe that a function can have only one exit point. def f(): r = None for i in range(20): if i > 10: r = 10 break if r is None: something else: return r From *firstname*nlsnews at georgea*lastname*.com Thu Nov 17 23:19:45 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Fri, 18 Nov 2005 04:19:45 GMT Subject: Hot to split string literals that will across two or more lines ? References: <1132284614.326121.252250@g49g2000cwa.googlegroups.com> Message-ID: <*firstname*nlsnews-A71E9A.23194917112005@news.verizon.net> In article <1132284614.326121.252250 at g49g2000cwa.googlegroups.com>, "Sam Pointon" wrote: > > print "a string which is very loooooo" \ > > + "ooooong." > > Minor pedantry, but the plus sign is redundant. Python automatically > concatenates string literals on the same logical line separated by only > whitespace. > While we're at it, I use bracketing instead of line continuation: print ( "a long string, longer than this " "and some more of the string" ) ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From kylotan at gmail.com Fri Nov 4 05:17:06 2005 From: kylotan at gmail.com (Ben Sizer) Date: 4 Nov 2005 02:17:06 -0800 Subject: help converting some perl code to python In-Reply-To: <1131094909.984993.32330@z14g2000cwz.googlegroups.com> References: <1131094909.984993.32330@z14g2000cwz.googlegroups.com> Message-ID: <1131099426.899163.14640@o13g2000cwo.googlegroups.com> eight02645999 at yahoo.com wrote: > the problem is the '..' operator in perl. Is there any equivalent in > python? I can't think of anything with a similar operation, to be honest. I'd try using while loops which look out for the next section delimiter. -- Ben Sizer. From paschott at no.yahoo.spamm.com Fri Nov 11 16:19:36 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Fri, 11 Nov 2005 21:19:36 GMT Subject: Command-line tool able to take multiple commands at one time? References: <1131672197.698115.284580@g43g2000cwa.googlegroups.com> Message-ID: I'll give it a try. I've been using PythonWin and SPE recently and hadn't really messed with IDLE too much as I liked the somewhat more advanced features of the other IDEs. I'll check it out again. Also thanks to all for the IP hints - I may check those out as well. -Pete "Devan L" wrote: > > Peter A. Schott wrote: > > Per subject - I realize I can copy/paste a line at a time into an interactive > > session when I'm trying to debug, but was wondering if there is any tool out > > there that allows me to copy sections of working Python scripts to paste into my > > interactive console and let those run so I don't have to copy line-by-line. > > > > Not sure if iPython would meet that criteria or not or even if such a beast > > exists. It would be helpful for debugging some of my simpler, yet still lengthy > > at times, scripts. > > > > Thanks in advance. > > > > -Pete Schott > > It's called IDLE (At least, the interactive session with it). Some > people dislike IDLE, though. From maketo at ukato.freeshell.org Wed Nov 30 12:32:27 2005 From: maketo at ukato.freeshell.org (Ognen Duzlevski) Date: Wed, 30 Nov 2005 17:32:27 +0000 (UTC) Subject: import Excel csv - files References: <000001c5f584$f90e7690$6106a8c0@samsungx30> <2fOdnb1W29ufQBDeRVn-iA@comcast.com> Message-ID: Hi, Larry Bates wrote: > You should actually explain what you mean by "export". > Excel has a Save As HTML that would save everything out to HTML > or you can do Save As .CSV. Hard to tell what you want. > I suspect that to get to the cell comments you will need to > go through COM interface to Excel. You can also script OpenOffice from python to suck in an excel file and spit out a CSV or HTML or whatever else you want. After that you can parse the resulting files. Ognen From duncan.booth at invalid.invalid Mon Nov 28 07:57:33 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Nov 2005 12:57:33 GMT Subject: General question about Python design goals References: Message-ID: Antoon Pardon wrote: > So suppose I want a dictionary, where the keys are colours, represented > as RGB triplets of integers from 0 to 255. A number of things can be > checked by index-like methods. > > e.g. > > def iswhite(col): > return col.count(255) == 3 > > def primary(col): > return col.count(255) == 1 and col.count(0) == 2 > > def secondary(col): > return col.count(255) == 2 and col.count(0) == 1 Just because you *can* implement these by treating your colour like a list doesn't make it a good idea. Treating them as opaque values makes these particular tests clearer: def iswhite(col): return col==WHITE def primary(col): return col in (RED,GREEN,BLUE) def secondary(col): return col in (CYAN,MAGENTA,YELLOW) If you relax your definition of primary to simply require that two planes are black then you may have a case where you want to treat the colour planes as a list, but if you convert it explicitly then you'll be better placed to keep the code working when someone decides to add an alpha channel or to switch the representation to CMYK. def anyshadeprimary(col): return [col.red, col.green, col.blue].count(0)==2 # or return col.toRGB().count(0)==2 So it looks to me as though you want col to be a type (which might be a subclass of tuple) but a list would be a mistake. From grahamd at dscpl.com.au Thu Nov 24 02:30:48 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 23 Nov 2005 23:30:48 -0800 Subject: ANNOUNCE: Mod_python 3.2.5 Beta References: <20051123102324.A63699@grisha.dyndns.org> Message-ID: <1132817448.670382.148180@g43g2000cwa.googlegroups.com> Damjan wrote: > > The Apache Software Foundation and The Apache HTTP Server Project are > > pleased to announce the 3.2.5 Beta release mod_python. > http://www.modpython.org/live/mod_python-3.2.5b/doc-html/hand-pub-alg-auth.html > > says "Since functions cannot be assigned attributes,..." > > But that's not true (at least in 2.3 and 2.4): > > >>> def f(): > ... return 'a' > ... > >>> f.__auth__ = {1:'one'} The documentation was originally written when mod_python supported 2.1 and 2.2. :-) Anyway, whether it can now be done is irrelevant as the next part of the documentation states: Note that this technique will also work if __auth__ or __access__ is a constant, but will not work is they are a dictionary or a list. Thus I suspect (but can't confirm right now), that your example will not work anyway as __auth__ defined within the scope of the function as a dictionary will not be seen as a constant as required. Overall, I would not recommend relying on nesting __auth__ or __access__ within the scope of a published function like this as the code which supports this feature is somewhat fragile. http://issues.apache.org/jira/browse/MODPYTHON-43 It is possible that now that mod_python requires at least mod_python 2.3 that new features in the language may be able to be utilised to improve this feature of mod_python. BTW, you are better off bringing up issue like this about mod_python on the mod_python mailing list instead of the general Python group. Graham From kylotan at gmail.com Mon Nov 7 04:52:59 2005 From: kylotan at gmail.com (Ben Sizer) Date: 7 Nov 2005 01:52:59 -0800 Subject: how to present Python's OO feature in design? In-Reply-To: <1131347829.761335.6780@g43g2000cwa.googlegroups.com> References: <1131332809.044523.169900@o13g2000cwo.googlegroups.com> <1131333250.078344.176070@g43g2000cwa.googlegroups.com> <1131333662.653503.285330@g47g2000cwa.googlegroups.com> <1131347829.761335.6780@g43g2000cwa.googlegroups.com> Message-ID: <1131357179.515200.48320@g44g2000cwa.googlegroups.com> Kay Schluehr wrote: > pcmanlin wrote: > > because i have a problem that python's oo feature is so great, but > > maybe when the project become larger, python's no-declaration cannot > > mapping the design to practice? > > > > I am not sure about it. I don't know if there are any tools that convert UML to Python code, but that doesn't stop you working with UML diagrams if you choose, and then hand-coding the classes later. Just remember that one of the major purposes of using UML for big up-front design is to save you from having to do a lot of refactoring later, but in Python this is rarely a difficult task. -- Ben Sizer From mirandacascade at yahoo.com Fri Nov 4 21:48:47 2005 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 4 Nov 2005 18:48:47 -0800 Subject: import statement / ElementTree Message-ID: <1131158927.097582.91530@g14g2000cwa.googlegroups.com> O/S: Windows 2K Vsn of Python: 2.4 Currently: 1) Folder structure: \workarea\ <- ElementTree files reside here \xml\ \dom\ \parsers\ \sax\ 2) The folder \workarea\ is in the path. 3) A script (which is working) makes calls to the Element(), SubElement(), tostring() and XML() methods within ElementTree.py; the script is organized as follows: # top of file; not within any function/mehtod import ElementTree root = ElementTree.Element('request') pscifinq = ElementTree.SubElement(root, 'pscifinq') bank = ElementTree.SubElement(pscifinq, 'bank') bank.text = '1' inquiryString = ElementTree.tostring(root) 4) the term 'ElementTree files' referenced above refers to the following files: __init__.py (this file contains only comments) ElementInclude.py ElementPath.py ElementTree.py HTMLTreeBuilder.py SgmlopXMLTreeBuilder.py SimpleXMLTreeBuilder.py SimpleXMLWriter.py TidyHTMLTreeBuilder.py TidyTools.py XMLTreeBuilder.py Want to change things as follows: Folder structure: \workarea\ <- ElementTree files no longer here \xml\ \dom\ \elementtree\ <- ElementTree files reside here \parsers\ \sax\ I tried changing the import ElementTree statement to: import xml.elementtree.ElementTree The result of changing the folder structure and the import statement was the following error: import xml.elementtree.ElementTree ImportError: No module named elementtree.ElementTree I verified that the file ElementTree.py really does reside in the \workarea\xml\elementtree\ folder. Assuming that I really want the ElementTree files to reside in the \workarea\xml\elementtree\ folder, what changes must I make such that the script can locate the ElementTree.py file? I have a hunch that there is something obvious that I am missing in the import statement; is it possible to accomplish this by changing only the import statement rather than changing each of the calls to the Element(), SubElement(), XML() and tostring() methods. From vmlinuz at abisen.com Wed Nov 9 17:01:06 2005 From: vmlinuz at abisen.com (Anand S Bisen) Date: Wed, 09 Nov 2005 17:01:06 -0500 Subject: Python obfuscation In-Reply-To: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> Message-ID: <437271A2.1000306@abisen.com> I dont know much !! But if somebody asks me this question my answer would be to convert some of the meat inside my programs to C/C++ and then provide the interface to those novel ideas to Python using swig. And for another level of protection maybe use these offuscator on the remaining Python source. What do you think ? Anand S Bisen petantik wrote: > Are there any commercial, or otherwise obfuscators for python source > code or byte code and what are their relative advantages or > disadvantages. I wonder because there are some byte code protection > available for java and .NET, although from what i've read these seem to > be not comprehensive as protection schemes > > > > > > > > http://petantik.blogsome.com - Telling it like it is > From bokr at oz.net Sat Nov 5 18:15:30 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 05 Nov 2005 23:15:30 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <436bdc05.135552474@news.oz.net> Message-ID: <436d2a1e.221081358@news.oz.net> On Sat, 05 Nov 2005 14:37:19 +1100, Steven D'Aprano wrote: >On Sat, 05 Nov 2005 00:25:34 +0000, Bengt Richter wrote: > >> On Fri, 04 Nov 2005 02:59:35 +1100, Steven D'Aprano wrote: >> >>>On Thu, 03 Nov 2005 14:13:13 +0000, Antoon Pardon wrote: >>> >>>> Fine, we have the code: >>>> >>>> b.a += 2 >>>> >>>> We found the class variable, because there is no instance variable, >>>> then why is the class variable not incremented by two now? >> Because the class variable doesn't define a self-mutating __iadd__ >> (which is because it's an immutable int, of course). If you want >> b.__dict__['a'] += 2 or b.__class__.__dict__['a'] += 2 you can >> always write it that way ;-) >> >> (Of course, you can use a descriptor to define pretty much whatever semantics >> you want, when it comes to attributes). >> >>> >>>Because b.a += 2 expands to b.a = b.a + 2. Why would you want b.a = >> >> No, it doesn't expand like that. (Although, BTW, a custom import could >> make it so by transforming the AST before compiling it ;-) >> >> Note BINARY_ADD is not INPLACE_ADD: > >Think about *what* b.a += 2 does, not *how* it does it. Perhaps for some what it does, or what in the abstract it was intended to do? (which we need BDFL channeling to know for sure ;-) It looks like it means, "add two to ". I think Antoon is unhappy that is not determined once for the one b.a expression in the statement. I sympathize, though it's a matter of defining what b.a += 2 is really intended to mean. The parses are certainly distinguishable: >>> import compiler >>> compiler.parse('b.a +=2','exec').node Stmt([AugAssign(Getattr(Name('b'), 'a'), '+=', Const(2))]) >>> compiler.parse('b.a = b.a + 2','exec').node Stmt([Assign([AssAttr(Name('b'), 'a', 'OP_ASSIGN')], Add((Getattr(Name('b'), 'a'), Const(2))))]) Which I think leads to the different (BINARY_ADD vs INPLACE_ADD) code, which probably really ought to have a conditional STORE_ATTR for the result of INPLACE_ADD, so that if __iadd__ was defined, it would be assumed that the object took care of everything (normally mutating itself) and no STORE_ATTR should be done. But that's not the way it works now. (See also my reply to Mike). Perhaps all types that want to be usable with inplace ops ought to inherit from some base providing that, and there should never be a return value. This would be tricky for immutables though, since re-binding is necessary, and the __iadd__ method would have to be passed the necessary binding context and methods. Probably too much of a rewrite to be practical. >other data type it would make a difference whether the mechanism was >BINARY_ADD (__add__) or INPLACE_ADD (__iadd__), but in this case it does >not. Both of them do the same thing. Unfortunately you seem to be right in this case. > >Actually, no "perhaps" about it -- we've already discussed the case of >lists. Well, custom objects have to be considered too. And where attribute access is involved, descriptors. > >Sometimes implementation makes a difference. I assume BINARY_ADD and >INPLACE_ADD work significantly differently for lists, because their >results are significantly (but subtly) different: > >py> L = [1,2,3]; id(L) >-151501076 >py> L += [4,5]; id(L) >-151501076 >py> L = L + []; id(L) >-151501428 > Yes. > >But all of this is irrelevant to the discussion about binding b.a >differently on the left and right sides of the equals sign. We have >discussed that the behaviour is different with mutable objects, because >they are mutable -- if I recall correctly, I was the first one in this >thread to bring up the different behaviour when you append to a list >rather than reassign, that is, modify the class attribute in place. > >I'll admit that my choice of terminology was not the best, but it wasn't >misleading. b.a += 2 can not modify ints in place, and so the >effect of b.a += 2 is the same as b.a = b.a + 2, regardless of what >byte-codes are used, or even what C code eventually implements that >add-and-store. It is so currently, but that doesn't mean that it couldn't be otherwise. I think there is some sense to the idea that b.a should be re-bound in the same namespace where it was found with the single apparent evaluation of "b.a" in "b.a += 2" (which incidentally is Antoon's point, I think). This is just for augassign, of course. OTOH, this would be find-and-rebind logic for attributes when augassigned, and that would enable some tricky name-collision bugs for typos, and code that used instance.attr += incr depending on current behavior would break. > >In the case of lists, setting Class.a = [] and then calling instance.a += >[1] would not exhibit the behaviour Antoon does not like, because the >addition is done in place. But calling instance.a = instance.a + [1] >would. > >My question still stands: why would you want instance.a = >to operate as instance.__class__.a = ? > Because in the case of instance.a += , "instance.a" is a short spelling for "instance.__class__.a" (in the limited case we are discussing), and that spelling specifies _both_ source and target in a _single_ expression, unlike instance.a = instance.a + where two expressions are used, which one should expect to have their meaning accoring to the dynamic moment and context of their evaluation. If 'a' in vars(instance) then instance.a has the meaning instance.__dict__['a'] for both source and target of +=. I think you can argue for the status quo or find-and-rebind, but since there are adequate workarounds to let you do what you want, I don't expect a change. I do think that returning NotImplemented from __iadd__ to indicate no binding of return value desired (as opposed to __iadd__ itself not implemented, which is detected before the call) might make things more controllable for custom objects. Sorry about cramming too much into sentences ;-/ Regards, Bengt Richter From gh at ghaering.de Thu Nov 10 12:32:19 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 10 Nov 2005 18:32:19 +0100 Subject: Script to export MySQL tables to csv In-Reply-To: <1131623709.334036.58800@g43g2000cwa.googlegroups.com> References: <1131623709.334036.58800@g43g2000cwa.googlegroups.com> Message-ID: <43738423.4040201@ghaering.de> Jandre wrote: > To anyone that can help > > I have 2 MySQL databases that contain large amounts of tables. I need > to be able to compare the data in the tables with older/newer versions > of the tables. I figured the easiest way would be to get the info in > csv format and then run a comparison. [...] I think the easiest way to compare tables in a SQL-based database is using SQL ... What about exporting the tables from the databases, importing those you want to compare into one database and then using set-operations in SQL using MINUS, INTERSECT. For example: select c1, c2, c3 from table1 intersect select c1, c2, c3 from table2; -- return data common in both tables select c1, c2, c3 from table1 minus select c1, c2, c3 from table2; -- data only in table1 etc. You can export specific tables from a MySQL database using the mysqldump commandline tool and then load them into the other database. HTH, -- Gerhard From jena at vlakosim.com Fri Nov 11 18:17:59 2005 From: jena at vlakosim.com (jena) Date: Sat, 12 Nov 2005 00:17:59 +0100 Subject: list of lambda Message-ID: <437526A7.4020104@vlakosim.com> hello, when i create list of lambdas: l=[lambda:x.upper() for x in ['a','b','c']] then l[0]() returns 'C', i think, it should be 'A' my workaround is to define helper class with __call__ method: class X: def __init__(self,s): self.s=s def __call__(self): return self.s.upper() l=[X(x) for x in ['a','b','c']] now it is correct, l[0]()=='A' it is OK or it is bug? can i do it correctly simplier than with helper X class? thanks Honza Prochazka From noah at noah.org Thu Nov 3 10:15:33 2005 From: noah at noah.org (Noah) Date: 3 Nov 2005 07:15:33 -0800 Subject: How can I package a python script and modules into a single script? Message-ID: <1131030933.425241.142800@o13g2000cwo.googlegroups.com> I would like to package my main script and all the modules it imports into a single script that will run just as the collection would. It should not need to package standard Python lib modules -- just my local modules. This is not the same question that would be answered with py2exe or py2app. I don't need to package the script into a binary along with Python. I expect Python to be installed. I also don't want to use distutils to install the script. The script will always run on Unix. I thought that there might be some way to run a script package from a tar file. One way would be to have the package script untar itself into a temp directory; run the main script; then delete the temporary package directory when done. That sounds clunky and prone to leave around trash if someone does a 'kill -9'. However, this might be an acceptable compromise. I'm sure that I've seen a tool around like this, but I can't find it anymore. I checked the usual places (google and sf.net). I also considered simply cutting and pasting all the modules I need into one single, giant script, but that's less appealing than the tarball idea (unless it could be done automatically). Yours, Noah From fredrik at pythonware.com Sun Nov 20 16:45:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 22:45:22 +0100 Subject: Why are there no ordered dictionaries? References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > The example above is a bit misleading, because using 'a', 'b' as keys > can give the impression that you just have to sort() the keys to have > what you want. So let's make it more realistic: > > d = { 'pid': ('Employee ID', 'int'), > 'name': ('Employee name', 'varchar'), > 'sal': ('Salary', 'float') } > > Now if I want these things to be presented in this order, I need to run > through a separate list ('pid', 'name', 'sal') that holds the order. > > Ok, you could simply use a list instead of a dictionary: > > d = ( ('pid', 'Employee ID', 'int'), > ('name', 'Employee name', 'varchar'), > ('sal', 'Salary', 'float') ) if you restructure the list somewhat d = ( ('pid', ('Employee ID', 'int')), ('name', ('Employee name', 'varchar')), ('sal', ('Salary', 'float')) ) you can still loop over the list for key, (name, type) in d: print key, name, type # e.g. generate form entry > This works as long as you *only* have to go through the list > sequentially. But maybe you want to print the name with its description > at some other place as well. Now how do you access its description > 'Employee name' so easily? but you can easily generate an index when you need it: index = dict(d) name, type = index["pid"] print name the index should take less than a microsecond to create, and since it points to the members of the original dict, it doesn't use much memory either... From nobody at this.home.com Tue Nov 29 20:05:06 2005 From: nobody at this.home.com (Krystian) Date: Wed, 30 Nov 2005 02:05:06 +0100 Subject: python speed Message-ID: 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 From mackstevenson at hotmail.com Fri Nov 11 00:22:55 2005 From: mackstevenson at hotmail.com (MackS) Date: 10 Nov 2005 21:22:55 -0800 Subject: : detecting modifier keys? References: <1131613257.499173.115180@o13g2000cwo.googlegroups.com> Message-ID: <1131686575.949631.327100@g44g2000cwa.googlegroups.com> Hi Dennis, Thanks for your help, what is happening is clear now. Just found that calling curses.raw() lets you get all scan codes. Cheers Mack From fredrik at pythonware.com Sat Nov 12 08:11:17 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Nov 2005 14:11:17 +0100 Subject: about widget construction kit References: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com><1d987df30511111400m19f02d25had206df638c1bc0a@mail.gmail.com><1131753997.446010.167410@f14g2000cwb.googlegroups.com><1d987df30511111632l350105bbo51e2f9620a156793@mail.gmail.com> <1d987df30511120400t20344394x4aa6fea4a5f7078f@mail.gmail.com> Message-ID: "Shi Mu" wrote: > > > I tried again and got the follwoing message: > > > *** cannot find Tcl/Tk headers and library files > > > change the TCL_ROOT variable in the setup.py file > > > but i have already installed TCL under python23 > > > > hmm. I still think it would be easier if you used a prebuilt version, like > > everyone else. > > > > (if you insist on using an old source release instead of the latest binaries, > > follow the instructions, and make sure the TCL_ROOT variable points to > > the location of the Tcl/Tk development libraries (the directory that con- > > tains Tcl's "include" and "lib" directories, that is)) > > what is Tcl/Tk development libraries? the stuff you get if you install tcl-devel/tk-devel on unix, or a complete Tcl/Tk distribution on Windows (e.g. ActiveTcl). > I have a tcl folder under c:\python23. Is that what you mean? if you set TCL_ROOT to that directory and setup still says that it cannot find the development files, the answer is most likely "no". can you explain why you cannot use a prebuilt version? From teimu.tm at gmail.com Sun Nov 27 00:45:49 2005 From: teimu.tm at gmail.com (teimu.tm at gmail.com) Date: 26 Nov 2005 21:45:49 -0800 Subject: why? Message-ID: <1133070348.986083.268960@g43g2000cwa.googlegroups.com> ive been using python for about two years now, and cant think of an instance where i would need that functionality. Dictionaries arent supposed to be ordered...they provide object associations, and simply that. Whatever your trying to do in python....TMTOWTDI From dcrespo at gmail.com Fri Nov 11 10:21:46 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 11 Nov 2005 07:21:46 -0800 Subject: Is there a built-in method for transforming (1, None, "Hello!") to 1, None, "Hello!"? Message-ID: <1131722506.604482.323720@f14g2000cwb.googlegroups.com> Is there a built-in method for transforming (1,None,"Hello!") to 1,None,"Hello!"? Thanks From p at ulmcnett.com Tue Nov 29 21:10:03 2005 From: p at ulmcnett.com (Paul McNett) Date: Tue, 29 Nov 2005 18:10:03 -0800 Subject: wxGrid and Focus Event In-Reply-To: References: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> <438CACF1.1020909@ulmcnett.com> <1133294056.952406.108890@g44g2000cwa.googlegroups.com> <1133298277.358823.184670@f14g2000cwb.googlegroups.com> Message-ID: <438D09FB.7020904@ulmcnett.com> Bugs wrote: > So Paul, are you saying there's a bug with the wxGrid control and if so, Yes, I think it is a bug. > do you know if there's been a bug-report submitted to the wxWidgets > and/or wxPython folks? I don't know, but I've been meaning to check. > Or is this just the way the wxGrid control works? > Thanks! wxPython/wxWidgets, like any GUI toolkit, is pretty complex. For the most part all the commonly-needed things work just fine - it is when you venture into the less-used things that you get into trouble. If I filed a proper bug report for everything wrong with wxPython/wxWidgets, I'd probably not get anything else done. But on the other hand you couldn't force me to stop using wxPython if you tried! -- Paul McNett http://paulmcnett.com http://dabodev.com From meatpodeye at yahoo.com Wed Nov 16 16:32:45 2005 From: meatpodeye at yahoo.com (Gorlon the Impossible) Date: Wed, 16 Nov 2005 21:32:45 GMT Subject: running functions Message-ID: Hello I'm not sure how to phrase this question. I have a Python function that sends MIDI messages to a synth. When I run it, I of course have to wait until it is finished before I can do anything else with Python. Is it possible to run this function and still be able to do other things with Python while it is running? Is that what threading is about? From aleax at mail.comcast.net Wed Nov 23 00:48:35 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 22 Nov 2005 21:48:35 -0800 Subject: Why are there no ordered dictionaries? References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> <1132715742.672265.259740@o13g2000cwo.googlegroups.com> <4383e912.513766727@news.oz.net> <1132719449.516504.268980@z14g2000cwz.googlegroups.com> Message-ID: <1h6g70e.19ub6oh1pa0proN%aleax@mail.comcast.net> bonono at gmail.com wrote: > Bengt Richter wrote: > > For me the implication of "sorted" is that there is a sorting algorithm > > that can be used to create an ordering from a prior state of order, > > whereas "ordered" could be the result of arbitrary permutation, e.g., > > manual shuffling, etc. Of course either way, a result can be said > > to have a particular defined order, but "sorted" gets ordered > > by sorting, and "ordered" _may_ get its order by any means. > > > But Alex seems to think that based on another external table should be > classified as "sorted" whereas I would consider it as "manual > shuffling", thus "ordered". > > I may be wrong it interpreting him though, which is why I want to > clarify. What you can obtain (or anyway easily simulate in terms of effects on a loop) through an explicit call to the 'sorted' built-in, possibly with a suitable 'key=' parameter, I would call "sorted" -- exactly because, as Bengt put it, there IS a sorting algorithm which, etc, etc (if there wasn't, you couldn't implement it through the 'sorted' built-in!). So, any ordering that can be reconstructed from the key,value data held in a dict (looking up some combinations of those in an external table is nothing special in these terms) falls under this category. But, a dict does not record anything about what was set or changed or deleted when; any ordering which requires access to such information thus deserves to be placed in a totally separate category. Alex From roy at panix.com Mon Nov 21 22:09:47 2005 From: roy at panix.com (Roy Smith) Date: Mon, 21 Nov 2005 22:09:47 -0500 Subject: Preventing modules to be read from current working directory References: <1132628732.123362.122820@g43g2000cwa.googlegroups.com> Message-ID: In article <1132628732.123362.122820 at g43g2000cwa.googlegroups.com>, ssjassal at gmail.com wrote: > Is there a way to instruct Python to import modules from standard > library even if there is one with the same name in the current working > directory? I was trying to import BaseHTTPServer.py from standard > library but was prevented by a python file with the same name in > current working directory (but there was no __init__.py). Can I use > some warning switch to print a warning on stdout? > > Thanks, > Sunpreet. Sure, just modify sys.path so the current directory is not included. See the documentation for the sys module in the library reference for more details. From iainking at gmail.com Tue Nov 8 14:26:28 2005 From: iainking at gmail.com (Iain King) Date: 8 Nov 2005 11:26:28 -0800 Subject: PNG processing with only base python install Message-ID: <1131477988.709650.265880@g44g2000cwa.googlegroups.com> My web server supports python CGI scripts, but I can't install anything else there - I can just use what they've provided. I want to process some PNG images - any ideas how I can do this with just the basic modules? Is there an image processing module written purely in Python? Iain From bonono at gmail.com Wed Nov 30 22:25:43 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 30 Nov 2005 19:25:43 -0800 Subject: Recursion bug... In-Reply-To: <1133405155.154823.134620@g47g2000cwa.googlegroups.com> References: <1133405155.154823.134620@g47g2000cwa.googlegroups.com> Message-ID: <1133407543.433860.160960@g44g2000cwa.googlegroups.com> ex_ottoyuhr wrote: > class TreeCommand: > opcode = 0 > children = [] > def __init__(self, anOpcode) : > opcode = anOpcode > opcode and children in this case is more like "class" variable in C++. If you want "instance" variable, you need to do it as self.opcode, self.children, in all methods. From kylotan at gmail.com Fri Nov 25 04:52:55 2005 From: kylotan at gmail.com (Ben Sizer) Date: 25 Nov 2005 01:52:55 -0800 Subject: Writing big XML files where beginning depends on end. In-Reply-To: References: <1132846591.731735.75120@g44g2000cwa.googlegroups.com> Message-ID: <1132912375.025326.137460@g43g2000cwa.googlegroups.com> Magnus Lycka wrote: > This won't help if we have problems keeping the whole > structure / call graph in memory at one time. Ah, I had assumed that the main problem was just that the resulting DOM was too big. Still, I don't think there would be a problem if you just constructed a very small tree and then wrote out XML based upon that, instead of using an external library for this. For example, if your only elements are node and leaf, you can store that distinction in 1 bit, as opposed to a library's naive implementation using the strings "node" and "leaf", probably 40 bits in each case. Similarly you can calculate the aggregate attributes on the fly when it comes to outputting the tree instead of storing them. -- Ben Sizer From jglands at bellsouth.net Sat Nov 26 02:28:45 2005 From: jglands at bellsouth.net (Jesse Lands) Date: Sat, 26 Nov 2005 07:28:45 +0000 Subject: Hello World-ish In-Reply-To: <1133003995.066575.54530@g49g2000cwa.googlegroups.com> References: <1133003995.066575.54530@g49g2000cwa.googlegroups.com> Message-ID: <20051126072845.0115afd0@LandLap> On 26 Nov 2005 03:19:55 -0800 "ludvig.ericson at gmail.com" wrote: > from os import * > print "Working path: %s" % os.getcwd(); > > Just wondering how you would do that .. in theory, if you get what I > mean? > I get > NameError: name 'os' is not defined > currently, which I don't know how to fix.. anyone? > your using the getcwd from os. You need to change the 'from os import *' to import os i.e. import os print "Working path: %s" % os.getcwd() -- JLands Slackware 9.1 Registered Linux User #290053 "If you were plowing a field, which would you rather use? Two strong oxen or 1024 chickens?" - Seymour Cray (1925-1996), father of supercomputing From niemand.leermann at thomas-guettler.de Tue Nov 8 11:21:12 2005 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Tue, 08 Nov 2005 17:21:12 +0100 Subject: Invoking Python from Python References: <1131466225.744361.7010@z14g2000cwz.googlegroups.com> Message-ID: Am Tue, 08 Nov 2005 08:10:25 -0800 schrieb John Henry: > Hi all, > > I have a need to create a Python script on the fly from another Python > program and then execute the script so created. Do I need to invoke > Python through os.spawnl or is there a better way? Hi, creating source code with a script, is no good solution. Once I had to maintain lisp code which stored its data in lisp code, too (incl. conditions and loops). It was a nightmare. Please explain what you want to do, and we will find a better solution. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From steve at holdenweb.com Wed Nov 2 10:19:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Nov 2005 15:19:32 +0000 Subject: Flat file, Python accessible database? In-Reply-To: References: <877jbsxnrx.fsf@lucien.dreaming> Message-ID: Peter Hansen wrote: > Karlo Lozovina wrote: > >>bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) wrote in >>news:877jbsxnrx.fsf at lucien.dreaming: >> >> >>>If you need it to be SQL-like, SQLite seems to be the right thing. >> >>Tried that one, but had some problems setting things up. On the other >>hand, BerkeleyDB + Pybsddb worked like a charm, with no setting up (under >>Cygwin). > > > I'm very curious what problems you had. In my experience SQLite > requires *nothing* I'd call "setup". You install Pysqlite or APSW, > write your code, and it runs and works. There are no configuration > steps required, nothing but creating tables (and that's a standard step > with any SQL-like database). What environment were you using, and what > kind of issues did you encounter? (I ask because I often recommend > SQLite, but would like to temper that advice if in some cases these > setup problems would cause someone trouble.) > > -Peter My experience on Cygwin was that I had to install sqlite before pySqlite worked. Maybe that's what was meant. 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 thomas.weholt at gmail.com Wed Nov 2 08:31:07 2005 From: thomas.weholt at gmail.com (Thomas W) Date: 2 Nov 2005 05:31:07 -0800 Subject: Py2Exe produced "binary" shows terminal screen on execution Message-ID: <1130938267.875586.27470@g49g2000cwa.googlegroups.com> I've produced a "binary" version of a python-script using Py2Exe and when run on WinXP it shows a terminal window for a brief moment then the window disappears. How can I avoid this? I want the script to run without being visible at all. Thanks in advance, Thomas From bonono at gmail.com Thu Nov 24 19:44:34 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 16:44:34 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: References: <1132772142.500020.16360@g44g2000cwa.googlegroups.com> <1132782865.993175.92340@g43g2000cwa.googlegroups.com> Message-ID: <1132879474.437362.196690@g43g2000cwa.googlegroups.com> Magnus Lycka wrote: > bonono at gmail.com wrote: > > Oh, find a need to shut other up ? > > > Oh, find a need to get the last word? > like you ? From jtanis at pycoder.org Thu Nov 10 13:28:46 2005 From: jtanis at pycoder.org (James Tanis) Date: Thu, 10 Nov 2005 13:28:46 -0500 Subject: Python as a HTTP Client In-Reply-To: <1131626098.168521.178600@g49g2000cwa.googlegroups.com> References: <1131626098.168521.178600@g49g2000cwa.googlegroups.com> Message-ID: <65dcde740511101028x3bfb8516q9d0f8aa5aa78a1b8@mail.gmail.com> If you haven't discovered www.python.org yet I suggest going there :P. You will find there the documentation you need under the conspicuous name library reference. Specifically the modules you'd probably most be interested in are urllib/urllib2/httplib depending on what you need. Their may be other external modules which fit your task even better, try doing a search through the Python Package Index.. On 10 Nov 2005 05:02:32 -0800, pinkfloydhomer at gmail.com wrote: > I am writing a program that has to do some lightweight HTTP > communication with a webserver on the internet. I haven't checked, but > I'm sure I could do something lowlevel like opening a socket myself and > then send/receive everything myself on this (how do I do that?), but > I'd bet that Python have some module which is more high level. > Something that would just let me connect using an URL, send a few GETs, > and receive the answer as a string/file etc. > > Does this exist, and where can I read about it? > > /David > > -- > http://mail.python.org/mailman/listinfo/python-list > -- James Tanis jtanis at pycoder.org http://pycoder.org From desparn at wtf.com Wed Nov 16 09:06:01 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Wed, 16 Nov 2005 09:06:01 -0500 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote in news:pan.2005.11.15.22.57.58.855137 at REMOVETHIScyber.com.au: > def foo(inputVal): > try: > for val in inputVal: > # do stuff > except TypeError, msg: > if msg == "iteration over non-sequence": > # handle non-iterable case > else: > # some other TypeError is a bug, so re-raise the > exception raise Does this in fact work on your system? On mine (2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]), it doesn't seem to. I tried if msg.find("iteration over non-sequence") >= 0: ... but I got a traceback, and AttributeError: TypeError instance has no attribute 'find' ... which leads me to belive that 'msg' is not type(str). It can be coerced (str(msg).find works as expected). But what exactly is msg? It appears to be of , and does not test equal to a string. This is not the least surprise to me. -- rzed From aleax at mail.comcast.net Mon Nov 7 10:54:33 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 7 Nov 2005 07:54:33 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> Message-ID: <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> wrote: > I downloaded and tried the CVS version. Division still didn't work as > expected. Now that's truly interesting... > >>> import gmpy > >>> gmpy.version() > '1.01' > >>> gmpy.mpz(9)//gmpy.mpz(4) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for //: 'mpz' and 'mpz' while, on my machine: Helen:~/gmpy/test alex$ python Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import gmpy >>> gmpy.mpz(9)//gmpy.mpz(4) mpz(2) >>> etc, etc. The CVS commit which I did before the post you're replying to gave me: ... Checking in src/gmpy.c; /cvsroot/gmpy/gmpy/src/gmpy.c,v <-- gmpy.c new revision: 1.14; previous revision: 1.13 done Mailing gmpy-commits at lists.sourceforge.net... Generating notification message... Generating notification message... done. and the logfile should be...: Helen:~/gmpy alex$ cvs log src/gmpy.c | head -20 aleax at cvs.sourceforge.net's password: RCS file: /cvsroot/gmpy/gmpy/src/gmpy.c,v Working file: src/gmpy.c head: 1.14 branch: locks: strict access list: symbolic names: import_release: 1.1.1.1 import_vendor: 1.1.1 keyword substitution: kv total revisions: 15; selected revisions: 15 description: ---------------------------- revision 1.14 date: 2005/11/07 05:29:24; author: aleax; state: Exp; lines: +83 -2 Add floordiv and truediv implementations to mpz, mpq, mpf (unittests still need to be added). ---------------------------- revision 1.13 ... Unfortunately, I didn't have a CVS $Id$ in gmpy.c (silly me!) so checking that you have the right version was hard. I have now added it, and an accessor to it from Python: Helen:~/gmpy/test alex$ python Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import gmpy >>> gmpy._cvsid() '$Id: gmpy.c,v 1.15 2005/11/07 15:43:24 aleax Exp $' >>> Can you cvs update again and check what's going on? Thanks! Alex From james_jyhu at yahoo.com Sat Nov 12 20:18:25 2005 From: james_jyhu at yahoo.com (james HU) Date: Sat, 12 Nov 2005 17:18:25 -0800 (PST) Subject: need drvmcdb.sys In-Reply-To: Message-ID: <20051113011826.36646.qmail@web50403.mail.yahoo.com> Anybody has this file in ..\system32\drivers\drvmcdb.sys in your computer? please send it to me. You will save my life! thanks a lot! James --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From avail4one at gmail.com Sun Nov 6 15:28:22 2005 From: avail4one at gmail.com (Waitman Gobble) Date: 6 Nov 2005 12:28:22 -0800 Subject: zipfile.py, fp.seek(-22,2) error Message-ID: <1131308902.758034.9270@g44g2000cwa.googlegroups.com> Hello, I am new to Python. I am having trouble with zipfile.py. On a Linux machine with python 2.4.2 I have trouble opening a zipfile. Python is complaining about the bit where it does a seek(-22,2). Looks to me like zipfile.py is trying to come back 22 bytes from the end of file. # python Python 2.4.2 (#1, Oct 27 2005, 15:13:45) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import zipfile >>> zf=zipfile.ZipFile("testdoc.odt") Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/zipfile.py", line 210, in __init__ self._GetContents() File "/usr/local/lib/python2.4/zipfile.py", line 230, in _GetContents self._RealGetContents() File "/usr/local/lib/python2.4/zipfile.py", line 240, in _RealGetContents endrec = _EndRecData(fp) File "/usr/local/lib/python2.4/zipfile.py", line 83, in _EndRecData fpin.seek(-22, 2) # Assume no archive comment. IOError: [Errno 22] Invalid argument >>> ff=open("testdoc.odt","r") >>> ff.seek(-22,2) Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 22] Invalid argument >>> ff.seek(0,2) >>> ff.seek(22,1) >>> ff.seek(22,2) >>> ff.seek(-22,2) Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 22] Invalid argument on a windows machine using python 2.4.2 zipfile.py works fine. Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.1.2 >>> import zipfile >>> zf=zipfile.ZipFile("testdoc.odt") >>> ff=open("testdoc.odt","r") >>> ff.seek(-22,2) >>> ff.seek(0,0) >>> ff.seek(0,2) >>> ff.seek(-22,2) >>> here is a windows machine using python 2.3.2 (cygwin) $ python Python 2.3.2 (#1, Oct 9 2003, 12:03:29) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> ff=open("testdoc.odt","r") >>> ff.seek(-22,2) >>> ff.seek(0,2) >>> ff.seek(22,2) >>> ff.seek(0,0) >>> ff.seek(-22,2) >>> import zipfile >>> zf=zipfile.ZipFile("testdoc.odt") >>> seek doesn't mind going -22 from the end on a windows machine but hates doing it on a linux machine.... any idears???? Thanks and Best, Waitman Gobble From peno at mailme.org Sat Nov 5 10:46:07 2005 From: peno at mailme.org (Peter Notebaert) Date: Sat, 05 Nov 2005 15:46:07 GMT Subject: how to compile c-extensions under WinXP? References: Message-ID: <3t4bf.40181$k%6.2023462@phobos.telenet-ops.be> wrote in message news:mailman.111.1131101077.18701.python-list at python.org... > What should I do to be able to compile C-extensions (with python 2.4, > winXP)? I get an error message, approximately "The .NET Framework SDK > needs to be installed"; I tried to get something from the Microsoft web > site, but maybe not the right version (or didn't set some variables), > since the error remains. Could you please help me (it will need some > patience with a computer newbie)? > You need the Microsoft .NET Visual Studio environment. A stripped and free version is available at http://msdn.microsoft.com/visualc/vctoolkit2003/ However I am not sure if everything will work with this stripped version. Peter From bignose+hates-spam at benfinney.id.au Sun Nov 20 04:44:00 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Nov 2005 20:44:00 +1100 (EST) Subject: enum 0.2: Enumerations in Python Message-ID: Howdy all, I've uploaded enum 0.2 to the Cheeseshop. The main change is that enumeration values now export their enumtype, index, and key (the things that define each value) as attributes. Thanks to Bengt for making a convincing case in favour of this. So now it's easier to ask an enumeration value about itself: >>> from enum import Enum >>> Weekdays = Enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat') >>> print [str(v) for v in Weekdays] ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] >>> today = Weekdays.tue >>> print str(today) tue >>> print repr(today) EnumValue(, 2, 'tue') >>> print today.enumtype >>> print today.index 2 >>> print today.key tue -- \ "I spilled spot remover on my dog. Now he's gone." -- Steven | `\ Wright | _o__) | Ben Finney From pwatson at redlinepy.com Tue Nov 22 15:29:41 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 22 Nov 2005 14:29:41 -0600 Subject: 2.4.2 on AIX 4.3 make fails on threading Message-ID: <3uhddoF1145hiU1@individual.net> When I try to build 2.4.2 on AIX 4.3, it fails on missing thread objects. I ran ./configure --without-threads --without-gcc. Before using --without-threads I had several .pthread* symbols missing. I do not have to have threading on this build, but it would be helpful if it is possible. The machine has the IBM C compiler. Can anyone suggest a configuration or some change that I can make to cause this to build correctly? Thanks. $ xlc 2>&1|head -1 VisualAge C++ Professional / C for AIX Compiler, Version 5 ./Modules/makexp_aix Modules/python.exp . libpython2.4.a; c++ -Wl,-bE:Modules/python.exp -lld -o python Modules/python.o libpython2.4.a -ldl -lm collect2: ld returned 8 exit status ld: 0711-317 ERROR: Undefined symbol: ._PyGILState_NoteThreadState ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. make: 1254-004 The error code from the last command is 1. Stop. From jay.dow at gmail.com Sun Nov 27 19:24:10 2005 From: jay.dow at gmail.com (jay.dow at gmail.com) Date: 27 Nov 2005 16:24:10 -0800 Subject: Writing pins to the RS232 In-Reply-To: References: <1132953944.656557.31910@g14g2000cwa.googlegroups.com> <3urg78F130gopU1@individual.net> <1133134832.031873.302400@g49g2000cwa.googlegroups.com> Message-ID: <1133137450.311146.255660@o13g2000cwo.googlegroups.com> ahhh I understand now From jeff at schwabcenter.com Thu Nov 3 14:50:55 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Thu, 03 Nov 2005 19:50:55 GMT Subject: when and how do you use Self? In-Reply-To: <436a62a7$0$11127$626a14ce@news.free.fr> References: <4369d4f0$0$18073$626a14ce@news.free.fr> <436a62a7$0$11127$626a14ce@news.free.fr> Message-ID: bruno at modulix wrote: > Steven D'Aprano wrote: > >>On Thu, 03 Nov 2005 10:14:23 +0100, bruno at modulix wrote: >> >> >> >>>Tieche Bruce A MSgt USMTM/AFD wrote: >>> >>> >>>>I am new to python, >>>> >>>> >>>> >>>>Could someone explain (in English) how and when to use self? >>>> >>> >>>Don't use self. Use other. >> >> >>Are you serious? > > > Are you seriously wondering if I am serious ? I was also wondering. What's the problem you see with the identifier "self?" From exarkun at divmod.com Sun Nov 27 22:58:32 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 27 Nov 2005 22:58:32 -0500 Subject: General question about Python design goals In-Reply-To: <7xhd9xmny1.fsf@ruckus.brouhaha.com> Message-ID: <20051128035832.1217.1468852268.divmod.quotient.1293@ohm> On 27 Nov 2005 19:49:26 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >Robert Kern writes: >> Use cases are the primary tool for communicating those practical >> needs. If you can't think of a single use case, what's the point of >> implementing something? Or rather, why should someone else implement >> it if you don't know how you would use it? > >I can't think of a single use case for the addition (+) operator >working where either of the operands happens to be the number >0x15f1ef02d9f0c2297e37d44236d8e8ddde4a34c96a8200561de00492cb94b82 (a >random number I just got out of /dev/urandom). I've never heard of >any application using that number, and the chances of it happening by >coincidence are impossibly low. But if Python were coded in a way >that made the interpreter crash on seeing that number, I'd call that >a bug needing fixing. If you seriously believe what you just wrote, you have failed to understand the phrase "use case" (and possibly a lot of other things related to programming ;) However (fortunately for you) I suspect you don't. If you really did, you may want to pick up one of those platitude-filled XP books and give it a careful read. You may find there's more there than you were previously aware. Jean-Paul From peter at engcorp.com Thu Nov 24 07:53:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Nov 2005 07:53:00 -0500 Subject: return in loop for ? In-Reply-To: References: <1132812397.369787.214140@g47g2000cwa.googlegroups.com> Message-ID: Duncan Booth wrote: > In practice it is impossible to write code in Python (or most > languages) with only one return point from a function: any line could throw > an exception which is effectively another return point, so the cleanup has > to be done properly anyway. def funcWithGuaranteedOneExitPoint(): try: # do some stuff, or pass finally: return None Of course, you might have mistyped something (e.g. "none") and still manage to get an exception, but at least in the above example it's still only a single exit point, even if not the one you thought it was. ;-) -Peter From malvert at telenet.be Sun Nov 27 09:27:02 2005 From: malvert at telenet.be (malv) Date: 27 Nov 2005 06:27:02 -0800 Subject: Tablelist-tcl-tk-tile Message-ID: <1133101622.925091.293140@o13g2000cwo.googlegroups.com> Wanting to explore tk under python, I must say that it seems to be very difficult to find the required information in one single place. I would like to give tk a try but as I need as a test something equivalent of the Qt datagrid, I don't seem manage yet to get the latest releases of tablelist, tcl, tk and tile going. Did anybody manage to make the recent releases work in Python 2.4? I manged to do some things with tablelist v4.2 but with the 8.4 versions of tcl/tk. However, for future work including tile, it would seem wise to start out from 8.5. In order to make tcl8.5, tk8.5 go, I suppose the 8.4 versions have to be removed. Do I have to remove and recompile python 2.4 as well? Is there any compact writup on how to get going without having to delve into the inner workings and wrapping of tcl? Thx. malv From jeremy at emperorlinux.com Tue Nov 29 13:32:02 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Tue, 29 Nov 2005 13:32:02 -0500 Subject: ncurses' Dark Devilry Message-ID: <1133289123.3871.44.camel@localhost.localdomain> I'm working on a project using ncurses w/ Python. As an aside, I implemented addchstr in the cursesmodule.c file in Python SVN, if anyone wants me to try and get that made permanent. AT ANY RATE... I was wondering--and this is more a general curses question rather than a Python one, but I know there are some old-timers here who have made curses obey before--is there a way to "repaint" a portion of screen without stealing the "cursor?" That is: I have a focus "wheel" of sorts that allows the user to do input on various wigets and windows and whatnot. However, if I want to quickly call addstr somewhere else in the application I have to: 1. Store the YX coords of the cursor currently 2. Use the cursor in the "current" action 3. Restore the old cursor location I know there are ways around this as I have seen curses apps that, for example, have a clock that updates every second without stealing "focus." I tried implementing/using addchstr (mentioned above) to no success. Any ideas? Is this just the plain wrong place to ask this? :) From timr at probo.com Mon Nov 21 02:28:23 2005 From: timr at probo.com (Tim Roberts) Date: Mon, 21 Nov 2005 07:28:23 GMT Subject: BaseHTTPServer module References: <1132521453.100699.199850@g43g2000cwa.googlegroups.com> Message-ID: "amfr" wrote: > >>From the BaseHTTPServer module, how do i gget the POST or GET data sent >by the client? Is it stired the the file they requested? e.g. >objectname.path Did you check the documentation in the module? You need to derive your own class from BaseHTTPServer. In that module, you need to add functions called do_GET and do_POST. In a GET request, the data is all encoded in the URL. You'll find that in self.path. In a POST request, the data is all encoded in the body of the request. You'll find that in self.rfile. You'll have to parse and decode it yourself. However, as the module documentation also tells you, that has already been done for you in SimpleHTTPServer.py. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jay.dow at gmail.com Sat Nov 12 14:50:03 2005 From: jay.dow at gmail.com (jay.dow at gmail.com) Date: 12 Nov 2005 11:50:03 -0800 Subject: directory listing In-Reply-To: References: <14cltzqwyklwl.17i7f7qnfnlh0$.dlg@40tude.net> <192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu> <1d987df30511111423o572172eay36870d09220233d7@mail.gmail.com> <1d987df30511111444m1ddfaca2qcf0acc32e49fc108@mail.gmail.com> Message-ID: <1131825003.234702.230650@o13g2000cwo.googlegroups.com> Shi Mu: Before all you were doing was defining a function with: import os def buildList( directory='c:\TEMP' ): dirs = [ ] listing = os.listdir(directory) for x in listing: x = os.path.join(directory, x) print x if os.path.isdir(x): dirs.append(x) return dirs when you python this file, it does not execute the function, it only defines it. Later Lundh told you to add: print buildList() to the end of the file. Not only does this execute buildList() but it also prints out the list "dirs" that buildList returns. So the first time it wasn't that "print x" wasn't printing anything, it was only that you weren't executing the function buildList(). If, at the end of the file, you put buildList() you will only see output values corresponding to the print x statement From eternalsquire at comcast.net Wed Nov 9 14:34:38 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 9 Nov 2005 11:34:38 -0800 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> Message-ID: <1131564878.074210.74640@z14g2000cwz.googlegroups.com> Perhaps this could be a PEP: 1) Add a system path for decryption keys. 2) Add a system path for optional decryptors supplied by user (to satisfy US Export Control) 3) When importing a module try: import routine except importation error : for all decryptors present for all keys present run decryptor upon module and retry, finally raise importation error. With PGP encryption one could encrypt the pyc's with the private key and sell a public key to the end user. The Eternal Squire From mde at micah.elliott.name Tue Nov 1 11:37:34 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Tue, 1 Nov 2005 08:37:34 -0800 Subject: Automatically creating a HOME environ variable on Windows? In-Reply-To: <1130841590.254214.311370@z14g2000cwz.googlegroups.com> References: <1130549236.679806.297670@g43g2000cwa.googlegroups.com> <1130590817.728832.291020@g44g2000cwa.googlegroups.com> <20051029164345.54C1.0.NOFFLE@fiedzia.homeip.net> <20051031112631.261A.0.NOFFLE@fiedzia.homeip.net> <1130841590.254214.311370@z14g2000cwz.googlegroups.com> Message-ID: <20051101163734.GH2575@kitchen.client.attbi.com> Maciej Dziardziel wrote: > > ...there is a group of path related functions in os.path (or > > ntpath), including expanduser, and its better to use function... On Nov 01, jim.eggleston at gmail.com wrote: > Having a function is definitely cleaner. Creating a HOME environment > variable where one does not exist in the calling shell is > misleading. > ... > It would be nice to start of with having a standard way to find out > what the home directory is. I think that is what Maciej has already pointed out. Just to clarify then: os.path.expanduser('~') is the universal/portable means to find a user's home directory, regardless of platform. So use of HOME or USERPROFILE or whatever in scripts should be discouraged. Someone please correct me if the above is wrong. I haven't tried on a mac, but linux and windows seem to behave well; i.e., linux looks for HOME, and windows appears to combine HOMEDRIVE and HOMEPATH if HOME is not set. Details are in the 2.4.2 sources' "Python24/Lib/posixpath.py" if you're curious. -- _ _ ___ |V|icah |- lliott http://micah.elliott.name mde at micah.elliott.name " " """ From mahs at telcopartners.com Tue Nov 22 19:58:13 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 22 Nov 2005 16:58:13 -0800 Subject: best cumulative sum In-Reply-To: References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> Message-ID: David Isaac wrote: for a solution when these are available. > Something like: > def cumreduce(func, seq, init = None): > """Return list of cumulative reductions. > > This can be written more concisely as a generator: >>> import operator >>> def ireduce(func, iterable, init): ... for i in iterable: ... init = func(init, i) ... yield init ... >>> list(ireduce(operator.mul, range(1,5),init=1)) [1, 2, 6, 24] >>> Michael From bokr at oz.net Wed Nov 16 02:28:45 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 16 Nov 2005 07:28:45 GMT Subject: Default method arguments References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a0a1b_1@newsgate.x-privat.org> <1132071889.676287.240030@o13g2000cwo.googlegroups.com> <1h628u2.j7q74x1i9uhlvN%aleax@mail.comcast.net> <1132081358.907286.15960@g49g2000cwa.googlegroups.com> Message-ID: <437ab976.608692984@news.oz.net> On 15 Nov 2005 11:02:38 -0800, "Martin Miller" wrote: >Alex Martelli wrote, in part: >> If it's crucial to you to have some default argument value evaluated at >> time X, then, by Python's simple rules, you know that you must arrange >> for the 'def' statement itself to execute at time X. In this case, for >> example, if being able to have self.data as the default argument value >> is the crucial aspect of the program, you must ensure that the 'def' >> runs AFTER self.data has the value you desire. >> >> For example: >> >> class A(object): >> def __init__(self, n): >> self.data = n >> def f(self, x = self.data) >> print x >> self.f = f >> >> This way, of course, each instance a of class A will have a SEPARATE >> callable attribute a.f which is the function you desire; this is >> inevitable, since functions store their default argument values as part >> of their per-function data. Since you want a.f and b.f to have >> different default values for the argument (respectively a.data and >> b.data), therefore a.f and b.f just cannot be the SAME function object >> -- this is another way to look at your issue, in terms of what's stored >> where rather than of what evaluates when, but of course it leads to >> exactly the same conclusion. > >FWIT and ignoring the small typo on the inner def statement (the >missing ':'), the example didn't work as I (and possibily others) might >expect. Namely it doesn't make function f() a bound method of >instances of class A, so calls to it don't receive an automatic 'self'' >argument when called on instances of class A. > >This is fairly easy to remedy use the standard new module thusly: > >import new >class A(object): > def __init__(self, n): > self.data = n > def f(self, x = self.data): > print x > self.f = new.instancemethod(f, self, A) > >This change underscores the fact that each instance of class A gets a >different independent f() method. Despite this nit, I believe I >understand the points Alex makes about the subject (and would agree). > Or as Alex mentioned, a custom descriptor etc is possible, and can also protect against replacing f by simple instance attribute assignment like inst.f = something, or do some filtering to exclude non-function assignments etc., e.g., (not sure what self.data is really needed for, but we'll keep it): BTW, note that self.data initially duplicates the default value, but self.data per se is not used by the function (until the instance method is replace by one that does, see further on) >>> class BindInstMethod(object): ... def __init__(self, inst_fname): ... self.inst_fname= inst_fname ... def __get__(self, inst, cls=None): ... if inst is None: return self ... return inst.__dict__[self.inst_fname].__get__(inst, cls) # return bound instance method ... def __set__(self, inst, val): ... if not callable(val) or not hasattr(val, '__get__'): # screen out some impossible methods ... raise AttributeError, '%s may not be replaced by %r' % (self.inst_fname, val) ... inst.__dict__[self.inst_fname] = val ... The above class defines a custom descriptor that can be instatiated as a class variable of a given name. When that name is thereafter accessed as an attribute of an instance of the latter class (e.g. A below), the decriptor __get__ or __set__ methods will be called (the __set__ makes it a "data" descriptor, which intercepts instance attribute assignment. >>> class A(object): ... def __init__(self, n): ... self.data = n ... def f(self, x = self.data): ... print x ... self.__dict__['f'] = f # set instance attr w/o triggering descriptor ... f = BindInstMethod('f') ... >>> a = A(5) >>> a.f > Note that a.f is dynamically bound at the time of a.f access, not retrieved as a prebound instance method. >>> a.f() 5 >>> a.f('not default 5') not default 5 >>> a.data 5 >>> a.data = 'not original data 5' Since the default is an independent duplicate of a.data a call with no arg produces the original default: >>> a.f() 5 >>> a.data 'not original data 5' >>> a.f('this arg overrides the default') this arg overrides the default Try to change a.f >>> a.f = 'sabotage f' Traceback (most recent call last): File "", line 1, in ? File "", line 10, in __set__ AttributeError: f may not be replaced by 'sabotage f' Now use a function, which should be accepted (note: a function, not an instance method) >>> a.f = lambda self: self.data*2 >>> a.f of <__main__.A object at 0x02EF3B0C>> Plainly the method was dynamically bound >>> a.f() 'not original data 5not original data 5' That was self.data*2 per the lambda we just assigned to a.f BTW, the assignment is not directly to the instance attribute. It goes via the descriptor __set__ method. >>> a.data = 12 >>> a.f() 24 >>> b = A('bee') >>> b.f > >>> b.f() bee >>> b.f('not bee') not bee >>> b.data 'bee' >>> b.data = 'no longer bee' >>> b.f() bee >>> b.data 'no longer bee' >>> b.f = lambda self: ' -- '.join([self.data]*3) >>> b.data 'no longer bee' >>> b.data = 'ha' >>> b.f() 'ha -- ha -- ha' >>> b.f = lambda self, n='default of n':n >>> b.data 'ha' >>> b.f(123) 123 >>> b.f() 'default of n' >>> a.f() 24 Now let's add another name that can be used on instances like f >>> A.g = BindInstMethod('g') >>> a.g = lambda self:'a.g' >>> a.f() 24 >>> a.g() 'a.g' >>> a.g(123) Traceback (most recent call last): File "", line 1, in ? TypeError: () takes exactly 1 argument (2 given) Aha, the bound method got self as a first arg, but we defined g without any args. >>> b.g Traceback (most recent call last): File "", line 1, in ? File "", line 7, in __get__ KeyError: 'g' No instance method b.g defined yet (A.__init__ only defines f) Make one with a default >>> b.g = lambda self, x='xdefault': x >>> b.g() 'xdefault' >>> b.g('and arg') 'and arg' >>> a.g() 'a.g' >>> If we bypass method assignment via the descriptor, we can sapotage it: >>> a.g = lambda self: 'this works' >>> a.g() 'this works' >>> a.g = 'sabotage' Traceback (most recent call last): File "", line 1, in ? File "", line 10, in __set__ AttributeError: g may not be replaced by 'sabotage' That was rejected but, >>> a.__dict__['g'] = 'sabotage' # this will bypass the descriptor >>> a.g Traceback (most recent call last): File "", line 1, in ? File "", line 7, in __get__ AttributeError: 'str' object has no attribute '__get__' The descriptor couldn't form a bound method since 'sabotage' was not a function or otherwise suitable. But we can look at the instance attribute directly: >>> a.__dict__['g'] 'sabotage' We could define __delete__ in the descriptor too, but didn't so >>> del a.g Traceback (most recent call last): File "", line 1, in ? AttributeError: __delete__ We could have made the descriptor return a.g if unable to form a bound method, but then you'd probably want to permit arbitrary assignment to the descriptor-controlled attributes too ;-) Regards, Bengt Richter From aleax at mail.comcast.net Wed Nov 30 23:31:57 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 30 Nov 2005 20:31:57 -0800 Subject: How to list currently defined classes, methods etc References: <1133401234.314572.315550@g47g2000cwa.googlegroups.com> <1133405010.479773.10050@g14g2000cwa.googlegroups.com> Message-ID: <1h6uw13.qk417rfneyvxN%aleax@mail.comcast.net> Deep wrote: > yes that works. > but, it gives one list, which contains everything. > now about inferring types? :) You may want to look at module inspect in the standard library. Alex From mwm at mired.org Tue Nov 8 16:02:25 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 16:02:25 -0500 Subject: which feature of python do you like most? References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> <1131478407.991699.231860@g43g2000cwa.googlegroups.com> Message-ID: <867jbi97ku.fsf@bhuda.mired.org> "James" writes: > Most of the responses are of the "Why Python is more pleasant than C++" > variety, but the original poster specifically said he had experience > with Perl. As such, arguments like "automatic memory management" don't > carry any weight. > >>From my experience as both a Perl and Python user--and I do prefer Perl > for many tasks--the big win for Python is when you have complex data > structures: dictionaries containing arrays, arrays of arrays, array of > dictionaries, and so on. This kind of thing is awkward in Perl (you > need to use references), but perfectly natural and obvious in Python. Further, when operators use those structures, all they really care about is the API. You can create your own classes with those APIs, and plug them in (almost) anywhere the the builtin types are used. The APIs and how to create them is well-documented, and the distribution ships with example of several of the types. Making a user class work anywhere you can put a mapping in Perl is deep magic, but easy in Python. Creating types that act like files and can be used wherever a file is used is SOP in Python; I'm not even sure it's possible in Perl (probably is, but it's again deep magic). http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From hot.favorite at gmail.com Thu Nov 10 08:59:32 2005 From: hot.favorite at gmail.com (hot.favorite at gmail.com) Date: 10 Nov 2005 05:59:32 -0800 Subject: python + ODBC + Oracle + MySQL - money Message-ID: <1131631172.260603.201050@o13g2000cwo.googlegroups.com> Hi, I'm fairly new to Python so please pardon any dumbness on my part. I plan to write an app in Python that will run on Linux and would need to connect to Oracle and MySQL. I could use MySQLdb for MySQL and cx_oracle for Oracle, but 2 different APIs in the same app is kind of painful. So I have unixODBC that gives me ODBC on Linux. The best ODBC access for Python I know is mxODBC. But that is not free for commercial use. Could someone tell me if there are other choices I have? Thanks.. From pierre.barbier at cirad.fr Sun Nov 13 04:11:04 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sun, 13 Nov 2005 10:11:04 +0100 Subject: Proposal for adding symbols within Python In-Reply-To: References: <43762d68$0$4335$626a54ce@news.free.fr> Message-ID: <43770305$0$5294$636a15ce@news.free.fr> Ben Finney a ?crit : > Pierre Barbier de Reuille wrote: > >>This proposal suggests to add symbols into Python. > > > I still don't think "symbol" is particularly descriptive as a name; > there are too many other things already in the language that might > also be called a "symbol". Well, that's the name in many languages. Then, probably all the things already in the language that might be called "symbol" may be implemented using the symbols in this proposal ... or maybe I don't see what you mean here ? > [...] >>First, I think it would be best to have a syntax to represent >>symbols. > > > I disagree. Namespaces would be fine, and would also make clear which > values were related to each other; e.g. for your "state of an object" > use case, it's useful to have all the states in one namespace, > separate from unrelated states of other classes of objects. > > >>Adding some special char before the name is probably a good way to >>achieve that : $open, $close, ... are $ymbols. > > > Counterproposal: > > FileState = SomeTypeDefiningStates( 'open', 'closed' ) > > thefile.state = FileState.open > if thefile.state == FileState.closed: > print "File is closed" > > So all that's needed here is the type SomeTypeDefiningStates, not a > new syntax. The problem, IMHO, is that way you need to declare "symbols" beforehands, that's what I was trying to avoid by requiring a new syntax. >>One possible way to implement symbols is simply with integers >>resolved as much as possible at compile time. > > > I believe all your requirements and motivations could be met with an > Enum type in the language. Here's an implementation using a sequence > of integers for the underlying values: > > "First Class Enums in Python" > > > An enumerated type would also allow values from that type to be > compared with cmp() if their sequence was considered important. e.g. > for object state, the "normal" sequence of states could be represented > in the enumeration, and individual states compared to see if they are > "later" that each other. If sequence was not considered important, of > course, this feature would not get in the way. > Well, I don't think enumarated objects ARE symbols. I can see two "problems" : 1 - in the implementation, trying to compare values from different groups raises an error instead of simply returning "False" (easy to fix ...) 2 - You have to declare these enumerable variables, which is not pythonic IMO (impossible to fix ... needs complete redesign) In the end, I really think symbols and enum are of different use, one of the interest un symbols being to let the compiler does what he wants (i.e. probably what is the most efficient). Thanks for your reply, Pierre From pmartin at snakecard.com Mon Nov 21 14:27:46 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Mon, 21 Nov 2005 13:27:46 -0600 Subject: compiling Python under Windows References: <29pgf.12621$ih5.5110@dukeread11> Message-ID: Philippe C. Martin wrote: > My mistake: The makefile (as written in the readme!) looks for bzip 1.0.2 > PS: since bzip.org does not have 1.0.2 source anymore, can I just rename 1.0.3 ? Regards, Philippe > Sorry, > > Philippe > > > > Philippe C. Martin wrote: > >> Hi, >> >> I'm currently blocking on bzip2: >> >> python is in c:\python.2.4.2 >> and bz2 is in c:\bzip2-1.0.3 >> >> Since the readme say subprojects should be two directories above PCbuild, >> I assume I'm OK. >> >> I added c:\bzip2-1.0.3 to the include and link path, but I get: >> """ >> Performing Pre-Link Event ... >> The system cannot find the path specified >> NMAKE: fatal error U1052: file 'makefile.msc' not found >> >> c:\bzip2-1.0.3 does hold a makefile.msc. >> >> Any clue ? >> >> Thanks, >> >> Philippe From bearophileHUGS at lycos.com Sat Nov 12 21:12:03 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 12 Nov 2005 18:12:03 -0800 Subject: Iterator addition In-Reply-To: References: <7x4q6lm87q.fsf_-_@ruckus.brouhaha.com> <1h5s1dp.i6hnk31bmv4xN%aleax@mail.comcast.net> <7xslu5cdhz.fsf@ruckus.brouhaha.com> Message-ID: <1131847923.361393.233530@g47g2000cwa.googlegroups.com> Tom Anderson: > And we're halfway to looking like perl already! Perhaps a more pythonic > thing would be to define a "then" operator: > all_lines = file1 then file2 then file3 Or a "chain" one: > all_lines = file1 chain file2 chain file3 Bearophile From cyril.bazin at info.unicaen.fr Wed Nov 16 08:51:06 2005 From: cyril.bazin at info.unicaen.fr (Cyril Bazin) Date: Wed, 16 Nov 2005 14:51:06 +0100 Subject: initialising a list of lists In-Reply-To: References: Message-ID: Hello, >>> b = [[] for _ in xrange(6)] # <- note the xrange! >>> b[3].append('X') >>> b [[], [], [], ['X'], [], []] This syntax might be less hairy but could be better when you use large table. You can hide this syntax by making a function: def buildMatrix(nbRows): return [[] for _ in xrange(nbRows)] Then you call: >>> b = buildMatrix(6) Or: >>> b = buildMatrix(nbRows=6) Is it better for you? Cyril On 11/16/05, Peter Kleiweg wrote: > > Fredrik Lundh schreef op de 16e dag van de slachtmaand van het jaar 2005: > > > Peter Kleiweg wrote: > > > > > This does not what I want it to do: > > > > > > >>> a = [[]] * 6 > > > >>> a[3].append('X') > > > >>> a > > > [['X'], ['X'], ['X'], ['X'], ['X'], ['X']] > > > > > > This does what I want: > > > > > > >>> b = [[] for _ in range(6)] > > > >>> b[3].append('X') > > > >>> b > > > [[], [], [], ['X'], [], []] > > > > > > The first is clear and wrong. The second is hairy and right. > > > Is there a way to do it clear and right? > > > > > http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list > > In other words: no there isn't. > > -- > Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) > info: http://www.let.rug.nl/~kleiweg/ls.html > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cito at online.de Tue Nov 22 03:40:33 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 09:40:33 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> Message-ID: Alex Martelli schrieb: > Perl hashes now keep track of 'order of keys'? That's new to me, they > sure didn't back when I used Perl! Maybe I shouldn't have talked about Perl when I'm an ignoramus about that language... You're right, Perl has unordered arrays. That was new to me since I associate the term "array" always with "ordered" and I just remembered that PHP's assoc arrays are similar to Perl's but in fact, and the examples I have read did not mention about that problem. > What about PHP? You can conclude that PHP's assoc arrays are ordered from the fact that the language provides a ksort() function to order the keys. And I think PHP's insertion order is the one I mentioned in my last post. Anyway, it would be interesting to examine this in detail and how this is implemented in other languages. > "first insertion (since the last deletion if any)" is ONE unambiguous > definition, but surely not "_the_ ONE" with emphasis on ``the''. > I see nothing _ambiguous_ (nor _unnatural_) in being interested in the > *last* insertion, for example; indeed if phrased as "upon insertion, put > the key at the end of the sequence" (whether it was already elsewhere in > the sequence of not), with no need for conditionals regarding previous > existence, it might appear more "conceptually compact". But it would not satisfy the concept of "keys of a dictionary" which are always unique. BTW, there are some boundary conditions that should be fulfilled for the insertion order, most obviously: If you define an ordered dict that way: d = odict() d['a'] = 1 d['b'] = 2 d['c'] = 3 The keys should then be orderes as ('a', 'b', 'c'). > Anyway -- subclassing dict to implement your definition is reasonably > easy, and we could put the resulting package on the Cheese Shop. I hope > python.org keeps good enough statistics to be able to tell us, a couple > months later, how many people downloaded said package, vs how many > people downloaded a complete Python distro; of course, that ratio is > biased (in favour of the package) by the fact that many people already > have a complete distro available, while initially nobody would have the > package, but if we measure when things settle, after letting a month of > two or 'transient' pass, that effect might be lessened. That would be also biased (in favour of Python) by the fact that probably very little people would look for and use the package in the cheese shop if they were looking for ordered dicts. I for example would probably use ordered dicts if they were part of the standard lib, but not if I have to install it as an obscure separate package. So I don't think that will give us a real clue how many people would like ordered dicts in the standard lib. But anyway, if I find some time, I will research a little bit more about the issue and create such a package, because it seems to me that the existing packages and recipes are not really satisfying and you're right it seems to be reasonably easy. It's on my todo list now... -- Christoph From bokr at oz.net Fri Nov 18 00:12:43 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 18 Nov 2005 05:12:43 GMT Subject: Reading a file in same directory as code with relative path References: <1132277395.552201.81830@g14g2000cwa.googlegroups.com> Message-ID: <437d612d.85761027@news.oz.net> On 17 Nov 2005 17:29:55 -0800, dan.j.weber at gmail.com wrote: >I'm trying to read an XML file in the same directory as my python code, >using minidom: > >document = xml.dom.minidom.parse("data.xml") > >How can I read in the file "data.xml" without knowing it's full >path--just that it's in the same directory as my code file? Thanks for >any help with this. I'm new to python and really liking it so far. > ----< showmydir.py >------------ import os print dir() print __file__ print os.path.abspath(__file__) print os.path.dirname(os.path.abspath(__file__)) print os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data.xml') -------------------------------- When run, outputs (in my directory context): [21:07] C:\pywk\clp>py24 showmydir.py ['__builtins__', '__doc__', '__file__', '__name__', 'os'] showmydir.py C:\pywk\clp\showmydir.py C:\pywk\clp C:\pywk\clp\data.xml If I go somwhere else and execute it, e.g. from a sibling directory [21:08] C:\pywk\grammar>py24 ..\clp\showmydir.py ['__builtins__', '__doc__', '__file__', '__name__', 'os'] ..\clp\showmydir.py C:\pywk\clp\showmydir.py C:\pywk\clp C:\pywk\clp\data.xml (Hm, that's an interesting outcome for __file__ ) HTH Regards, Bengt Richter From mclister at zeesource.net Mon Nov 7 17:33:20 2005 From: mclister at zeesource.net (Claire McLister) Date: Mon, 7 Nov 2005 14:33:20 -0800 Subject: [OT] Map of email origins to Python list In-Reply-To: References: Message-ID: On Nov 7, 2005, at 10:23 AM, Rocco Moretti wrote: > It's also a testament to the limited value of physically locating > people > by internet addresses - If you zoom in on the San Fransico bay area, > and > click on the southern most bubble (south of San Jose), you'll see the > entry for the Mountain View postal code (94043) - a massive list which > contains mostly gmail.com accounts, but also contains accounts with .de > .ca .uk .pl .it .tw and .za domains. I doubt all of the people in that > list live in sunny California, let alone in Mountain View proper. > Indeed, locating people from IP is not that easy or correct. We are, however, not trying to suggest that we can find people's locations this way. We are just trying to pin-point the origins of emails to a group. The flaw that you point out is due to problems in our approach of how we find the 'origin' IP. We try to get a best guess estimate of the originating IP and its location. If we cannot find that, we fall back on the earliest server that has a location information. Clearly this marks quite a few email origins in the wrong way. It doesn't do the collection of ALL gmail addresses this way, however. If you do a filter on 'gmail' in the 'Name' filter, you'll see a lot of gmail addresses all over the world. So, we need to do a better job of guessing the originating IP, and not try to go too far forward. From cito at online.de Thu Nov 24 10:34:11 2005 From: cito at online.de (Christoph Zwerschke) Date: Thu, 24 Nov 2005 16:34:11 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <8664qi3oef.fsf@bhuda.mired.org> References: <8664qi3oef.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Are you sure dict.values() should be a set? After all, values aren't > guaranteed to be unique, so dict(a = 1, b = 1).values() currently > returns [1, 1], but would return set([1]) under your proposal. Good point. Contrary to the keys, the values are not unique. Still, it would make sense to only return the set (the value set of the mapping) because this is usually what you are interested in and you'd think the information about which value belongs to which key is lost anyway. However (see other postings in this thread) this last statement is wrong: If you call keys() and values() consecutively, then they are guaranteed to correspond to each other. If values() would return a set, this would be completely broken. > What about dict.items()? Actually, if keys() would be a set, this should return a set, too (the set of key/value tuples). >>For instance, by allowing the set operator "in" for dictionaries, >>instead of "has_key". > "in" already works for dicdtionaries: I know. I wanted to use it as an example where set operations have already been made available for dictionaries. I know, 'in' has existed for lists and tuples long before sets, but actually it is a native set operation. From a mathematical point of view, it would have been nice if Python had defined "set" as a basic data type in the beginning, with lists, tuples, dictionaries as derived data types. By the way, i wonder why the common mathematical notation { 1,2,3 } was not allowed for set((1,2,3)). It would not clash with the dictionary notation which requires additional colons. -- Christoph From roccomoretti at hotpop.com Fri Nov 4 10:23:24 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 04 Nov 2005 09:23:24 -0600 Subject: I Need Motivation Part 2 In-Reply-To: References: Message-ID: blah at blah.blah wrote: > i m losing my motivation with python because there are sooo many > modules, that i cant just learn them all, As other's have said, don't bother. If you ever need to use a module that you don't know, just go to http://docs.python.org/lib/lib.html (easily accessable from the "Documentation" link on the Python Home page), or a local copy, and scrounge around. I might suggest skimming it once, to see what is possible, but it isn't nessasary to "learn" it. -- Knowing that there is a Python module in the standard library to do CSV/Date manipulation/MD5/etc is sufficient. You don't even need to know what the module is called - a minute skimming the TOC will point you in the right direction. From erniedude at gmail.com Wed Nov 2 11:57:55 2005 From: erniedude at gmail.com (Ernesto) Date: 2 Nov 2005 08:57:55 -0800 Subject: Subprocess.Popen - passing args help In-Reply-To: <1130948913.627882.194220@g49g2000cwa.googlegroups.com> References: <1130948913.627882.194220@g49g2000cwa.googlegroups.com> Message-ID: <1130950675.968535.219010@g43g2000cwa.googlegroups.com> A nice person from another thread helped me... a = 'disable "@USB\VID_0403&PID_6010&MI_00\7&15E4F68&1&0000' print a disable "@USB\VID_0403&PID_6010&MI_00&15E4F68&1&0000 \7 is the ASCII bell so your args may be different from what you think. I thought the quote method I have fixes this problem, but I guess I was wrong. Anyone have suggestions on how I can get that parameter in there without the '\7' part getting lost? From norman at littletank.org Thu Nov 10 12:00:38 2005 From: norman at littletank.org (Norman Silverstone) Date: Thu, 10 Nov 2005 17:00:38 +0000 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> <1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: On Fri, 11 Nov 2005 01:39:40 +1100, Steven D'Aprano wrote: > On Thu, 10 Nov 2005 13:30:05 +0000, Norman Silverstone wrote: > >>> In that case, think of "bisection". Originally, all the computer knows >>> is that the number is in some range, say 0 to 100. It can then guess >>> the midpoint, 50. If it's right, yay! Otherwise: if it's told to go >>> lower, then the range is now 0 to 49 -- if higher, it's 51 to 100; in >>> each case the range was just halved (actually, a bit more than halved). >> >> Thank you, I thought that might be the case. So, I will have to settle >> down and try to write some pseudo-code first. I hope to be back. > > Heh, you will find that Python is practically executable pseudo-code! > > Untested: > > > def guess_number(): > # please don't cheat the poor computer... > print "Guess a number." > lo = 0 > hi = 100 > while True: > guess = (lo+hi)//2 > ans = raw_input("Is it %d? y/n " % guess) > if ans in ('y', 'yes'): > break > ans = raw_input("Too high? y/n ") > if ans in ("y", "yes"): > hi = guess-1 > else: > lo = guess+1 > > This should run, and it will *almost* do what you want. Thanks for that but I think it is too simplistic. It appears OK for the first guess, which is 50 but, what about the next guess. If the guess is too high then the next guess has to be 50/2. However, if it is too low then the next guess must be first guess + (100-second guess)/2. In general terms, if guess is too high then next guess must (guess - lowest possible)/2 and if too low then it is guess + (highest possible - guess)/2. Comments please. Norman From steve at holdenweb.com Fri Nov 4 00:26:25 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Nov 2005 05:26:25 +0000 Subject: installing PygreSQL and psychopg2 modules (a newbie question) In-Reply-To: <000001c5e07d$054f63f0$52bffea9@zlatkovyfkpgz6> References: <000001c5e07d$054f63f0$52bffea9@zlatkovyfkpgz6> Message-ID: Zlatko Mati? wrote: > Hello. > I was trying to install PygreSQL and psychopg2 in order to use python as front-end for PostgreSQL, on WIndows XP. > When I tried to install by calling setup.py from command prompt ("setup.py install"), in both cases I had the same error: > > "error: Python was built with version 7.1 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed." > > It looks like this: > "C:\Downloads\Python\psychopg\psycopg2-2.0b5\psycopg2-2.0b5>setup.py install > running install > running build > running build_py > running build_ext > building 'psycopg2._psycopg' extension > error: Python was built with version 7.1 of Visual Studio, and extensions > need t > o be built with the same version of the compiler, but it isn't installed. > > C:\Downloads\Python\psychopg\psycopg2-2.0b5\psycopg2-2.0b5>pause > Press any key to continue . . ." > > What does it mean ? What am I supposed to do? > > Thanks, > > Zlatko > I recently installed psycopg2 - is this the same package you wanted? If so, Google for "psycopg2-2.0b4-pre4.win32-py2.4.exe", which is a pre-bult binary installer (though the version I picked up wasn't able to handle mx.datetime objects, this shouldn't be a problem unless you have other modules that generate them). Never used PygreSQL, so can;t help there (though you might try a similar trick and Googal for "PygreSQL Windows installer", say). If you look at http://www.holdenweb.com/Python/ you'll find a link to Mike Fletcher's page describing how you can install and use the free Microsoft toolchain to compile extension modules so they will be compatible wiht the Python installed by the Windows installer from python.org. 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 johnjsal at NOSPAMgmail.com Thu Nov 3 09:42:54 2005 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 03 Nov 2005 14:42:54 GMT Subject: another beginner sort of question In-Reply-To: <86hdaujn15.fsf@bhuda.mired.org> References: <86hdaujn15.fsf@bhuda.mired.org> Message-ID: Thanks! Mike Meyer wrote: > John Salerno writes: > [Wants to learn C# and Python simultaneously.] > >>So my question is, is this feasible? > > > Should be. It might be faster to do them sequentually. > > >>Or does learning Python require (or entail) learning all the details >>behind it? > > > Not really. There are some traps you can fall into that are obvious if > you know how the underlying implementation works, but even for those, > you just need the general idea, not the details. > > >>Also, do I need to know anything about C or C++? > > > No. In fact, the less you know about them, the less you'll have to > unlearn to use Python effectively. > > >>Python seems to connected to those languages that I'm afraid >>learning Python by itself might not be practical, but hopefully >>that's unfounded. > > > CPython (the implementation most people mean when they say "Python") > is written in C, and has well-defined APIs for putting an interpreter > into a C program, or making functionality from a C library available > to a CPython program. Other implementations have similar hooks for > different languages. Unless you want to get into the internals of an > implementation, to embed Python in an application, or to write a > Python extension (usually because you're wrapping an existing > library), you won't need to worry about any of these. > > One thing. While Python is called a "scripting language", it doesn't > have facilities for dealing with shell scripting that other "scripting > languages" have. As such, it's harder to do shell scripting type > things in Python than in those languages. On the other hand, it's > easier than doing them in C, for the same reason that doing pretty > much anything in Python is easier than doing it in C. On the gripping > hand, if you do things pythonically instead of like you'd do them in a > shell script, you may find that Python is easier than the shell > script. > > Message-ID: <1132081799.028969.8750@o13g2000cwo.googlegroups.com> QuadriKev wrote: >I would like to see examples of programs written. http://python.codefetch.com lets you search published books for Python example source code. > I am also interested in using Telnet to check services and things on > the Linux server. a search for "telnet" on codefetch brought up this nice example source code: http://www.codefetch.com/cache?url=http://examples.oreilly.com/pythoncook2/cb2_examples.zip&path=cb2_examples/cb2_15_9_sol_1.py&lang=python&qy=telnet from the book _Python Cookbook_ From skip at pobox.com Fri Nov 18 17:05:36 2005 From: skip at pobox.com (skip at pobox.com) Date: Fri, 18 Nov 2005 16:05:36 -0600 Subject: Choose meaningful subjects for posts [was: Re: newb ?] In-Reply-To: <11nsgj6250bne4e@corp.supernews.com> References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> <86u0eaj5ed.fsf@bhuda.mired.org> <11nsbh2r64kb9ae@corp.supernews.com> <17278.14762.150392.942325@montanaro.dyndns.org> <11nsgj6250bne4e@corp.supernews.com> Message-ID: <17278.20528.91462.824282@montanaro.dyndns.org> Grant> If I allowed news posts to interrupt me, I'd never get anything Grant> done. I limit e-mail to things that really do require fairly Grant> immediate attention. Well, I do try to limit the number of things I pay attention to. However, as the "Python guy" at work, participating in this group and the python-dev mailing list overlap my daytime duties. There are a few other things I watch as well (matplotlib, pygtk, moin, scipy, etc). Running through all of them in one place simplifies my life. Last time I checked, most of Usenet was crap (overrun with spam), so on those few occasions where I need something I just use Google to search for help and post via Google or Gmane. I never have to worry about NNTP. I have no idea if my ISP (Comcast) even provides NNTP access. Skip From onurb at xiludom.gro Fri Nov 11 12:32:40 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 11 Nov 2005 18:32:40 +0100 Subject: Import statements for timeit module In-Reply-To: <1131724191.716900.314710@o13g2000cwo.googlegroups.com> References: <1131715618.580594.68630@z14g2000cwz.googlegroups.com> <4374b8f8$0$31636$626a14ce@news.free.fr> <1131724191.716900.314710@o13g2000cwo.googlegroups.com> Message-ID: <4374d5b9$0$21032$636a55ce@news.free.fr> ChaosKCW wrote: > So timeit is mostly useless then ? > I wouldn't say so. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mwm at mired.org Fri Nov 25 13:48:12 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 25 Nov 2005 13:48:12 -0500 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <86hda2x9ny.fsf@bhuda.mired.org> Message-ID: <86k6ewimxf.fsf@bhuda.mired.org> Antoon Pardon writes: > Op 2005-11-24, Mike Meyer schreef : >> Antoon Pardon writes: >>>> The usual response is "That's not the Python way." That's not calling >>>> someone dumb, just pointing out that they don't yet fully understand >>>> the Python way. >>> "That is not the Python way", is just saying "Python doesn't have it" >>> in other words. So it can't be the answer to why python can't have >>> something. >> >> No, it isn't. At least, it isn't when I use it. A language is more >> than just an accumulation of features. Well, a good language is more >> than just an accumulation of features - there's a philosophy >> underlying the language, that guides what features are added and what >> features aren't. Other languages have other philosophies, and wind up >> being good for other things. > > But how this philosophy influences design is not straight forward. > > The ternary operator was thought of to go against the philosopy, By who? > and now seems to be at least compatible with the philosophy. > > So when someone asks why it is not in python, saying "It is not > the python way" still doesn't answer the question, because the > person would probably still like to know what in his proposal > is against the python philosophy and why. Sometimes, such things are easy to explain, and they'll generally get that explanation. Sometimes they aren't, so you're reduced to pointing out similar - but more obvious - things that aren't in the language, and "import this", and suggesting that they try it for a while and see how it works >> My vision >> isn't perfect - I've changed my mind about things: I used to want real >> macros, and I initially disliked list comprehensions. My vision >> doesn't agree with the developers - notably including Guido's - a lot >> of the time. On the other hand, they haven't done anything that >> strikes me as so wrong that I want to spend the time required working >> on Python rather than in Python to allow me to get it fixed. > > I see nothing wrong with that. But I would apreciate it, should > you be more open about something being your personal vision. > To me something like: "That is not the python way" comes accross > as: "You just don't understand about python, if you ask/propose > something like that" That's essentially true. In some cases, the reasons can be explained without understanding about python. In some cases, they can't. > It gives me the feeling the person is saying something like: "Python > is like this, I like it this way, so nobody better suggests this > changes". You're carrying things a step to far, going from explaining an overly brief statement to imagining a motive for said statement. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From kylotan at gmail.com Tue Nov 1 06:07:38 2005 From: kylotan at gmail.com (Ben Sizer) Date: 1 Nov 2005 03:07:38 -0800 Subject: Automatically creating a HOME environ variable on Windows? In-Reply-To: References: <1130549236.679806.297670@g43g2000cwa.googlegroups.com> Message-ID: <1130843258.600599.180750@g47g2000cwa.googlegroups.com> > jim.eggleston at gmail.com napisa?(a): > > MS recommends using %USERPROFILE%, as the above in many cases returns > "C:\", which is wrong. I'm guessing this is why IDLE creates a directory in the root of my Win98 system whenever I use it. It would be great if this could be fixed for the next version. -- Ben Sizer. From bdesth.quelquechose at free.quelquepart.fr Thu Nov 17 18:44:34 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 18 Nov 2005 00:44:34 +0100 Subject: Zope vs Php In-Reply-To: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> Message-ID: <437d0b7a$0$7585$636a15ce@news.free.fr> Steve a ?crit : > We are building a web app and the our backend is currently using python > with php front end. We would like to do everything in python but php > for our front end is so easy to use. We would like to use zope on our > front end(no experience with it) can anyone provide any experience with > this? > >>From what I can tell you can't just do > <% > #python code > %> > some title Yuck. > this is what we would like to do with session support and things that > php provides? > I don't think Zope is the right solution for you. It's a world in itself... If you're looking for a PHP-like solution, the closer is probably mod_python + [Cheetah or PSP]. My 2 cents... From paul at boddie.org.uk Wed Nov 23 09:01:30 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Nov 2005 06:01:30 -0800 Subject: wxPython Licence vs GPL References: <43838497$1@nntp0.pdx.net> Message-ID: <1132754490.193962.172940@f14g2000cwb.googlegroups.com> Steven D'Aprano wrote: > On Tue, 22 Nov 2005 12:57:12 -0800, Scott David Daniels wrote: > > I would, at the very least, acknowledge the wxPython origin of the code > > whether any remains or not (credit is appreciated and cheap to give). > > Ha ha, don't ask movie director James Cameron about *that*. On the basis > of a throw-away line that he "got the idea" for Terminator from a couple > of Harlan Ellison stories, he and the studio were sued by Ellison, who > ultimately won and was awarded millions. Yes, but this anecdote is more relevant to various "modern" patent regimes, not copyright. > In this world where ideas are thought to be property (if only I could > own the idea that ideas can be owned) the safest position is to claim > you've never read a book, seen a line of code, been to the movies or heard > a song in your life. This is somewhat difficult given that the questioner wanted to include "evidence" of having seen the code (ie. the code itself) in his own work. Not reproducing copyright attributions is a sure way to be on the end of copyright infringement proceedings. > (Only half joking.) I should hope so. But I imagine the questioner was looking for serious advice. Paul From fredrik at pythonware.com Thu Nov 10 02:06:27 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Nov 2005 08:06:27 +0100 Subject: How to set program name in Python? ($0 in Perl) References: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > > Is there a way to set the program name in Python, similar to $0 in > > Perl? > > > >>From `man perlvar`: > > > > $0 Contains the name of the program being executed. On some oper- > > ating systems assigning to "$0" modifies the argument > > area that > > the ps program sees. This is more useful as a way of > > indicat- > > ing the current program state than it is for hiding the > > program > > you're running. (Mnemonic: same as sh and ksh.) > import sys > print sys.argv[0] that *gets* the name, but assigning to sys.argv[0] doesn't *set* it (afaik). setting the name involves overwriting the C level argv array, several large buckets of worms, and huge portability issues, and is thus better left to non- standard extensions. From rrr at ronadam.com Wed Nov 2 02:47:38 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 02 Nov 2005 07:47:38 GMT Subject: dictionary that have functions with arguments In-Reply-To: <1130911116.235217.75310@g43g2000cwa.googlegroups.com> References: <1130903698.450993.268680@f14g2000cwb.googlegroups.com> <0dX9f.181261$xl6.80345@tornado.tampabay.rr.com> <1130911116.235217.75310@g43g2000cwa.googlegroups.com> Message-ID: Neal Norwitz wrote: > Ron Adam wrote: > >>Eval or exec aren't needed. Normally you would just do... >> >> execfunc['key1'](**args) >> >>If your arguments are stored ahead of time with your function... >> >> Committed revision 41366. Committed revision 41366 ? >>You could then do... >> >> func, args = execfunc['key1'] >> func(**args) > > > Interesting that both Ron and Alex made the same mistake. Hmmm, makes > me wonder if they are two people or not... > > If args is a tuple, it should be: > > func(*args) No mistake at all, I simply reused the name the OP used in his example. >>> execfunc = { 'key1' : func1(**args) } There's no rule that says you can't name a dictionary 'args', and it wasn't part of the posters question. > If you want the full generality and use keyword args: > > func(*args, **kwargs) I tend to prefer (*args, **kwds) myself. There are also times when I don't want full generality. In many cases the less general your arguments are to a function the easier it is to catch errors. Cheers, Ron From cito at online.de Wed Nov 23 15:56:57 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 21:56:57 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> <1132715742.672265.259740@o13g2000cwo.googlegroups.com> Message-ID: Ganesan Rajagopal wrote: > the definition of "sorted" and "ordered", before we can > go on ? Sorted > would be ordered by key comparison. Iterating over such a container will > give you the keys in sorted order. Java calls this a SortedMap. See > http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html C++ STL > map container is also a Sorted Associative container. See > http://www.sgi.com/tech/stl/Map.html Ganesan Exactly, that's "sorted." "Ordered" means the same there is some order between the existing elements, but there is no magic (i.e. a general comparison function) for ordering new elements. Thus, if you add an element to an ordered collection, it simply gets appended (is considered as the greatest of all elements) by convention, whereas if you add an element to a sorted collection, it will be inserted into the correct place by using the comparison function. -- Christoph From zanesdad at bellsouth.net Wed Nov 30 08:09:19 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 30 Nov 2005 08:09:19 -0500 Subject: How could I ask Thread B to call B().Method() from inside Thread A's run? In-Reply-To: <311b5ce10511300311u201c31aej6cc7f1e8cd42e232@mail.gmail.com> References: <311b5ce10511300311u201c31aej6cc7f1e8cd42e232@mail.gmail.com> Message-ID: <438DA47F.2050506@bellsouth.net> could ildg wrote: > I have 2 thead instances, > A and B, > In A's run method, if I call B.Method(), it will be executed in thead A, > but I want B.Method() to be executed in B's thread. > That's to say, I want to tell Thead B to do B's stuff in B's thread, > kinda like PostMessage in win32. > Can I do it in python? > How? > Thank you in advance. Here is a really simple, stupid example of what I think you're trying to do. You probably want to use a Queue between your threads. ########################## #!/usr/bin/python import threading import Queue class A(threading.Thread): def __init__(self, q): self.q = q threading.Thread.__init__(self) def run(self): for i in range(10): print "Thread A putting \"something\" onto the queue" self.q.put("something") self.q.put("stop") class B(threading.Thread): def __init__(self, q): self.q = q self.proceed = True threading.Thread.__init__(self) def do_something(self): print "Thread B doing something" def do_stop(self): print "Thread B should stop soon" self.proceed = False def run(self): while self.proceed: print "Thread B pulling sommething off of the queue" item = q.get() print "Thread B got %s" % item getattr(self, "do_" + str(item))() if __name__ == "__main__": q = Queue.Queue() a = A(q) a.start() b = B(q) b.start() a.join() b.join() ############################## HTH, - jmj From cito at online.de Tue Nov 22 04:26:22 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 10:26:22 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <438258f2.411334718@news.oz.net> References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <438258f2.411334718@news.oz.net> Message-ID: Bengt Richter wrote: > d = OrderedDict(); d[1]='one'; d[2]='two' =>> list(d) => [1, 2] > ok, now we do d[1]='ein' and what is the order? list(d) => [2, 1] ?? > Or do replacements not count as "insertions"? If you simply set a value for a key that already exists, the order should not be changed. I think this is intuitive. > Or maybe you want to permit append and NOT prevent > [('a',1), ('a':2)] and maybe d['a'] => [1, 2] ??? You could ask the same question about dict. I think that is not an option. Why should you want odict behave different than dict? I still believe that the concept of an "ordered dictionary" ("behave like dict, only keep the order of the keys") is intuitive and doesn't give you so much scope for ambiguity. But probably I need to work on an implementation to become more clear about possible hidden subtleties. -- Christoph From donn at u.washington.edu Mon Nov 7 17:20:07 2005 From: donn at u.washington.edu (Donn Cave) Date: Mon, 07 Nov 2005 14:20:07 -0800 Subject: O_DIRECT on stdin? References: <11mvbsv4lbri8d@corp.supernews.com> Message-ID: In article , jepler at unpythonic.net wrote: > Here's some text from my open(2) manpage: > Transfer sizes, and the alignment of user buffer and file offset must > all > be multiples of the logical block size of the file system. Does that apply in the example he gave, < /dev/sda1 ? It seems to me this would not go through any filesystem anyway. That might account for the "invalid argument" error, but at any rate it would be irrelevant. Plus it doesn't seem to score very high on portability, according to the Linux man page I'm looking at -- apparently not a POSIX or any such standard, just borrowed from Irix in recent Linux versions, and FreeBSD with slightly different behavior. Don't see any trace of it in NetBSD, MacOS X. > It's unlikely that in practice you can get Python's sys.stdin.read() or > os.read() to reliably use a buffer that fits the alignment restriction. Though of course os.read() would eliminate one layer of buffering altogether. Might be worth a try. Donn Cave, donn at u.washington.edu From manuelg at gmail.com Fri Nov 18 17:41:43 2005 From: manuelg at gmail.com (manuelg at gmail.com) Date: 18 Nov 2005 14:41:43 -0800 Subject: Reading a file in same directory as code with relative path References: <1132277395.552201.81830@g14g2000cwa.googlegroups.com> Message-ID: <1132353703.254112.289390@f14g2000cwb.googlegroups.com> Answer to a similar question: http://groups.google.com/group/comp.lang.python/msg/c01f292d7926f393?hl=en& If you want a way that will work regardless if your module is run interactively, imported, or just run by itself, this is a solution that will always work: :: \wherever\wherever\ (the directory your module is in, obviously somewhere where PYTHONPATH can see it) :::: danmodule.py (your module) :::: danmodule_xml\ (a subdirectory in the same directory as your module; it will only have 2 files in it) :::::: __init__.py (an empty textfile in danmodule_xml\, only here to make danmodule_xml\ work like a package) :::::: data.xml (your xml file in danmodule_xml\) Here is the Python code for loading the file: # ################ # import xml.dom.minidom import os.path import danmodule_xml xml_data_path = os.path.split(danmodule_xml.__file__)[0] xml_file_fullpath = os.path.join(xml_data_path, 'data.xml') document = xml.dom.minidom.parse(xml_file_fullpath) # ################ # Obviously, if you have more than 1 xml files, just put them all in "danmodule_xml\". From nakpac at gmail.com Thu Nov 3 11:25:02 2005 From: nakpac at gmail.com (nak) Date: 3 Nov 2005 08:25:02 -0800 Subject: How to print random strings References: <1130978067.685487.194530@g44g2000cwa.googlegroups.com> Message-ID: <1131035102.048484.179830@g44g2000cwa.googlegroups.com> theboringdays at gmail.com wrote: > Im at the end of chapter 3 of "Python Programming For The Absolute > Beginner, Michael Dawson " and he asks to make a fortune program that > displays a fortune each time its ran, and to have 5 unique fortunes. > > Whats confusing is that, he never discussed how to do this. The only > thing he talked about was using random.randrange() and I tried that > with text but it seems like its only for integers as it complains when > I put text in the argument. > > So how would I go about have 5 strings, and running a program that will > randomly pick one of those to print? > > I think he may have forgot to cover something? The fortune cookie program can be made by copying the code for 'Mood Computer' on page 64 and 65. So it could be something like: import random print "Welcome to the Fortune cookie program" fortune = random.randrange(3) if fortune == 0: print "some fortune1" elif fortune == 1: print "some fortune2" elif fortune == 2: print "some fortune3" From robert.kern at gmail.com Thu Nov 3 00:33:58 2005 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 02 Nov 2005 21:33:58 -0800 Subject: [OT] Gmane/Tunderbird users: is g.c.p.general too big? In-Reply-To: References: Message-ID: Steve Holden wrote: > Sorry about this almost off-topic post, but I am guessing there must be > other readers of this group who use Thunderbird (in my case 1.0.2) to > access it as gmane.comp.general.python. > > I'm currently showing 344,548 articles in the group due to the gmane > policy of permanent retention, and lately it seems to have started > taking forever to switch from mailboxes to the newsgroup. Furthermore, > the Thunderbird process's memory usage climbs from ~30MB reading mail to > over 200MB reading the newsgroup. > > Has anyone else noticed this, or is it specific to my setup? Does anyone > have a solution? You can specify a policy for keeping old messages for each server account. Go to your "Account Settings" for GMane and look in "Offline & Disk Space". You can choose to keep all messages, the newest N messages, or messages from the past N days. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From daniel.evers at rwth-aachen.de Fri Nov 18 10:08:47 2005 From: daniel.evers at rwth-aachen.de (Daniel Evers) Date: Fri, 18 Nov 2005 16:08:47 +0100 Subject: combine doxygen and doc-strings? References: Message-ID: <3u6940Fvj2r2U1@news.dfncis.de> You're maybe searching for epydoc: http://epydoc.sourceforge.net/ From apardon at forel.vub.ac.be Fri Nov 4 03:14:16 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 08:14:16 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: Op 2005-11-03, Steven D'Aprano schreef : > On Thu, 03 Nov 2005 12:53:37 +0000, Antoon Pardon wrote: > >>> I don't suppose you'd care to enlighten us on what you'd regard as the >>> superior outcome? >> >> No. I don't think a superior outcome is necessary to see that this is >> not sane behaviour. I don't care that much on how it gets fixed. > > It isn't broken, there is nothing to fix. The code does precisely what the > inheritance model promises to do. That is not a contra argument. Delivering what is promissed says nothing about the sanity of what is promissed. It is even possible that a number of things that are sane in itself, produce something unsane when combined or in certain circumstances. -- Antoon Pardon From tuvas21 at gmail.com Mon Nov 7 13:47:36 2005 From: tuvas21 at gmail.com (Tuvas) Date: 7 Nov 2005 10:47:36 -0800 Subject: Tkinter- Building a message box In-Reply-To: References: <1131387846.676519.184420@g44g2000cwa.googlegroups.com> Message-ID: <1131389256.633959.267940@g44g2000cwa.googlegroups.com> Do you have any info on dialogs? I've been trying to find some, without alot of success... From y.glodt at sitasoftware.lu Wed Nov 9 09:13:59 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 09 Nov 2005 15:13:59 +0100 Subject: append to non-existing list In-Reply-To: <4371fb5a$0$18086$626a14ce@news.free.fr> References: <4371fb5a$0$18086$626a14ce@news.free.fr> Message-ID: <43720427.7070801@sitasoftware.lu> bruno at modulix wrote: > Yves Glodt wrote: >> Hello, >> >> if I do this: >> >> for row in sqlsth: >> ________pkcolumns.append(row[0].strip()) >> ________etc >> >> >> without a prior: >> >> pkcolumns = []; >> >> >> I get this error on first iteration: >> UnboundLocalError: local variable 'pkcolums' referenced before assignment >> >> >> I guess that's normal as it's the way python works...?!? > > yes sir. > >> My question is: Is there no way to append to a non existing list? > > No. Definitively. And that's a Good Thing(tm). > > How would you use something that doesn't exist ??? > >> I am lazy for declaring it first, > > s/declaring/instantiating/ > > If you were to use your own class Toto, would you ever hope that the > following code would work : > > for v in some_seq: > toto.dothis(v) > > without instantiating Toto and binding it to the name 'toto' before ? > Well, in Python, a list is an instance of class list. There are > syntactic sugar to instanciate a list (or a tuple or a string or a dict > etc), but this: > > my_list = [] > > is strictly equivalent to this: > > my_list = list() > > Now let's try something else: > > class Machin(object): > def append(self, value): pass > > class Bidule(object): > def append(self, value): pass > > for i in range(10): > m.append(i) > > > How should Python interpret this ? Should it create a list, or a Machin, > or a Bidule, or an instance of whatever imported class having a > append() method ? ok I see your point, and python's... (just FYI, and not to start a flamewar ;-): In php, the [] means "append to an array object". If the array does not exist yet, it's created. [] *is* explicit for arrays, thus for php it's clear what you want.) >> IMHO it bloats the code, > > run your python interpreter and type: > import this > > Then read carefully. > > Now if being explicit still hurts your personal convictions, there's > this other language with a name starting with p... !-) no thanks, this is the 21st century ;-) >> and (don't >> know if it's good to say that here) where I come from (php) I was used >> to not-needing it... > > Not creating an Array before using it is Bad Style in PHP (and generate > a Warning BTW). an "undefined" notice, yes, not a warning... ;-) > There are warts in Python (as in any other languages), and there are > things that sometimes bore me but are not really warts. But having to > explicitely instanciate objects can't be seen as a wart in any language > IMHO !-) Ok... I thank you for all the explanations. It helps me to see more far. I (and will continue to) use php for web, and wanna standardize on python for all non-web stuff we are doing, so I might be a frequent guest on this list... have a nice day, Yves From bokr at oz.net Tue Nov 8 06:14:21 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 08 Nov 2005 11:14:21 GMT Subject: os.path.getmtime on winXP References: <43704c83@news.broadpark.no> <43706983.433918702@news.oz.net> <437074e8$1@news.broadpark.no> Message-ID: <4370805e.439769895@news.oz.net> On Tue, 08 Nov 2005 10:49:56 +0100, =?ISO-8859-1?Q?Jorg_R=F8dsj=F8?= wrote: >Bengt Richter wrote: >> How did you format the number you got from os.path.getmtime? > >I'm not doing any formating at all. I am just looking at the numbers of >seconds since epoch. Which is what makes it so strange. > >> You might want to try some of the above. > >I'll do that. At the moment I'm looking at the difference between >localtime and gmtime to see if my computer is in dst. If it is not, I >just add 3600 seconds to the result from os.path.getmtime -- which then >should give consistent results. the time module should know how to do that for you, unless something is fubar. see time.timz import time help(time) > >> If you actually created/modified files just before and after the DST change >> and saw an extra hour difference instead of the time between the two actions, >> then maybe I'd look into whether the OS has some perverse option to use local DST >> time to record in the file stat info, but that's hard to believe. More likely someone >> is messing with with raw file time setting, like touch. Don't have it handy to see >> what DST assumptions it makes if any. > >The files I am testing with have not been modified for a long time. >Windows reports the modified date as being the same, no matter what I do > (both through the gui, and through win32file). And they all show the >same strange 3600 sec difference with/without dst when I call getmtime >on them. By 'getmtime' you mean os.path.getmtime(fer_shure_or_absolute_path_to_file) right? Doesn't that get you an integer number of seconds? What GUI or win32file is showing you that integer so you see a 3600 sec difference? Or how are you seeing it? Could you paste an example of this difference from an example on your screen? I don't think I am understanding ;-) ... urk, it's late ;-/ Regards, Bengt Richter From scott.daniels at acm.org Fri Nov 11 11:35:00 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 11 Nov 2005 08:35:00 -0800 Subject: LARGE numbers In-Reply-To: <7xmzkbkw0j.fsf@ruckus.brouhaha.com> References: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> <1131691903.961955.19950@o13g2000cwo.googlegroups.com> <1h5uqy3.sdzwkkuvu86mN%aleax@mail.comcast.net> <7xmzkbkw0j.fsf@ruckus.brouhaha.com> Message-ID: <4374c6f5$1@nntp0.pdx.net> Paul Rubin wrote: > aleax at mail.comcast.net (Alex Martelli) writes: > > For numbers of this size, won't gmpy use FFT-based multiplication? > That's potentially orders of magnitude faster than ordinary n**2 > multiplication. But Python is no slouch with its use of Karatsuba multiplication. (in other words, Python is not N**2 for large numbers). --Scott David Daniels scott.daniels at acm.org From steve at REMOVETHIScyber.com.au Wed Nov 23 17:02:51 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 24 Nov 2005 09:02:51 +1100 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132756197.635519.114180@g47g2000cwa.googlegroups.com> Message-ID: On Wed, 23 Nov 2005 07:01:58 -0800, Daniel Crespo wrote: >> WHY WHY WHY the obsession with one-liners? What is wrong with the good old >> fashioned way? > > >> if cond: >> x = true_value >> else: >> x = false_value > > Let me tell you something: I'm not a one-liner coder, but sometimes It > is necesary. I'm not arguing for multi-line code just for the sake of using more than one line. I'm against artificially trying to compress a algorithm that is naturally expressed in two or more lines into one line. > For example: > I need to translate data from a DataField to Another. > > def Evaluate(condition,truepart,falsepart): > if condition: > return truepart > else: > return falsepart > > dOldDataFields = {} > dNewDataFields = {} Why do you bother to initialise dNewDataFields to an empty dict when you then populate it in the very next statement? > dNewDataFields = { > 'CODE': dOldDataFields['CODEDATA'], > 'DATE': dOldDataFields['DATE'], > 'CONTACT': Evaluate(dOldDataFields['CONTACTTYPE']==2, > dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT']) > } Doesn't look like a one-liner to me. You've called Evaluate, which takes five lines by my count. > With this, I created a new dic very easy, saving in > dNewDataFields['CONTACT'] the value of dOldDataFields['FIRSTCONTACT'] > or the value of dOldDataFields['SECONDCONTACT'] depending on > dOldDataFields['CONTACTTYPE']. How you do this in a practic way without > the use of one-line code? It is needed! You can't avoid it! Even using > a = [if_false_expr, if_true_expr][predicate] or a function, you'll > always have to use a one-line code (for this purpose, of course). Again, I am not arguing for needlessly inflating lines of code, I think your solution is fine. But just to prove it can be done: dNewDataFields['CODE'] = dOldDataFields['CODEDATA'] dNewDataFields['DATE'] = dOldDataFields['DATE'] if dOldDataFields['CONTACTTYPE'] == 2: dNewDataFields['CONTACT'] = dOldDataFields['FIRSTCONTACT'] else: dNewDataFields['CONTACT'] = dOldDataFields['SECONDCONTACT'] There. The world didn't end. *wink* -- Steven. From fredrik at pythonware.com Mon Nov 21 08:50:40 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Nov 2005 14:50:40 +0100 Subject: ownership problem? References: Message-ID: Jeffrey Schwab wrote: > >>>the problem isn't determining who owns it, the problem is determining > >>>who's supposed to release it. that's not a very common problem in a > >>>garbage-collected language... > >> > >>Yes it is. Memory is only one type of resource. > > > > Python's garbage collector deals with objects, not memory. > > But you don't want to spin and wait for the garbage collector to release > the object that happens to be holding a thread lock... no, but arguing that sockets and thread locks are objects that suffer from ownership problems is rather silly. if their use isn't localized to a single function or a single manager object, your design is flawed. From cito at online.de Sun Nov 27 21:52:57 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 28 Nov 2005 03:52:57 +0100 Subject: General question about Python design goals In-Reply-To: References: Message-ID: >>Let me ask back: Do I really need to bother and justify it with a use >>case in a case where the language can be easily made more consistent or >>orthogonal without breaking anything? Robert Kern wrote: > Yes. If it's not going to be used, then there's not much point. > Practicality beats purity, and all that. I have nothing against "practicality beats purity". But to stay with the examples I have given, in how far is writing list(t).index(x) more practical than t.index(x)? And by the way, if we are speaking about practicality here, are we speaking about practicality for the Python developers or for the Python users? This may be sometimes be in opposition. Let me give an extreme example: Assume the count() method for strings would have been called "numberofsubstringsinthestring()" and I argue it should be called "count()" because that is shorter and how it is called for lists. What should I give as a "use case" here? Must I give "use cases" if the issue is about convenience/simplicity/elegance? > However, I will note that if you were to present us with a working patch > with documentation and unittests, then you'll probably get responses > along the lines of "Thank you!", instead. Not everybody has the time and skills to provide that. Ordinary people from the Python user base should be given the opportunity to make suggestions for improvement - of course not in the tone of "I demand...", but they should not be automatically regarded as "demanding" if they just utter their opinion or make a suggestion either. Even if I had the time and skills, before starting to work on a patch, unittests etc. I still would first discuss with others whether my suggestion is reasonable and would be appreciated by the "user base", developers and the BDFL. Just take the example of the following patch: https://sourceforge.net/tracker/?func=detail&atid=305470&aid=403693&group_id=5470 It was not rejected by reason of missing unittests or documentation, but the very idea was rejected. Actually, I'm not keen on being a protagonist for this issue or starting a hard-bitten discussion about this and defend the idea if everybody is against or nobody cares. It does not bother me that much either. But it just led me to the general question: Which significance actually have design features such as orthogonality for Python? -- Christoph From aisaac0 at verizon.net Mon Nov 21 16:16:56 2005 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 21 Nov 2005 21:16:56 GMT Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> Message-ID: "Alan Isaac" wrote in message news:Mzpgf.12794$NN2.4089 at trnddc02... > cr[0] = func(cr[0],init) Ooops. That assumed commutativity. It shd be: cr[0] = func(init,cr[0]) or perhaps for clarity cr[0] = func(init,seq[0]) Alan Isaac From bonono at gmail.com Fri Nov 25 03:25:55 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 25 Nov 2005 00:25:55 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: References: <1132772142.500020.16360@g44g2000cwa.googlegroups.com> <1132782865.993175.92340@g43g2000cwa.googlegroups.com> Message-ID: <1132907155.557106.162410@g43g2000cwa.googlegroups.com> Steve Holden wrote: > Magnus Lycka wrote: > > bonono at gmail.com wrote: > > > >>Oh, find a need to shut other up ? > >> > > > > Oh, find a need to get the last word? > > > > /Magnus > > > > P.S. Yes, this *is* a test. > > Looks like you hooked him, Magnus ;-) and he is permenantly hooked From jepler at unpythonic.net Mon Nov 21 09:47:00 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 21 Nov 2005 08:47:00 -0600 Subject: writing a generic method In-Reply-To: <1132566891.016382.116540@g43g2000cwa.googlegroups.com> References: <1132566891.016382.116540@g43g2000cwa.googlegroups.com> Message-ID: <20051121144700.GB22167@unpythonic.net> You could use a format like "#s#sO", and then use PyFloat_Check, PyFloat_AsDouble, and the equivalent PyInt macros to get the "C" value out of the Python object. You should be able to use the converter "O&" to get what you want. The conversion function might look like: int double_only(PyObject *o, double *d) { if(!PyFloat_Check(o)) return 0; *d = PyFloat_AsDouble(o); } and the call would be if(PyArg_ParseTuple(args,"s#s#O&",&cname,&lname,&cprop,&lprop,double_only,&x)) mdbgetd_(cname,cprop,&x,&z,lname,lprop); (untested) I believe that if you write if(PyArg_ParseTuple(...)) else(PyArg_ParseTuple(...)) you're missing a PyErr_Clear() before the second PyArg_ParseTuple(). Returning non-NULL when an exception has been set in C code will lead to a hard-to-trace failure down the road. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From sybrenUSE at YOURthirdtower.com.imagination Fri Nov 18 14:16:10 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 18 Nov 2005 20:16:10 +0100 Subject: Python on linux References: <1132321509.20073.24.camel@wrkstn6> Message-ID: John Abel enlightened us with: > Here's one I used a while back. Returns a dict containing details per > partition This only gives information about actually mounted partitions. It could be improved by checking /proc/partitions as well. 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 john.lehmann at gmail.com Sat Nov 19 15:19:12 2005 From: john.lehmann at gmail.com (john.lehmann at gmail.com) Date: 19 Nov 2005 12:19:12 -0800 Subject: Problems returning/attaching cookies In-Reply-To: <1132417459.990824.232590@g49g2000cwa.googlegroups.com> References: <1132417459.990824.232590@g49g2000cwa.googlegroups.com> Message-ID: <1132431552.445547.120700@o13g2000cwo.googlegroups.com> NEVERMIND. My friend pointed out that I am simply hitting the wrong URL when trying to "test" whether I am logged in or not. The correct one is: http://www.dpreview.com/forums/editprofile.asp But I still have one question, if anyone knows -- why is it that when I print out the headers on my request object, they are empty? I thought that I should find the cookies there which are being sent back. This is what I thought the problem was. Thanks if anyone can explain how that works. John (PS i have stopped attacking the cookies now) john.lehmann at gmail.com wrote: > Attacked is a piece of code which first hits the login page > successfully and receives back login cookies. But then when I attempt > to hit a page which is restricted to logged in users only, I fail. > > That seems to be because I am not successfully re-attaching the cookies > to the header portion of the this request. I have tried 2 methods > which should both work I think. The first was to use install_opener to > attach the cookie handler back to urlopen. The second method was to > use the cookiehandler method add_cookie_header. But in both cases, > before sending out the 2nd request, it seems to have empty headers -- > which indicates to me that the necessary cookies have not been > attacked. > > I also tryed messing with the policy quite a bit, thinking that might > be causing the cookies not to be returned. First I used the default, > then set some flags on the default, then even overrode methods on the > default to make it as lenient as possible. This had no apparent > effect. > > Thanks a lot! > > Below I have pasted the most relevant code section, as well as my full > code file. Apologies for all the comments, but I wanted to show what I > had tried. > ----------------- > RELEVANT CODE (snipped from full code) > > # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE > the_url = > "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp" > req = urllib2.Request(the_url) > #print "headers:", req.headers > #cj.add_cookie_header(req) > > # EXPECT THESE HEADERS TO BE NON-EMPTY - BUT THEY ARE EMPTY, > # NO COOKIES RETURNED? > print "headers:", req.headers > > # THIS OPEN FAILS - I GET - "NEED TO LOGIN" PAGE > #handle = opener.open(req) > handle = urllib2.urlopen(req) > the_page = handle.read() > > ----------------- > FULL CODE > > #!/usr/bin/python > > import urllib > import urllib2 > import re > import os > from cookielib import * > > class MyCookiePolicy(DefaultCookiePolicy): > def __init__(self): > DefaultCookiePolicy.__init__(self, rfc2965=True, > hide_cookie2=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal) > def set_ok(self, cookie, request): > return True > def return_ok(self, cookie, request): > return True > def domain_return_ok(self, cookie, request): > return True > def path_return_ok(self, cookie, request): > return True > > the_url = 'http://www.dpreview.com/forums/login_post.asp' > user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > values = { > 'email' : '****', > 'password' : '****', > #"remember" : "checked", # <- create permanent cookie > 'jump' : "/forums/" > } > # also "remember" : "remember" > > # INITIAL REQUEST WITH USER INFO > headers = { 'User-Agent' : user_agent } > data = urllib.urlencode(values) > req = urllib2.Request(the_url, data, headers) > > # COOKIE POLICY > # tried using several configurations of the default cookie policy > #policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False, > strict_ns_domain=DefaultCookiePolicy.DomainLiberal) > # tried using my own custom cookie policy > #policy = MyCookiePolicy() > policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False) > > # CREATE COOKIE JAR WITH POLICY > cj = MozillaCookieJar() > cj.set_policy(policy) > > # CREATE OPENER, AND OPEN PAGE > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > #handle = opener.open(req) > handle = urllib2.urlopen(req) > the_page = handle.read() > > # SHOW COOKIES COLLECTED - LOOKS GOOD HERE > for c in cj: > print "COOKIE:", c > print "URL:", handle.geturl() > print "INFO:", handle.info() > > #DEMONSTRATE WE'RE LOGGED IN > for line in the_page.split('\n'): > line = line.strip() > if re.search("Welcome to the", line): > print "MESSAGE:", line > > # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE > # - tried using the install_opener above > # - tried using add_cookie_header > # - either way, can't seem to get cookies in the header of this request > the_url = > "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp" > req = urllib2.Request(the_url) > #print "headers:", req.headers > #cj.add_cookie_header(req) > > # EXPECT THESE HEADERS TO BE NON-EMPTY > print "headers:", req.headers > #handle = opener.open(req) > handle = urllib2.urlopen(req) > the_page = handle.read() > > # THIS ALSO PROVES LOGIN-STATE WAS LOST > for line in the_page.split('\n'): > line = line.strip() > if re.search("To access", line): > print "MESSAGE:", line > > print "URL:", handle.geturl() > print "INFO:", handle.info() From fredrik at pythonware.com Wed Nov 2 12:00:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Nov 2005 18:00:34 +0100 Subject: how to check for unix password References: <1130927459.936730.50190@o13g2000cwo.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > i created a login page that authenticate the user and his/her password > to the unix ssystem. what modules can i used to compare the unix > password with what the user typed in the cgi form? the password is > encrypted (shadowed) so i need to decrypt it first before comparing > to what the user typed. encrypted != shadowed. unix passwords are always encrypted, and cannot be decrypted (at least not easily). to check a password, encrypt the given password using the same salt, and check if you get the same result. see the second example on this page for an example: http://effbot.org/librarybook/crypt.htm if the password is shadowed, you need the right privileges, and the spwd module: http://www.python.org/dev/doc/devel/lib/module-spwd.html this is only available in development versions. to use it with an older version, you have to built it yourself. the source code is here: http://svn.python.org/view/python/trunk/Modules/spwdmodule.c From mtebeka at qualcomm.com Tue Nov 1 02:10:14 2005 From: mtebeka at qualcomm.com (Miki Tebeka) Date: Tue, 1 Nov 2005 09:10:14 +0200 Subject: Forced to Embed? In-Reply-To: References: Message-ID: <20051101071014.GA5832@qualcomm.com> Hello Lloyd, > I have about 10 shared libraries that up until now have only been > statically linked into an application and used from C++. I'd like to > expose a lot of this functionality as different Python modules ( core, > network, input, etc ), however the interdependency between the libraries > seem to prohibit this. The library dependencies are in a tree heirarchy > with the basic core library at the bottom. > > As far as I can tell I have to export these all in one massive module as > there is no way for the different python modules to directly communicate > with each other? What do you mean by "communicate"? Whey isn't "import" good enough? > Because of this I have to assume any application specific code would > have to be placed in this massive module aswell and thus the whole > module setup is moot and I might aswell embed python in the application > and import the different interfaces as modules into the python namespace > while still having them communicate directly because they're in the same > executable. > > I'd prefer to extend while using the normal python interpreter but I see > no way around this without a large restructure? You can have one Python module that is the interface to the C++ module and it will be structured the way you want (using classes, modules ...). Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 215 bytes Desc: not available URL: From swarnapsv at yahoo.co.in Fri Nov 4 12:25:46 2005 From: swarnapsv at yahoo.co.in (Swarna Pulavarty) Date: Fri, 4 Nov 2005 17:25:46 +0000 (GMT) Subject: connect to a remote web server & upload data from Python using ssh and scp Message-ID: <20051104172547.16148.qmail@web8408.mail.in.yahoo.com> Hi all, I need to upload data ( text & image data ) to a remote web server from python. I came to know that i could do it using ssh and scp.....but am not sure of how to do it. I don't want to use CGI for that ..... Can anyone help me....how to do it, and where i can get a good tutorial for doing this....I surfed the net..but could'nt find a good doc for this.. Thanks, for your time !........ Swarna. --------------------------------- Enjoy this Diwali with Y! India Click here -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Nov 22 04:55:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 10:55:52 +0100 Subject: about sort and dictionary References: <1132493880.591426.224140@g49g2000cwa.googlegroups.com> <1132651818.348370.117450@g49g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Since python's '=' is just name binding and that most objects(other > than those like int/float/string?) are mutable, I don't quite > understand why this is a gotcha that is so worrying. > > a = [1,2,3] > a.sorted() > b = a > > even an entry level python programmer can't expect 'b' to be > unchanged(after getting the first bite may be) if there is any > operation on a later. This not only applies to list but almost all > mutable object. so what would an entry-level Python programmer expect from this piece of code? for item in a.reverse(): print item for item in a.reverse(): print item (as the X people used to say, the only thing worse than generalizing from one example (sort) is generalizing from no examples at all ("let's assume I have a use case")). From sszmidt at netwvcom.com Wed Nov 30 20:53:50 2005 From: sszmidt at netwvcom.com (sszmidt at netwvcom.com) Date: Wed, 30 Nov 2005 20:53:50 -0500 Subject: ANN: Dao Language v.0.9.6-beta is release! In-Reply-To: References: <1133174924.322968.273370@o13g2000cwo.googlegroups.com> Message-ID: <200511302053.50386.sszmidt@netwvcom.com> Please trim replies... ; ) -- Steve From nick at craig-wood.com Wed Nov 9 14:30:14 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 09 Nov 2005 13:30:14 -0600 Subject: xml.minidom and user defined entities Message-ID: I'm using xml.minidom to parse some of our XML files. Some of these have entities like "°" in which aren't understood by xml.minidom. These give this error. xml.parsers.expat.ExpatError: undefined entity: line 12, column 1 Does anyone know how to add entities when using xml.minidom? I've spend some time searching the docs/code/google but I haven't found the answer to this question! Thanks -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dan at wolf.com Wed Nov 23 13:50:29 2005 From: dan at wolf.com (Dan M) Date: Wed, 23 Nov 2005 10:50:29 -0800 Subject: Timeout in urllib2 Message-ID: I'm writing a system monitor script that needs to load web pages. I'm using urllib2.urlopen to get the pages, and I'm attempting to set the timeout value using socket.defaulttimeout. Specifically, I'm calling socket.defaultttimeout(10), then calling urllib2.urlopen to fetch a web page that never gets delivered. My code waits about 30 seconds before terminating. I am about to add threading to my app so that delays on a few servers won't be a critical issue, but I'd still like to understand why the call to socket.defaulttimeout doesn't affect the timeout on my urlopen calls. My code follows. #!/usr/local/bin/python import socket, time socket.setdefaulttimeout(10) import urllib2 def doHttpTest(): url = "http://url.that.never.returns" t_start = time.time() if httptest(url): print "Error on site ", url t_end = time.time() t_diff = t_end - t_start def httptest(url): timeout = 10 socket.setdefaulttimeout(timeout) try: req = urllib2.Request(url) urllib2.urlopen(req) except urllib2.HTTPError, e: if e.code == 401: return 1 elif e.code == 404: return 1 elif e.code == 503: return 1 else: return 1 except urllib2.URLError, e: return 1 else: return 0 if __name__ == '__main__': try: doHttpTest() except KeyboardInterrupt: print "Exiting..." From kay.schluehr at gmx.net Wed Nov 23 04:24:46 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 Nov 2005 01:24:46 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> Message-ID: <1132737886.158858.255830@g44g2000cwa.googlegroups.com> bonono at gmail.com wrote: > Steve Holden wrote: > > Perhaps now the answer top your question is more obvious: there is by no > > means universal agreement on what an "ordered dictionary" should do. > > Given the ease with which Python allows you to implement your chosen > > functionality it would be presumptuous of the core developers to favour > > any one of the several reasonable alternatives that might be chosen. > > > It seems to be though as "ordered dictionary" are slowly to be confined > to only "ordered on order of change to the dictionary". While I'm only +0 for a standard odict I'm wondering that discussing this topic leads to the auctoritative conclusion that it is unsolvable, we have to accept infinite diversity etc. where people like me seeing a classification immediately ( mathematical education? ) . Of course this matter is trivial but we already know about monster-threads revolving around decorator syntax ( including hurt souls and semi-scientific papers ) and abandoning the print statement in Python 3.0. From gsakkis at rutgers.edu Tue Nov 8 11:29:04 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Nov 2005 08:29:04 -0800 Subject: which feature of python do you like most? References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: <1131467344.716867.297390@g44g2000cwa.googlegroups.com> wrote: > [snipped] > > i've read a few chapters of a python tutorial book. The things are much like the perl one. > > I have no idea why people are so facinating with python. Because they can write a program or module longer than 100 lines and be actually able to read, debug, refactor or extend it after 6 months. George From waldbie at yahoo.com Sat Nov 26 22:49:07 2005 From: waldbie at yahoo.com (Carl Waldbieser) Date: Sat, 26 Nov 2005 22:49:07 -0500 Subject: Nested list comprehensions References: <1133060448.284028.238680@f14g2000cwb.googlegroups.com> Message-ID: neildunn at gmail.com wrote: > Hey guys: > >>>> [(i,j,k) for i in range(1,j) for j in range(1,k) for k in range(1,5)] > [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 1), (1, 2, 2), (1, > 2, 3), (1, 2, 4), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (2, 1, > 1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 2, 1), (2, 2, 2), (2, 2, 3), > (2, 2, 4), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4)] >>>> def a(): > ... print [(j,k) for j in range(1,k) for k in range(1,5)] > ... >>>> a() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in a > UnboundLocalError: local variable 'k' referenced before assignment > > Why is it that I can execute the nested list comprehension in the > intepreter > but if the same line is within a method declaration I get an unbound > reference error? > > Is this a bug or am I missing some deep rule? > > Regards, Neil Dunn You may not be getting the name error in the interpreter because you already defined those variables. Try this: $ python >>> [(j,k) for j in range(1,k) for k in range(1,5)] Traceback (most recent call last): File "", line 1, in ? NameError: name 'k' is not defined >>> Looks like the variable was not defined here, either. You are trying to use the variable "k" in the range() function before it has been bound to anything, hence the error. From juho.schultz at helsinki.fi Wed Nov 30 03:22:33 2005 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Wed, 30 Nov 2005 10:22:33 +0200 Subject: Nested loop In-Reply-To: References: Message-ID: viewcharts wrote: > I am reading two text files comparing the values in one to the other, > this requires two loops. The problem is that when the inner loop is > finished, it never goes back into the loop. Any suggestions? > > > for refSymbol in symbols.readlines(): > for lookupSymbol in myfile.readlines(): > showme = lookupSymbol.split('\t') > if showme[3] == refSymbol.strip(): > priceNew.write(refSymbol.strip()+" "+showme[10]) > > > When the inner loop is finished for the 1st time, myfile has been read. So next time you start to the loop, myfile.readlines() returns an empty list. Something like this should be better: lookupSymList = myfile.readlines() for refSymbol in symbols.readlines(): for lookupSymbol in lookupSymList: showme = lookupSymbol.split('\t') if showme[3] == refSymbol.strip(): priceNew.write(refSymbol.strip()+" "+showme[10]) From fdu.xiaojf at gmail.com Sun Nov 20 04:47:27 2005 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Sun, 20 Nov 2005 17:47:27 +0800 Subject: what happens when the file begin read is too big for all lines to be read with "readlines()" In-Reply-To: References: <1132399371.267088.291000@g14g2000cwa.googlegroups.com> <437FFB57.6010101@gmail.com> Message-ID: <4380462F.2010006@gmail.com> Steve Holden wrote: >Xiao Jianfeng wrote: > > >>Steven D'Aprano wrote: >> >> >> >> >>>On Sun, 20 Nov 2005 11:05:53 +0800, Xiao Jianfeng wrote: >>> >>> >>> >>> >>> >>> >>>>I have some other questions: >>>> >>>>when "fh" will be closed? >>>> >>>> >>>> >>>> >>>When all references to the file are no longer in scope: >>> >>>def handle_file(name): >>> fp = file(name, "r") >>> # reference to file now in scope >>> do_stuff(fp) >>> return fp >>> >>> >>>f = handle_file("myfile.txt) >>># reference to file is now in scope >>>f = None >>># reference to file is no longer in scope >>> >>>At this point, Python *may* close the file. CPython currently closes the >>>file as soon as all references are out of scope. JPython does not -- it >>>will close the file eventually, but you can't guarantee when. >>> >>> >>> >>> >>> >>> >>>>And what shoud I do if I want to explicitly close the file immediately >>>>after reading all data I want? >>>> >>>> >>>> >>>> >>>That is the best practice. >>> >>>f.close() >>> >>> >>> >>> >>> >>> >> Let me introduce my problem I came across last night first. >> >> I need to read a file(which may be small or very big) and to check line >>by line >> to find a specific token, then the data on the next line will be what I >>want. >> >> If I use readlines(), it will be a problem when the file is too big. >> >> If I use "for line in OPENED_FILE:" to read one line each time, how can >>I get >> the next line when I find the specific token? >> And I think reading one line each time is less efficient, am I right? >> >> >> >Not necessarily. Try this: > > f = file("filename.txt") > for line in f: > if token in line: # or whatever you need to identify it > break > else: > sys.exit("File does not contain token") > line = f.next() > >Then line will be the one you want. Since this will use code written in >C to do the processing you will probably be pleasantly surprised by its >speed. Only if this isn't fast enough should you consider anything more >complicated. > >Premature optimizations can waste huge amounts of unnecessary >programming time. Don't do it. First try measuring a solution that works! > > Oh yes, thanks. >regards > Steve > > First, I must say thanks to all of you. And I'm really sorry that I didn't describe my problem clearly. There are many tokens in the file, every time I find a token, I have to get the data on the next line and do some operation with it. It should be easy for me to find just one token using the above method, but there are more than one. My method was: f_in = open('input_file', 'r') data_all = f_in.readlines() f_in.close() for i in range(len(data_all)): line = data[i] if token in line: # do something with data[i + 1] Since my method needs to read all the file into memeory, I think it may be not efficient when processing very big file. I really appreciate all suggestions! Thanks again. Regrads, xiaojf From bokr at oz.net Sun Nov 27 00:18:11 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 27 Nov 2005 05:18:11 GMT Subject: Whitespace test after string.split References: Message-ID: <43894080.18968284@news.oz.net> On Sat, 26 Nov 2005 16:15:17 +0100, Peter Otten <__peter__ at web.de> wrote: >David Pratt wrote: > >> Hi. I am splitting a string on a non whitespace character. One or more >> whitespace characters can be returned as items in the list. I do not >> want the items in the list that are only whitespace (can be one or more >> characters of whitespace) and plan to use string.strip on those items >> that are not only whitespace (to remove any whitespace from front or >> back of items). >> >> What kind of efficient test can I use to obtain only list items >> returned from the split that I am interested in, ignoring any list >> items that would only be comprised of one or more characters of >> whitespace (since whitespace can mean one or more spaces, tabs, and >> other characters) > >>>> s = "alpha, \t\n, gamma, delta," >>>> s.split(",") >['alpha', ' \t\n', ' gamma', ' delta', ''] >>>> [t for t in s.split(",") if not t.isspace()] >['alpha', ' gamma', ' delta', ''] >>>> [t for t in s.split(",") if t and not t.isspace()] >['alpha', ' gamma', ' delta'] >>>> [t.strip() for t in s.split(",") if t and not t.isspace()] >['alpha', 'gamma', 'delta'] > >There you are. Alternatively, possibly >>> [t for t in (t.strip() for t in s.split(",")) if t] ['alpha', 'gamma', 'delta'] > >> As a second question, I am seeing string split as deprecated in 2.4.2 >> manual. What is planned in future to split (strings or unicode)? > >Just use the corresponding methods, e. g. s.strip() instead of >string.strip(s) etc. > >Peter > Regards, Bengt Richter From luca.bs at gmail.com Thu Nov 10 03:10:34 2005 From: luca.bs at gmail.com (LB) Date: 10 Nov 2005 00:10:34 -0800 Subject: ANN: P(x) 0.2 applet builder In-Reply-To: <86br0t6mtz.fsf@bhuda.mired.org> References: <86br0t6mtz.fsf@bhuda.mired.org> Message-ID: <1131610234.561775.10980@z14g2000cwz.googlegroups.com> >The tarball can be found at http://www.mired.org/downloads/P(x)-0.2.tar.gz >. Something doesn't work wit the link. LB From duncan.booth at invalid.invalid Mon Nov 28 10:29:02 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Nov 2005 15:29:02 GMT Subject: General question about Python design goals References: Message-ID: Antoon Pardon wrote: > > No I gave an example, you would implement differently. But even > if you think my example is bad, that would make it a bad argument > for tuples having list methods. That is not the same as being > a good argument against tuples having list methods. Tuples don't have list methods, therefore any code which seems to require a tuple with list methods should make you stop and consider whether your design is wrong. Your example made me consider your design was wrong. If tuples did have list methods you would have gone ahead with a poor design. That is why I said that, to me, it is an argument against giving tuples the additional methods. It is a fairly weak argument though, so if you do have some other use case you could easily prove me wrong. From python_it at hotmail.com Fri Nov 18 07:34:51 2005 From: python_it at hotmail.com (Python_it) Date: 18 Nov 2005 04:34:51 -0800 Subject: mysql connection Message-ID: <1132317291.759987.307310@z14g2000cwz.googlegroups.com> How can I close more cursors at the END of my page, after execute some scripts/functions. example: I use one DB connection and 5 cursor actions. How can I close these connections/actions at the END of my page? cursor.close() ==> 5 times?? db.close() From mensanator at aol.com Mon Nov 21 20:53:54 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 21 Nov 2005 17:53:54 -0800 Subject: mxODBC sql MSAccess In-Reply-To: <1132621839.128441.49430@f14g2000cwb.googlegroups.com> References: <1132621839.128441.49430@f14g2000cwb.googlegroups.com> Message-ID: <1132624434.098385.194830@f14g2000cwb.googlegroups.com> BartlebyScrivener wrote: > Hello, I'm new to python and trying to get records from an MSAccess > database using mxODBC. It works, but the output is not formatted the > way I want it. > > Here's the script: > > import mx.ODBC.Windows as odbc > > driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access > Databases/Quotations2005' > > conn = odbc.DriverConnect(driv) > c = conn.cursor() > c.execute ("SELECT Author, Topic1, Topic2, Quote FROM QuotesToTxt WHERE > Author LIKE 'Mencken%'") > > rows = c.fetchall() > for r in rows: > print r > > And here's what I get: > > ('Mencken, H.L.', 'Americans', 'Democracy', 'Democracy is the theory > that the common people know what they want, and deserve to get it good > and hard.') > ('Mencken, H.L.', 'Conscience', 'Mother-In-Law', 'Conscience is a > mother-in-law whose visit never ends. The inner voice which warns us > that someone may be looking.') > > Where are the parenthese and single quotes coming from? SQL or mxODBC? >From Python. You data is stored as a list of tuples. > And how can I get just simple tab-delimited records with a standard > carriage return separating the records? for r in rows: print "%s\t%s\t%s\t%s" % r > > Thanks so much for any help. > > bs From david.rasmussen at gmx.net Tue Nov 1 14:38:47 2005 From: david.rasmussen at gmx.net (David Rasmussen) Date: Tue, 01 Nov 2005 20:38:47 +0100 Subject: Scanning a file In-Reply-To: <4365EF09.7020709@REMOVEMEcyber.com.au> References: <1130497567.764104.125110@g44g2000cwa.googlegroups.com> <7xek65nal0.fsf@ruckus.brouhaha.com> <1130505731.850947.68690@o13g2000cwo.googlegroups.com> <4363fdd4$0$2107$edfadb0f@dtext02.news.tele.dk> <4365EF09.7020709@REMOVEMEcyber.com.au> Message-ID: <4367c444$0$2100$edfadb0f@dtext02.news.tele.dk> Steven D'Aprano wrote: > > However, there may be a simpler solution *fingers crossed* -- you are > searching for a sub-string "\x00\x00\x01\x00", which is hex 0x100. > Surely you don't want any old substring of "\x00\x00\x01\x00", but only > the ones which align on word boundaries? > Nope, sorry. On the files I have tried this on, the pattern could occur on any byte boundary. /David From fredrik at pythonware.com Thu Nov 10 17:21:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Nov 2005 23:21:10 +0100 Subject: different binding behavior References: Message-ID: Gabriel Zachmann wrote: > It seems to me that the following behavior of python (2.4.1) is > inconsistent: > > >>> a=1 > >>> b=a > >>> a+=1 > >>> b > 1 > >>> a > 2 > >>> a=[1,2] > >>> b=a > >>> b+=[3] > >>> a > [1, 2, 3] > >>> b > [1, 2, 3] > > Why was it implemented like this?? assuming that you know that integers cannot modified in place, and that += on a list is defined to be the same thing as a call to extend, what did you expect this to do? From fredrik at pythonware.com Mon Nov 7 12:24:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 7 Nov 2005 18:24:50 +0100 Subject: Sending email in utf-8? References: <1131381565.320532.229310@g49g2000cwa.googlegroups.com> Message-ID: "morphex" wrote: > I have an email that's in the utf-8 encoding, and I'm getting this > error message when I try to send it using smtplib: > > * Module smtplib, line 688, in sendmail > * Module smtplib, line 485, in data > * Module smtplib, line 312, in send > * Module socket, line 1, in sendall > > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 263-264: ordinal not in range(128) > > any suggestions on how I can approach this so that the email can be > sent without raising errors? looks like you're confusing Unicode (character set) and UTF-8 (encoding). smtplib only deals with 8-bit character streams; if you want to use a specific encoding, you have to apply it yourself *before* you call the library: HOST = "..." FROM = "..." TO = "..." BODY = u"..." server = smtplib.SMTP(HOST) server.sendmail(FROM, [TO], BODY.encode("utf-8")) server.quit() From afa.NOSPAM at neuf.fr Sun Nov 13 07:52:36 2005 From: afa.NOSPAM at neuf.fr (Amaury) Date: Sun, 13 Nov 2005 13:52:36 +0100 Subject: Is there a built-in method for transforming (1,None,"Hello!") to 1,None,"Hello!"? In-Reply-To: <1131722506.604482.323720@f14g2000cwb.googlegroups.com> References: <1131722506.604482.323720@f14g2000cwb.googlegroups.com> Message-ID: <4377370d$0$41147$14726298@news.sunsite.dk> Hello, Daniel Crespo wrote: > Is there a built-in method for transforming (1,None,"Hello!") to > 1,None,"Hello!"? As others answered before, the two syntaxes build the same object, so there is no need to convert. Except if you already have the tuple stored in a variable, and want to call a function with the tree arguments: args = (1,None,"Hello!") func(args) # equivalent to func((1,None,"Hello!")) func(*args) # equivalent to func(1,None,"Hello!") Note the '*' on the second call, it will flatten the args, and 3 arguments are passed to the function. -- Amaury From aleax at mail.comcast.net Mon Nov 7 10:54:31 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 7 Nov 2005 07:54:31 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> Message-ID: <1h5nbfg.qku30012qwxglN%aleax@mail.comcast.net> Steve Holden wrote: ... > I tried compiling it with the MS free toolkit but the C compile > complains about the absence of "gmp.h". Since I see such a header in my > Cygwin installation I presume it's something that a full VC7 > installation could expect to be present. gmp.h is the header of GMP, the GNU library that gmpy wraps. It appears to be preinstalled on Cygwin, from what you mention, but I'm pretty sure Microsoft doesn't preinstall GPL-covered libraries from GNU with THEIR stuff... a suitable Windows version need to be procured and installed in some other way (having no Windows around I'm hard put to suggest what is the best way to do this these days). > So I'm afraid you might need someone with access to VC to test this on > Windows for you, sorry. Tx for the attempt, but I don't think VC per se will suffice -- somebody needs to build or find a suitable version of GMP for Windows, too. Alex From steve at holdenweb.com Wed Nov 30 05:33:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Nov 2005 10:33:08 +0000 Subject: Nested loop In-Reply-To: <1133339863.718152.140770@g43g2000cwa.googlegroups.com> References: <1133339863.718152.140770@g43g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > viewcharts wrote: > >>I am reading two text files comparing the values in one to the other, >>this requires two loops. The problem is that when the inner loop is >>finished, it never goes back into the loop. Any suggestions? >> >> >>for refSymbol in symbols.readlines(): >> for lookupSymbol in myfile.readlines(): >> showme = lookupSymbol.split('\t') >> if showme[3] == refSymbol.strip(): >> priceNew.write(refSymbol.strip()+" "+showme[10]) > > As another poster said, you have "used up" the inner iterable in the > first round, it is an iterable, just not like a list where you can use > multiple times. > The result of the readlines() function *is* a list, which is precisely why it's been used up: >>> f = file("mail.py") >>> type(f.readlines()) >>> A second call to readlines just gets an empty list, since there are no more lines left to be read. > Either turn it into a list(so you can reuse it) or better yet, turn it > into a dict which would speed up the matching process. Either way, it > better be done outside of the outer loop. > The solution, as already proposed, is to bind the list of lines to a nanme so it can be reused. 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 rrr at ronadam.com Tue Nov 8 00:01:00 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 08 Nov 2005 05:01:00 GMT Subject: overloading *something In-Reply-To: <1h5obt1.ml6ib01swfdhbN%aleax@mail.comcast.net> References: <1h5obt1.ml6ib01swfdhbN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > Ron Adam wrote: > > >>James Stroud wrote: >>>And, how about the "**something" operator? >>> >>>James >> >>A dictionary would be pretty much the same except subclassed from a >>dictionary of course. > > > I believe this one is correct (but I have not checked in-depth!). > > > Alex A quick test shows the error message to be very specific in this case, where as the *something error message requests a more general sequence. >>> def foo(**b): pass ... >>> class a: pass ... >>> foo(**a) Traceback (most recent call last): File "", line 1, in ? TypeError: foo() argument after ** must be a dictionary Ron From usenet.20.evilspam at spamgourmet.com Sat Nov 12 01:24:57 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sat, 12 Nov 2005 06:24:57 GMT Subject: Dynamically Update Class Definitions? In-Reply-To: <0Zedf.474$MY4.174@trnddc03> References: <1131732708.541270.192310@g47g2000cwa.googlegroups.com> <1h5vngr.1060ihnqpqg6N%aleax@mail.comcast.net> <0Zedf.474$MY4.174@trnddc03> Message-ID: Chris Spencer wrote: > Alex Martelli wrote: >> If you're in no hurry, you COULD loop over all of gc.get_objects(), >> identify all those which are instances of old_class and "somehow" change >> their classes to new_class -- of course, x.__class__ = new_class may >> well not be sufficient, in which case you'll have to pass to update a >> callable to do the instance-per-instance job. > > > Couldn't I just loop over gc.get_referrers(cls), checking for instances > of the class object? Since class instances refer to their class, the gc > seems to be doing the exact same thing as Hudson's fancy metaclass. Or > am I missing something? > > Chris In fact, the following code seems to work, and doesn't require any modification to new-style class based code: import os import time import threading import inspect import gc import copy class ModuleUpdater(object): ''' This will constantly check a module's source file for updates, reload if any are detected, and update all class instances. Only works for new-style classes. Use like: checker = ModuleUpdater(module=mymod) checker.start() ''' def __init__(self, module): self.module = module self.lastloaded = time.time() self.running = 0 self.t = None def __call__(self): self.running = 1 while self.running: self.check() time.sleep(1) def check(self): lastmodified = os.stat(inspect.getsourcefile(self.module))[8] if lastmodified > self.lastloaded: print 'update detected for',self.module.__name__ oldmod = copy.copy(self.module.__dict__) newmod = reload(self.module) try: for name,obj in oldmod.items(): if isinstance(obj,type) and name in newmod.__dict__: newobj = newmod.__dict__[name] referrers = gc.get_referrers(obj) for referrer in referrers: if isinstance(referrer,obj): # update old class instances to use new class referrer.__class__ = newobj print 'update loaded for',self.module.__name__ except Exception, e: print 'unable to load update for %s: %s' % (self.module.__name__, str(e)) self.lastloaded = lastmodified return 1 return 0 def start(self): t = threading.Thread(target=self) t.setDaemon(1) t.start() self.t = t return t def stop(self, blocking=0): self.running = 0 if blocking: self.t.join() if __name__ == '__main__': import testmod # any module containing class Bar with method meth uc = ModuleUpdater(testmod) uc.start() b=testmod.Bar(1) while 1: # meanwhile, modify the source to testmod.py time.sleep(1) print b.meth() From gsakkis at rutgers.edu Mon Nov 21 12:18:02 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 21 Nov 2005 09:18:02 -0800 Subject: Immutable instances, constant values References: Message-ID: <1132593482.209912.194970@g14g2000cwa.googlegroups.com> Steven D'Aprano wrote: > Yes, that would be how I interpret constants: You want a name which can't > be re-bound to something else. > > One work-around is to use the convention of writing the name in all caps: > > CONSTANT = some_value > > and then trust that your module user doesn't rebind CONSTANT. I'd like to > see support for something a little stronger than just "cross your fingers > and hope", without necessarily going all the way to Pascal's full > enforcement of constants. "We're all adults here" -- if somebody *really* > wants to rebind CONSTANT, I'm not going to stop them, but I want them to > jump through a hoop to do it, as a reminder that the module creator thinks > they shouldn't be doing it. Another workaround if you tradeoff strictness with convenience is define a CONST metaclass in which contants are accessed as attributes and which raises an Exception in __setattr__: class CONST(type): def __new__(cls, name, bases, dict): def __setattr__(self,attr,val): raise AttributeError('Cannot reassign constant %s.%s' % (name, attr)) cls.__setattr__ = __setattr__ return type.__new__(cls, name, bases, dict) class PhysicsConstants(object): __metaclass__ = CONST c = 2.9979246e+08 >>> PhysicsConstants.c = 0 AttributeError: Cannot reassign constant PhysicsConstants.c George From onurb at xiludom.gro Wed Nov 9 06:44:48 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 09 Nov 2005 12:44:48 +0100 Subject: Hi, from my login i want to login as a other user , In-Reply-To: <1131533184.096101.49940@g49g2000cwa.googlegroups.com> References: <1131533184.096101.49940@g49g2000cwa.googlegroups.com> Message-ID: <4371e131$0$19929$626a54ce@news.free.fr> sumi wrote: > Hi, from my login i want to login as a other user , how can i do it > using python. http://www.catb.org/~esr/faqs/smart-questions.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mark.dufour at gmail.com Mon Nov 7 19:18:07 2005 From: mark.dufour at gmail.com (Mark Dufour) Date: Tue, 8 Nov 2005 01:18:07 +0100 Subject: Shed Skin Python-to-C++ compiler 0.0.5 released! Message-ID: <8180ef690511071618s6b248222w541efc81ddea35a5@mail.gmail.com> Hi all, I have just released Shed Skin 0.0.5. It fixes many bugs and adds many minor features to the Python builtins, most notably, the 'set' class. There have also been some optimizations on the C++ side. Finally, the README now better explains the compiler's limitations, and a TODO file has been added containing open bugs. I would like to invite anyone to try out this new version, especially if there were problems with 0.0.4. If you encounter a bug or missing feature, please send me a small code fragment that exhibits the problem, so I can fix it or add it to the TODO. If you are a C++ programmer, please consider helping out on the C++ side, by sending in patches to improve the C++ implementation of the Python builtins! For 0.0.6 (a feature release!), the following things are on my list: - Basic inheritance support - Automating the connection to the Python standard library - Better error messages for things SS doesn't handle (Finally?!) Shed Skin can be downloaded here: http://shedskin.sourceforge.net. I also maintain a blog about the project: http://shed-skin.blogspot.com. Thanks!! Mark. From aleax at mail.comcast.net Thu Nov 24 12:23:11 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 24 Nov 2005 09:23:11 -0800 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> Message-ID: <1h6ixcd.min0y918f4hthN%aleax@mail.comcast.net> Ben Finney wrote: ... > > A type implemented in C offers different possibilities than one > > implemented in Python -- no deep conceptual reason, just practical > > ones. > > So, in the hypothetical situation that all Python types were > implemented in pure Python, what would the ideal behaviour for > immutables be? Or would there be no immutables? Pypy is implementing Python in Python and using just the same semantics as CPython. Of course, there IS some sleight of hand, because there are still two "sides" -- interpreter level and application level... stuff implemented in interpreter level Python plays just the same role as stuff implemented in C does in CPython. Musing theoretically, I can see an *ideal* approach would have to meet higher aesthetic goals than Python's -- reach for richer symmetry, e.g., all types existing in mutable and immutable flavors (Ruby comes sort of close, with plain and frozen objects). Python's more about pragmaticity than purity (and, therefore, than idealness)... > I'm looking for a "consenting adults" restriction: classes will have > immutable instances only where it makes sense from the class protocol. > I'm not going to lose sleep over users who go looking for trouble. Yep, I understand this, now that you've explained in more detail, and FWIW I do approve. One more piece of advice: you might document that, in circumstances where (using a normal Python class's instances) the obvious approach would be to add some per-instance attribute to the instances (with semantics totally outside the class), your users might be better advised to employ a weakref.WeakKeyDictionary with the instances as keys. Although a tad more cumbersome, they can get the same semantics this way, even though it may seem "inside-out" wrt the "intuitive" approach. Alex From ccurvey at gmail.com Sun Nov 27 19:32:38 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 27 Nov 2005 16:32:38 -0800 Subject: importing a method In-Reply-To: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> Message-ID: <1133137958.685179.286140@o13g2000cwo.googlegroups.com> why not just have your user subclass "soandso" and override the definition of "custom"? from soandso import soandso class MyClass(soandso): def custom(self): self.theother = 3 c = MyClass() From alanmk at hotmail.com Mon Nov 7 16:05:46 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 07 Nov 2005 21:05:46 +0000 Subject: Map of email origins to Python list In-Reply-To: <1131396963.363256.12250@g47g2000cwa.googlegroups.com> References: <1131390365.721288.272070@g47g2000cwa.googlegroups.com> <1131396963.363256.12250@g47g2000cwa.googlegroups.com> Message-ID: [Robert Kern] >>Most of AOL's offices are in Dulles, VA. Google's headquarters are in >>Mountain View, CA. [mensanator at aol.com] > Aha, I post to the usenet through Google. Makes the map application > all the more stupid, doesn't it? Actually, no, because Google Groups sets the NNTP-Posting-Host header to the IP address from which the user connected to Google. So your post to which I'm replying came from IP address "68.73.244.37", which reverses to "adsl-68-73-244-37.dsl.chcgil.ameritech.net". http://groups.google.com/group/comp.lang.python/msg/ca06957210fe12ae?dmode=source So presumably "chcgil" indicates you're in Chicago, Illinois? Although I do have to point out that the map makes it appear as if I've been busy posting from all over Dublin's Southside, which, as anyone who has seen "The Commitments" can attest, is a deep insult a born-and-bred Northsider such as myself ;-) -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From mwm at mired.org Tue Nov 15 15:04:55 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 15 Nov 2005 15:04:55 -0500 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> Message-ID: <86fypxr82g.fsf@bhuda.mired.org> "Ben Sizer" writes: >> But we can be >> explicit if you want: How do you do that without requiring that your >> software be given special consideration in the distaster recovery and >> preparedness planning? > I should state that I am not at all claiming a "one size fits all" > policy for software development. Firstly, from a personal point of view > I am talking about simple consumer entertainment software which is not > mission critical or anything like it. For more important software, > there will surely be different expectations and requirements. In my > case, providing a free download of any lost executables or data upon > presentation of a legitimate license key should be adequate. In other words, you don't do that at all. My special handling for such things - and *especially* for entertainment software, where the media gets handled by children - is "Return that POS." Worse yet, you play semantic games so you can claim not to be violating fair use rights in the process. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Thu Nov 10 05:12:41 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 10 Nov 2005 10:12:41 +0000 Subject: getting results into one variable In-Reply-To: <1131611798.561119.48770@g43g2000cwa.googlegroups.com> References: <1131611798.561119.48770@g43g2000cwa.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: That's a nice email address :-) > hi > the database "execute" function returns a list of logical results. Each > logical result is a list of row tuples, as explained in the documents. > In a DB-API-compliant module, execution of the query adn retrieval of the result(s) are actually sepearated: execute() executesthe query (and on some, but not all, platforms returns the number of rows in the result). Then you use either fetchone(), fetchmany() or fetchall() to retrive the results from the cursor. > everytime i use it to execute various statements, it returns me, for > example > ([(0,)], [(0,)], [(0,)]) and sometimes , ([(0,)], [(0,)]) or ([(0,)]) > What you seem to be saying here is that you are getting a tuple of lists, each of which contains a (single-element) tuple. What mopdule are you using to do this, or is it the result of a gedanken-experiment? > in my call, i give > eg (a,b,c) = db.execute(stmt) so that it returns me ([(0,)], [(0,)], > [(0,)]) > > in python, can we do something like > > a = db.execute(stmt) and then expand variable 'a' > > instead of doing > (a,b) = db.execute(stmt) for return of 2 > (a,b,c) = for return of 3 > (a,b,c,d) for return of 4 > > thanks > Yes. Here's a pracical example using the database that generates www.holdenweb.com: >>> import mx.ODBC.Windows as db >>> conn = db.connect("comsite") >>> curs = conn.cursor() >>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION") >>> [Note that this returns None for this particular combination of database module and backend]. >>> rows = curs.fetchall() >>> rows [(1, 'Explore Holden Web', 'hd_explore'), (2, 'Student Links', 'hd_students'), (3, 'Other Stuff', 'hd_otherstuff'), (4, 'Recent Python News', 'hd_pythonnews'),(5, 'Python Links', 'hd_pythonlinks'), (6, 'Python Reading', 'hd_pythonreading'), (7, 'Python Modules', 'hd_pythonreviews')] >>> You see here that fetchall() returns a list of tuples - each tuple being a rows from the query result. It's normal to iterate over this list, and one way to do this is: >>> for row in rows: ... print row ... (1, 'Explore Holden Web', 'hd_explore') (2, 'Student Links', 'hd_students') (3, 'Other Stuff', 'hd_otherstuff') (4, 'Recent Python News', 'hd_pythonnews') (5, 'Python Links', 'hd_pythonlinks') (6, 'Python Reading', 'hd_pythonreading') (7, 'Python Modules', 'hd_pythonreviews') >>> Of course you can unpack each row if you want to refer to the columns individually: >>> for row in rows: ... id, title, path = row ... print title, id ... Explore Holden Web 1 Student Links 2 Other Stuff 3 Recent Python News 4 Python Links 5 Python Reading 6 Python Modules 7 >>> You can save yourself some time by doing the unpacking right in the for loop: >>> for id, title, path in rows: ... print id, title ... 1 Explore Holden Web 2 Student Links 3 Other Stuff 4 Recent Python News 5 Python Links 6 Python Reading 7 Python Modules >>> Finally, if you only want to use the result once you don't even need to save it: >>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION") >>> for id, ttl, pth in curs.fetchall(): ... print pth, ":", ttl ... hd_explore : Explore Holden Web hd_students : Student Links hd_otherstuff : Other Stuff hd_pythonnews : Recent Python News hd_pythonlinks : Python Links hd_pythonreading : Python Reading hd_pythonreviews : Python Modules >>> You can use fetchone() to return each row as a tuple if that suits you better, but it may be less efficient because it can lead to inefficient communication between the database server and the client, particularly if the result set is large. >>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION") >>> curs.fetchone() (1, 'Explore Holden Web', 'hd_explore') >>> So of course you can unpack the tuple as well: >>> id, ttl, pth = curs.fetchone() >>> print "Title:", ttl, "path:", pth, "id:", id Title: Student Links path: hd_students id: 2 >>> If the result sets are too large to comfortably hold in memory you can fetch them N at a time with fetchmany(N), repeating until there's nothing left to read. And so on, but I hope this gives you the idea. 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 qwweeeit at yahoo.it Tue Nov 1 17:35:59 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 1 Nov 2005 14:35:59 -0800 Subject: Expanding Python as a macro language In-Reply-To: <1130631958.683127.215300@g14g2000cwa.googlegroups.com> References: <1130545600.925061.287390@g49g2000cwa.googlegroups.com> <1130631958.683127.215300@g14g2000cwa.googlegroups.com> Message-ID: <1130884558.986508.198560@o13g2000cwo.googlegroups.com> I didn't want to replicate any more, expecially because the last replies (Jorgen Grahn, Sybren Stuvel and Mike Meyer) have taken a direction that doesn't interest me (GUI or not GUI?), but I must thank gmi for his contribution. gmi wrote: > This may be of some use for you: > - http://www.idyll.org/~t/www-tools/twill.html > a python tool with a language to script "web commands" I downloaded the last version of twill (0.7.3) and tried to apply it to get data from an asp file. I only succeeded in getting the first 2 chunks of data, out of almost 200, but it is the first time that I see an opportunity to make real web automation... Bye. From egbert.bouwman at hccnet.nl Wed Nov 9 05:19:28 2005 From: egbert.bouwman at hccnet.nl (egbert) Date: Wed, 9 Nov 2005 11:19:28 +0100 Subject: which feature of python do you like most? In-Reply-To: <1131502190.274658.237490@o13g2000cwo.googlegroups.com> References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> <1131502190.274658.237490@o13g2000cwo.googlegroups.com> Message-ID: <20051109101928.GA4378@hccnet.nl> python is almost pseudocode, so much so that you don't need pseudocode anymore. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From fuzzyman at gmail.com Sun Nov 27 07:30:07 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Nov 2005 04:30:07 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <4389193a.8914908@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <1132735254.039468.106660@g44g2000cwa.googlegroups.com> <4385b7b6.632202659@news.oz.net> <4389193a.8914908@news.oz.net> Message-ID: <1133094606.989139.227090@f14g2000cwb.googlegroups.com> Note that I've done two things with the Foord/Larosa dict. ;-) I've implemented slicing, including slice assignment and deletion. I've also 'hidden' ``sequence``, but you can pass arguments to keys, values and items. I've done a second (experimental) implementation of a custom keys object. This is effectively the managed list - which you can call as a method or mutate in place. You can't delete members from 'keys' but you can do slice assignment so long as the sequence you're replacing is the same length (and is a re -ordering of the set being replaced). I'll post it on Monday, and if people like it I'll complete it. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From rubencharles at gmail.com Tue Nov 1 07:26:38 2005 From: rubencharles at gmail.com (Ruben Charles) Date: Tue, 1 Nov 2005 08:26:38 -0400 Subject: Need Python Pro for Help!! Plzz In-Reply-To: References: <5uSdnSSK7vYrTfneRVn-pQ@giganews.com> Message-ID: > On the other hand, a group for learning that has no experts in it may > tend to produce "what works" style of programming as oppsoed to "what is > a good idea or practise". What is better? Good practise doesn't work better? From bonono at gmail.com Thu Nov 24 04:01:16 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 01:01:16 -0800 Subject: Making immutable instances In-Reply-To: <868xvezb2k.fsf@bhuda.mired.org> References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> Message-ID: <1132822876.386030.260610@f14g2000cwb.googlegroups.com> Mike Meyer wrote: > "Giovanni Bajo" writes: > > Mike Meyer wrote: > >> Note that this property of __slots__ is an implementation detail. You > >> can't rely on it working in the future. > > I don't "rely" on it. I just want to catch bugs in my code. > > I certainly hope you're not relying on it to catch bugs. You should do > proper testing instead. Not only will that catch pretty much all the > bugs you mention later - thus resolving you of the need to handcuff > clients of your class - it will catch lots of other bugs as well. > That is an ideal case and we all know the real world is not ideal or every program would be bug free. And I don't think anyone would solely relies on the language feature for spotting bugs. Whether this kind of guard is useful is another story. From fiedzia at fiedzia.prv.pl Sat Nov 5 06:04:55 2005 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Sat, 05 Nov 2005 12:04:55 +0100 Subject: Using Which Version of Linux References: Message-ID: <20051105110456.5205.0.NOFFLE@fiedzia.homeip.net> blahman (blah at blah.blah) wrote: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. A standard answer is - use that one, which is known to your friends, so they can help you. Actually all Linux distros come with python and huge amount of additional modules, so choose any. Fedora, Mandrake, Suse and Ubuntu willi be easier for begginers, as they are targeted on inexperienced Linux users (what doesn't mean they cannot be used by experienced), Debian requires some knowledge (well, way more then other distros) but i like it for its clarity, wonderful package manager apt and control i have over it, it is also well documented and popular. I suggest first use Knoppix - Debian based distro, that boots from cd, doesn't require installation and contains tons of software, including python of course. Solaris is a different os, has nothing to do with Linux. -- Maciej "Fiedzia" Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl) www.fiedzia.prv.pl It is my fondest hope that you are reading these while you should be working. Isn't that what the net's really about anyways? Sort of a place to go 'researching' while you should be getting stuff done! From martin at v.loewis.de Tue Nov 29 02:17:57 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 29 Nov 2005 08:17:57 +0100 Subject: cheese shop registration error In-Reply-To: References: Message-ID: <438C00A5.5030708@v.loewis.de> Todd Greenwood-Geer wrote: > Q: Do I have to be a member of some sort of secret society in order to > be listed in the 'local recipient table'? Ah, you don't know about the PSU :-? Seriously, please report a bug at sf.net/projects/pypi. Unfortunately, the (single) cheeseshop maintainer is overworked, so that may take some time. Regards, Martin From aleax at mail.comcast.net Wed Nov 16 11:53:19 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 16 Nov 2005 08:53:19 -0800 Subject: AJAX => APAX? Or: is there support for python in browsers? References: <6qpln1hg7q5up93kder88seduphnjpebtg@4ax.com> Message-ID: <1h6439o.11s40bt880tllN%aleax@mail.comcast.net> Tim Roberts wrote: ... > Internet Explorer will allow any registered ActiveScript language to be > used in a web page. Python qualifies. In the latest Win32 extensions, > there is a script in win32comext/axscript/client/pyscript.py that will > register Python as an ActiveScript language. > > The you can say > > Out of curiosity, how "sandboxed" is this Python? I remember a similar solution being withdrawn once because it wasn't really safely sandboxed, so the ``script'' could easily do any arbitrary damage to the machine... Alex From could.net at gmail.com Mon Nov 21 20:17:20 2005 From: could.net at gmail.com (could ildg) Date: Tue, 22 Nov 2005 09:17:20 +0800 Subject: How to paste python code on wordpress? Message-ID: <311b5ce10511211717q1d1cd6e7hd622c16d0f725745@mail.gmail.com> Wordpress.com blog will eat up the spaces before a line, just as it will trim every line of my article. So I can't paste python code indentedly. Does any one use wordpress blog here? Please tell me how to leave the sapces as they are when publishing ariticles on the blog, Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jdferrell3 at gmail.com Sun Nov 6 15:26:07 2005 From: jdferrell3 at gmail.com (JDF) Date: 6 Nov 2005 12:26:07 -0800 Subject: Windows service using the socket module Message-ID: <1131308767.010720.143100@g14g2000cwa.googlegroups.com> I am fairly new to python and seem to have gotten ahead of myself. I am trying to write a Windows service that will return the current number of Citrix sessions to a client. This service will run on my Citrix servers for usage tracking purposes. The service itself seems to function properly, it starts, stops, logs to the event viewer, etc. The problem seems to be with the portion where it either waits to be stopped or waits for remote connection - it does not get to the 'wait for remote connection' part. If I remove the 'wait for stop request' portion the service will return the session count but of course I can't stop the service nicely. Does anyone have some example code I could take a look at or some advice to get me back on track? thanks in advance, John s = socket.socket() hostIP = socket.gethostbyaddr(socket.gethostname())[2][0] if debug == 'true': servicemanager.LogInfoMsg('Host IP: ' + str(hostIP)) s.bind((hostIP, port)) while 1: # Wait for either a connection, or a service stop request. timeout = win32event.INFINITE waitHandles = self.hWaitStop, self.overlapped.hEvent rc = win32event.WaitForMultipleObjects(waitHandles, 0, timeout) if rc == win32event.WAIT_OBJECT_0: # Stop event break else: s.listen(5) while True: sessions = 0 qwinstaOut = os.popen(qwinstaCmd).readlines() for line in qwinstaOut: ## Look for active ICA sessions if (((re.search("ICA", line, re.IGNORECASE)): sessions = sessions + 1 c, addr = s.accept() ## Send session count c.send(str(sessions)) c.close() From ndbecker2 at gmail.com Thu Nov 3 09:21:13 2005 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 03 Nov 2005 09:21:13 -0500 Subject: shared library search path References: <87br12klws.fsf@keizer.soze.com> Message-ID: Stefan Arentz wrote: > > Hi. I've wrapped a C++ class with Boost.Python and that works great. But, > I am now packaging my application so that it can be distributed. The > structure is basically this: > > .../bin/foo.py > .../lib/foo.so > .../lib/bar.py > > In foo.py I do the following: > > sys.path.append(os.path.dirname(sys.path[0]) + '/lib') > > and this allows foo.py to import bar. Great. > > But, the foo.so cannot be imported. The import only succeeds if I place > foo.so next to foo.py in the bin directory. > > I searched through the 2.4.2 documentation on python.org but I can't find > a proper explanation on how the shared library loader works. > > Does anyone understand what it going on here? > > S. > No, but here is the code I use: import sys sys.path.append ('../wrap') From grante at visi.com Tue Nov 1 17:26:26 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Nov 2005 22:26:26 -0000 Subject: WTF? References: Message-ID: <11mfqsibenjoqff@corp.supernews.com> On 2005-11-01, James Stroud wrote: > Why do my posts get held for suspcious headers and troll Xha > Lee gets to post all sorts of profanity and ranting without > any problem? Held? It's not a moderated group... -- Grant Edwards grante Yow! I'm a fuschia bowling at ball somewhere in Brittany visi.com From william.peterson at mchsi.com Fri Nov 25 14:31:24 2005 From: william.peterson at mchsi.com (Bill) Date: 25 Nov 2005 11:31:24 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132947084.906457.289850@o13g2000cwo.googlegroups.com> peter.mosley at talk21.com wrote: > I am trying to learn GUI programming in Python, but have to confess I > am finding it difficult. > > Googling around it seems the best GUI is either Tkinter or PyGtk. This statement is, and has been subject to much debate. If you ask 10 people on this newsgroup you'll probably get 12 opinions. If you're having trouble at this early stage, you might want to reconsider and take another look at either QT or wxWidgets. I've been through the QT tutorial and was quite satisfied with it, although I'll admit I was not a GUI newby at the time. I also found the tutorial accompanying Boa Constructor (http://boa-constructor.sourceforge.net/) to be a good start at creating a wxWidgets GUI. Bill From bokr at oz.net Thu Nov 24 04:26:46 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 24 Nov 2005 09:26:46 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <43837bf7.485835644@news.oz.net> <43845a44.542744996@news.oz.net> Message-ID: <438583a2.618870558@news.oz.net> On Wed, 23 Nov 2005 13:23:21 +0100, "Fredrik Lundh" wrote: >Bengt Richter wrote: > >> Are you thinking of something like lines from a file, where there might be >> chunky buffering? ISTM that wouldn't matter if the same next method was called. >> Here we have multiple references to the same iterator. Isn't e.g. buiding >> a plain tuple defined with evaluation one element at a time left to right? > >yeah, but what says that the iterator has to be called during tuple construction? > > while 1: > for each sequence: > # optimize cache behaviour! > grab up to N items from each iterator > M = length of shortest output list > for i in range(M): > build tuple and append > if M != N: > break > I'd say it's ok to cache some iterator output, but the cache buffer must be associated with the iterator like cachedict[id(it)]. Then the loop would only pump up the same cache buffer, since all iterators would refer to the same buffer, and the loop that builds the tuple would draw one from "each" buffer unknowingly drawing from the same buffer, since they would be all found by cachedict[id(it)] which would be the same. This would preserve the identity and logical sequentiality of the data stream(s). To buffer separately on the unverified assumption that they are different iterators seems like a buggy implementation to me ;-) (optimizing use of total available buffering space is another matter, not to mention handling StopIteration in the buffer loading) ISTM to me the easiest just to define the intuitive behaviour, and let implementers buffer accordingly if they want to. Regards, Bengt Richter From bokr at oz.net Tue Nov 8 04:33:00 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 08 Nov 2005 09:33:00 GMT Subject: os.path.getmtime on winXP References: <43704c83@news.broadpark.no> Message-ID: <43706983.433918702@news.oz.net> On Tue, 08 Nov 2005 07:57:44 +0100, =?ISO-8859-1?Q?Jorg_R=F8dsj=F8?= wrote: >[sorry to those reading twice, but I just realised that I had posted >this after mucking about with the date on my machine to try to figure >this out -- so the message probably went into last months messages for >most people including me.] > >Hi > >I'm trying to use os.path.getmtime to check if a file has been modified. > My OS is WinXP. The problem is, that when the os changes from/to >daylight savings time, the result is suddenly off by 3600 seconds ie. >one hour, even if the file remains the same. Well, if the file hasn't been modified, the file time should be wrt a constant epoch, so you must be observing a DST-corrected conversion of that number, but you don't show what you are using. E.g. you can convert with time.localtime or time.gmtime, and format the result any way you want with time.strftime(...) >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime('wc.py'))) '2003-09-10 14:38:57' >>> time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getmtime('wc.py'))) '2003-09-10 21:38:57' Which comes from >>> os.path.getmtime('wc.py') 1063229937 And default localtime formatting is >>> time.ctime(os.path.getmtime('wc.py')) 'Wed Sep 10 14:38:57 2003' which is >>> time.asctime(time.localtime(os.path.getmtime('wc.py'))) 'Wed Sep 10 14:38:57 2003' the GMT version of which is >>> time.asctime(time.gmtime(os.path.getmtime('wc.py'))) 'Wed Sep 10 21:38:57 2003' reflecting >>> os.system('dir wc.py') Volume in drive C is System Volume Serial Number is 14CF-C4B9 Directory of c:\pywk\clp 03-09-10 14:38 595 wc.py > >I've tried using win32file.GetFileTime, and it reports a consistent >number, regardless of DST. > >What is happening here? My first thought is that getmtime should measure >'raw' time, and not be concerned with DST, and thus give me the same >result no matter the date on the machine I call it. Is the module broken >in some way, or am I just missing something here? > How did you format the number you got from os.path.getmtime? You might want to try some of the above. If you actually created/modified files just before and after the DST change and saw an extra hour difference instead of the time between the two actions, then maybe I'd look into whether the OS has some perverse option to use local DST time to record in the file stat info, but that's hard to believe. More likely someone is messing with with raw file time setting, like touch. Don't have it handy to see what DST assumptions it makes if any. Regards, Bengt Richter From zelzel.zsu at gmail.com Fri Nov 11 02:21:58 2005 From: zelzel.zsu at gmail.com (zelzel.zsu at gmail.com) Date: 10 Nov 2005 23:21:58 -0800 Subject: how can i get system time? Message-ID: <1131693718.127836.168950@z14g2000cwz.googlegroups.com> Hi, Can I get a system date time? I want to get current time, like the target string should looks like: the output of : `date +"%Y%m%d %H:%M:%S"` how can i do this? thanks. From daniel.dittmar at sap.corp Mon Nov 14 05:18:58 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Mon, 14 Nov 2005 11:18:58 +0100 Subject: D foreach In-Reply-To: <1131904860.125509.150090@g49g2000cwa.googlegroups.com> References: <1131904860.125509.150090@g49g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > The Digital Mars D compiler is a kind of "improved c++", it contains a > "foreach" statement: > http://www.digitalmars.com/d/statement.html#foreach > > Usage example: > foreach(int i, inout int p; v1) p = i; > > Is equal to Python: > for i in xrange(len(v)): v[i] = i [...] > So the variable p contains (scans) the elements of the given iterable > object, but if you assign p with a value, that value becomes copied > inside the mutable iterable too. Those are little examples, but I think > it can be quite useful in more complex code. 1. It would be difficult to implement. Python would require the concept of 'reference to variable', which has lots of repercussions for reference counting, garbage collection etc. Requiring iterators to return references would also break all existing iterators. It would also be required that the assignment operator is overloadable and this is another box of Pandora no one likes to open (well, no one except C++ programmemrs). Or the compiler would have to detect 'assignment to iterator variable' and issue an 'update_current' to the iterator. 2. It violates the Zen of Python 'Explicit is better than implicit' (although the definition of 'explict' varies wildly in the Python community) 3. For specific collections like lists and dictionaries, you could write a wrapper so that it is possible to write for ref in wrapper (mycollection): print ref.value ref.value = newvalue Daniel From rschroev_nospam_ml at fastmail.fm Sat Nov 12 11:40:55 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 12 Nov 2005 16:40:55 GMT Subject: tutorial example In-Reply-To: References: <20051112015026.74881.qmail@web35903.mail.mud.yahoo.com> Message-ID: Ruben Charles wrote: > That is the diference between a method and a function. > A method do something and a function return something. I'd rather say it's the difference between a procedure and a function, as it is used in e.g. Pascal. Procedures in Pascal don't return anything, more or less analogue to functions returning void in C/C++. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From s99999999s2003 at yahoo.com Thu Nov 10 03:36:38 2005 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 10 Nov 2005 00:36:38 -0800 Subject: getting results into one variable Message-ID: <1131611798.561119.48770@g43g2000cwa.googlegroups.com> hi the database "execute" function returns a list of logical results. Each logical result is a list of row tuples, as explained in the documents. everytime i use it to execute various statements, it returns me, for example ([(0,)], [(0,)], [(0,)]) and sometimes , ([(0,)], [(0,)]) or ([(0,)]) in my call, i give eg (a,b,c) = db.execute(stmt) so that it returns me ([(0,)], [(0,)], [(0,)]) in python, can we do something like a = db.execute(stmt) and then expand variable 'a' instead of doing (a,b) = db.execute(stmt) for return of 2 (a,b,c) = for return of 3 (a,b,c,d) for return of 4 thanks From lycka at carmen.se Fri Nov 4 10:21:07 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 04 Nov 2005 16:21:07 +0100 Subject: Class Variable Access and Assignment In-Reply-To: <1131049615.656278.24270@g47g2000cwa.googlegroups.com> References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <1131049615.656278.24270@g47g2000cwa.googlegroups.com> Message-ID: Graham wrote: > My question remains however, i suppose i'm not familiar with how this > functions in > other languages, but what is the common way of referring to a class > variable. > > is . the norm? > or . the norm. It's not always that easy, due to inheritance. You might want the defined in the class where a method you define now is implemented (A. if we're in a method defined in class A), or you might want in the class of the instance object (which could be a subclass of A). You can get that through self.__class__., so I guess you could always manage without Python searching in the class scope after searching the instance scope, if it wasn't for the problem below... > I just seems to me that . shouldn't defer to the class > variable if > an instance variable of the same name does not exists, it should, at > least how i > understand it raise an exception. So, you want this: >>> class A: ... def f(self): ... print 'Hello' ... >>> a = A() >>> a.f() Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'f' A bit boring that we need to make method calls with a.__class__.f(a) in your Python... Python is more consistent than you have thought... You know, it could be that we want to assign the method to another variable, as in: o = A() o_f = o.f # This might look as I'm getting a normal # attribute, but f is a method for i in range(gazillion): o_f() # This is slightly faster than o.f() Or, we might want to do: o.f=len o.f('Hello') Here, o.f is no longer a method in o's class hierarchy, but it's still callable. If you think about it, you'll understand that in such a dynamic language as Python, there is no way that the interpreter can know before lookup whether it will find a method or a simple attribute. If it's going to look in different places depending on what it will find when it has looked...we have a Catch 22. Normal methods in Python are defined in the scope of the class, and they are passed the instance object as their first argument when they are called. The call (where the instance object is implicitly called in case of a bound method) is something that comes after the lookup, as you can see in the a_f() example. Python is *very* dynamic. The behaviour of the class can change after the instance has been created. >>> class A: ... def f(self): ... print 'Hello' ... >>> a = A() >>> a.f() Hello >>> del A.f >>> a.f() Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'f' How would this work if 'a.f' doesn't cause a lookup in A if it's missing in a? Do you want a.f to first search the instance a, then the class A, and if it finds f in A, issue an AttributeError if it turns out that f isn't a method? From xah at xahlee.org Thu Nov 24 03:59:26 2005 From: xah at xahlee.org (Xah Lee) Date: 24 Nov 2005 00:59:26 -0800 Subject: Xah's Edu Corner: Sophie's World Message-ID: <1132822766.956904.130760@g43g2000cwa.googlegroups.com> Recommended: Sophie's World, by Jostein Gaarder, 1995. http://en.wikipedia.org/wiki/Sophie%27s_World http://www.amazon.com/gp/product/0425152251/ Xah xah at xahlee.org ? http://xahlee.org/ From paidhi at mospheira.net Sun Nov 6 09:50:10 2005 From: paidhi at mospheira.net (Markus) Date: Sun, 06 Nov 2005 15:50:10 +0100 Subject: I need Motivation In-Reply-To: References: Message-ID: <29127$436e1823$54728e3f$29607@news.chello.at> I can recommend you listening to the Python411 podcast. http://www.awaretek.com/python/index.html -Markus- blah at blah.blah wrote: > I m not a python Expert or anythin > i need help, i m losin my motivation to continue with python > can anyone inspire me again.??? From ivan.sas at gmail.com Fri Nov 4 10:47:52 2005 From: ivan.sas at gmail.com (Ivan Sas) Date: Fri, 4 Nov 2005 16:47:52 +0100 Subject: Shareware in Python Message-ID: <23a796c20511040747j960be13qc7b91bd7879dc5af@mail.gmail.com> I want to create some shareware program in Python. Can I distribute this program with python24.dll file from Python 2.4.2? I'm not sure if Python GPL compatible license allowing for doing it. Thanks, Ivan Sas From jeff at schwabcenter.com Mon Nov 14 10:38:46 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Mon, 14 Nov 2005 15:38:46 GMT Subject: generate HTML In-Reply-To: <1131962200.216285.307760@g44g2000cwa.googlegroups.com> References: <1131962200.216285.307760@g44g2000cwa.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > hi > i have fucntion that generates a HTML page > > def genpage(arg1,arg2): > print '''
BLAH BLAH.....%s %s > ''' % (arg1, arg2) > > print ''' ....blah blah... %s %s > >
''' % (arg1,arg2)' > > The func is something like that, alot of open''' and closing ''' triple > quotes. anyway, i wish to print all these into a HTML output file so > that when i click on it, it shows me the html page. How can i do that? > > i tried > f = open("output.html","w") > f.write ( 'print '''
> I am stuck at above after doing a lot of f.write for every line of HTML > . Any betterways to do this in python? > > something like here documents in a shell script where it can also be > directed to a file. > thanks > Why not just redirect the output of your Python script from the shell? E.g.: python generate_html.py > output.html From aleax at mail.comcast.net Sat Nov 5 23:11:23 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 5 Nov 2005 20:11:23 -0800 Subject: GMPY: divm() memory leak revisited References: <1131151958.314488.310400@z14g2000cwz.googlegroups.com> Message-ID: <1h5kl68.1qpifts1rxnrlpN%aleax@mail.comcast.net> mensanator at aol.com wrote: ... > Unfortunately, I don't have any means of testing this theory. Yep -- I reproduced the memory leak you mentioned, and easily fixed it (exactly as you suggest) in the current CVS version of gmpy (meant to be "1.01 release candidate"). I need to fix some other pending bugs, then remind myself of how the (expl.del) one makes a release on Sourceforge, then it shd be fine (except for Windows -- I have no Windows development system around to do anything... Mac and Linux only). One of the bugs I must still get around to examining is the algorithmic one you mention in your next post, btw. Thanks for your diagnostic and debugging help. BTW, should you wish to mail me privately, I'm "aleaxit" (my favourite userid, with or w/o the trailing "it" depending on service -- see www.aleax.com to understand why that is the case), and the best way to reach me these days is through "gmail.com" . Alex From cito at online.de Thu Nov 24 14:06:46 2005 From: cito at online.de (Christoph Zwerschke) Date: Thu, 24 Nov 2005 20:06:46 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <1h6iyik.86v3t3z8icd7N%aleax@mail.comcast.net> References: <8664qi3oef.fsf@bhuda.mired.org> <1h6iyik.86v3t3z8icd7N%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > Absolutely not in my use cases. The typical reason I'm asking for > .values() is because each value is a count (e.g. of how many time the > key has occurred) and I want the total, so the typical idiom is > sum(d.values()) -- getting a result set would be an utter disaster, and > should I ever want it, set(d.values()) is absolutely trivial to code. Agree. This reason alone is enough for values() to be a list, besides the problem that it can contain unhashable values. > Note that in both cases I don't need a LIST, just an ITERATOR, so > itervalues would do just as well (and probably faster) except it looks > more cluttered and by a tiny margin less readable -- "the sum of the > values" rolls off the tongue, "the sum of the itervalues" doesn't!-) > So, the direction of change for Python 3000, when backwards > compatibility can be broken, is to return iterators rather than lists. > At that time, should you ever want a list, you'll say so explicitly, as > you do now when you want a set, i.e. list(d.values()) Sounds reasonable. > In Python today 'in' doesn't necessarily mean set membership, but some > fuzzier notion of "presence in container"; e..g., you can code > > 'zap' in 'bazapper' > > and get the result True (while 'paz' in 'bazapper' would be False, even > though, if you thought of the strings as SETS rather than SEQUENCES of > characters, that would be absurd). So far, strings (plain and unicode) > are the only containers that read 'in' this way (presence of subsequence > rather than of single item), but one example should be enough to show > that "set membership" isn't exactly what the 'in' operator means. In this case, I would interpret the set on which 'in' operates as the set of all substrings of the given string to have peace for my soul ;-) > You appear to have a strange notion of "derived data type". In what > sense, for example, would a list BE-A set? It breaks all kind of class > invariants, e.g. "number of items is identical to number of distinct > items", commutativity of addition, etc.. Sorry. Your're right. In the computer world, sets are derived from lists (collections). In mathematics, lists are derived from sets. Here, you would define the list [1, 1] as the set {1, {1, 1}} (you see, the cardinality is the same). Yes, mathematics is strange ;-) Actually, in mathematics, everything is a set and set theory is the "theory of everything". When I grew up pedagogues here in Germany even believed it would be best if kids learn set theory and draw venn diagrams before they learn arithmetics... We were tortured with that kind of things in the first class. Probably I'm still suffering from the late damages of that treatment. -- Christoph From http Fri Nov 4 07:42:54 2005 From: http (Paul Rubin) Date: 04 Nov 2005 04:42:54 -0800 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: <7xk6fovb1t.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > There are good usage cases for the current inheritance behaviour. Can you name one? Any code that relies on it seems extremely dangerous to me. From falcon3166 at hotmail.com Fri Nov 18 19:18:24 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 18 Nov 2005 17:18:24 -0700 Subject: Can anyone tell me if pygame and Tkinter can work together? References: <437ab8b5$0$20233$88260bb3@news.atlantisnews.com><437b81d9$0$20257$88260bb3@news.atlantisnews.com> Message-ID: <437e6694$0$20272$88260bb3@news.atlantisnews.com> Even its from one or two external libraries like Tkinter and pygame? I prefer to load what I need, not to constantly have to call it by its library dot its_name. It makes easier coding for me. I try to keep my code as simply as possible. Wonder if its possible to use a Tkinter question to make a pygame run again (example being you get killed on a level and you want to play again without exiting)? -- For great sites go to: http://www.the-web-surfers-store.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty "Fredrik Lundh" wrote in message news:mailman.757.1132171839.18701.python-list at python.org... > Nathan Pinno wrote: > >> It's a warning that says: >> >> Can only use * in top level or something like that. >> >> It's kind of annoying > > why? importing tons of unknown stuff into a local namespace is > rather silly, and makes it impossible for the compiler to properly > analyze your code -- which means that you cannot use nested > scoping. the language reference says: > > The from form with "*" may only occur in a module scope. > If the wild card form of import -- "import *" -- is used in a > function and the function contains or is a nested block with > free variables, the compiler will raise a SyntaxError. > > future versions of Python will most likely issue a SyntaxError also > for "import *" in non-nested functions. > >> but the program still ran after I made the import * lines top level, >> and removed the def's. > > moving the "import *" line to the module scope would have been > enough; functions can refer to module-level variables just fine. > > you might wish to read up on Python scoping rules: > > http://docs.python.org/ref/naming.html > > > > -- ............................................................. > Posted thru AtlantisNews - Explore EVERY Newsgroup < > http://www.AtlantisNews.com -- Lightning Fast!!! < > Access the Most Content * No Limits * Best Service < From jepler at unpythonic.net Sat Nov 12 09:57:11 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 12 Nov 2005 08:57:11 -0600 Subject: changeing users on linux In-Reply-To: <86mzka331n.fsf@bhuda.mired.org> References: <1131766541.519931.313710@g44g2000cwa.googlegroups.com> <86mzka331n.fsf@bhuda.mired.org> Message-ID: <20051112145710.GA27610@unpythonic.net> On Fri, Nov 11, 2005 at 11:25:56PM -0500, Mike Meyer wrote: > You didn't say what the password was for, so I skipped asking for it. You're a real comedian. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ark at acm.org Wed Nov 23 09:23:52 2005 From: ark at acm.org (Andrew Koenig) Date: Wed, 23 Nov 2005 14:23:52 GMT Subject: wxPython Licence vs GPL References: Message-ID: "John Perks and Sarah Mount" wrote in message news:dlvmtu$fp9$1 at newsg4.svr.pol.co.uk... > we have some Python code we're planning to GPL. However, bits of it were > (This assumes the wxPython Licence is compatible with the GPL -- if not, > do we just cosmetically change any remaining lines, so none remain from > the orignal?) What makes you think that cosmetic changes in a copyrighted work affect the copyright? From stefan.arentz at gmail.com Wed Nov 9 07:11:28 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 09 Nov 2005 13:11:28 +0100 Subject: PYTHON LOOSING FOR JAVA??????? References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> Message-ID: <87oe4um367.fsf@keizer.soze.com> "Fcamattti" writes: > Hello for everybody???? OH MY GOD!?!?!?!?!?!?! I BETTER FIND A NEW JOB!?!?!?!? S. From robert.h.boyd at gmail.com Mon Nov 7 17:46:20 2005 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Mon, 7 Nov 2005 17:46:20 -0500 Subject: PYTHON LOOSING FOR JAVA??????? In-Reply-To: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> Message-ID: On 7 Nov 2005 14:04:53 -0800, Fcamattti wrote: > > So I have a doubt. I'd like to know what do you think about the joint > of efforts of Sun Microsystems and the Google to create a office web > based. I sincerely enjoy the idea althoug I'd like to know what will be > the future of this wonderful language called Python?????? > The last I read, Sun and Google have squashed the rumor that they intend to produce a Google Office. Whether or not their denial is true, and even with Google packaging Java runtime in their toolbar application, why should it impact the future of Python, or any programming language? What is your doubt about Python? Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.vets at skynet.be Thu Nov 24 08:15:19 2005 From: tim.vets at skynet.be (tim) Date: Thu, 24 Nov 2005 14:15:19 +0100 Subject: [Fwd: Python Midi Package: writing events non-chronologically] Message-ID: <4385BCE7.9090501@skynet.be> (...I sent this one a second time, waited for 60 minutes, it didn't appear, sorry if it's a double...) Someone using Python Midi Package from http://www.mxm.dk/products/public/ lately? I want to do the following : write some note events in a midi file then after doing that, put some controllers at the beginning of the midifile (because I want to be able to make those dependant on what notes were just written) def midctrls(): global roffset, melchan, roffset, gmt, timedisplay, out_file, midi, usednotes, n midi.reset_time() #seems to do nothing for cha in range(16): if cha==1: midi.abs_time=0 #seems to do nothing midi._relative_time = 0 #seems to do nothing, but I can imagine why midi._absolute_time = 0 #seems to do nothing midi.update_time(new_time=0, relative=0) #although I give the variable relative=0 it seems to be relative ? midi.continuous_controller(cha, 0, 122) (snip) With this code I want a controller number 0 with value 122 to be written at the beginning of my midifile. It is written at the end, how I move the writing position to the beginning? thanks for any help! -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded message was scrubbed... From: tim Subject: Python Midi Package: writing events non-chronologically Date: Thu, 24 Nov 2005 12:39:55 +0100 Size: 1558 URL: From dan at tangledhelix.com Mon Nov 21 21:10:56 2005 From: dan at tangledhelix.com (Dan Lowe) Date: Mon, 21 Nov 2005 21:10:56 -0500 Subject: How to paste python code on wordpress? In-Reply-To: <311b5ce10511211717q1d1cd6e7hd622c16d0f725745@mail.gmail.com> References: <311b5ce10511211717q1d1cd6e7hd622c16d0f725745@mail.gmail.com> Message-ID: <79021162-F73D-44DC-B621-1CE24E14F453@tangledhelix.com> On Nov 21, 2005, at 8:17 PM, could ildg wrote: > Wordpress.com blog will eat up the spaces before a line, > just as it will trim every line of my article. So I can't paste > python code indentedly. > Does any one use wordpress blog here? > Please tell me how to leave the sapces as they are when publishing > ariticles on the blog, You can enclose the code in a PRE block, like this:
def foobar():
     print "abc"
     if x == 3:
         print "def"
     print "ghi"
If you don't care for how it renders in a browser, hack your CSS to make PRE render in a way you like. -dan -- Well sure the government lies, and the press lies, but in a democracy they aren't the same lies. -Alexis A. Gilliland From Norbert.Klamann at klamann-software.de Sun Nov 13 13:11:27 2005 From: Norbert.Klamann at klamann-software.de (Norbert) Date: 13 Nov 2005 10:11:27 -0800 Subject: Pywin32: How to import data into Excel? References: <662DD8E0B9B5064EB60F7F8ED573CC39024C9E@ANTHRAX.xtract-hq.local> Message-ID: <1131905487.141598.61200@f14g2000cwb.googlegroups.com> Simon Brunning wrote: > On 08/11/05, Dmytro Lesnyak wrote: > > I need to import some big data into Excel from my Python script. I have TXT > > file (~7,5 Mb). > > Have you considered converting your text data to CSV format? Excel > opens CSV files happily enough, and you could always automate > save-as-workbook and any formatting you need afterwards. But there are thorny issues with different locales and number formats. Excel is also just too clever in recognising dates All the best Norbert From bonono at gmail.com Tue Nov 22 18:43:52 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 15:43:52 -0800 Subject: Converting a flat list to a list of tuples In-Reply-To: <43837bf7.485835644@news.oz.net> References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <43837bf7.485835644@news.oz.net> Message-ID: <1132703032.313209.204970@g44g2000cwa.googlegroups.com> Bengt Richter wrote: > On Tue, 22 Nov 2005 13:37:06 +0100, =?ISO-8859-1?Q?Andr=E9?= Malo wrote: > > >* Duncan Booth wrote: > > > >> metiu uitem wrote: > >> > >> > Say you have a flat list: > >> > ['a', 1, 'b', 2, 'c', 3] > >> > > >> > How do you efficiently get > >> > [['a', 1], ['b', 2], ['c', 3]] > >> > >> That's funny, I thought your subject line said 'list of tuples'. I'll > >> answer the question in the subject rather than the question in the body: > >> > >> >>> aList = ['a', 1, 'b', 2, 'c', 3] > >> >>> it = iter(aList) > >> >>> zip(it, it) > >> [('a', 1), ('b', 2), ('c', 3)] > > > >Though it looks nice, it's an implementation dependant solution. What if > >someone changes zip to fetch the second item first? > > > That would be a counter-intuitive thing to do. Most things go left->right > in order as the default assumption. > I have to admit that the poster was right as there is nothing stop the implementor to do it this way and still gives you the defined result of zip(). One scenario I can think of is that it can be implemented to run in parallel, taking "n" results from "n" streams at the same time and when all n arrived, pump the resultinging tuple out and repeat. Why it needs to be done this way or is it desirable is another story. And I doubt the current behaviour will go away, unless they really want to break some codes to make the point. From kent37 at tds.net Sat Nov 5 09:37:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 05 Nov 2005 09:37:59 -0500 Subject: re sub help In-Reply-To: <1131173343.954029.211530@o13g2000cwo.googlegroups.com> References: <1131173343.954029.211530@o13g2000cwo.googlegroups.com> Message-ID: <436cc173$1_2@newspeer2.tds.net> s99999999s2003 at yahoo.com wrote: > hi > > i have a string : > a = > "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" > > inside the string, there are "\n". I don't want to substitute the '\n' > in between > the [startdelim] and [enddelim] to ''. I only want to get rid of the > '\n' everywhere else. Here is a solution using re.sub and a class that maintains state. It works when the input text contains multiple startdelim/enddelim pairs. import re a = "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" * 2 class subber(object): def __init__(self): self.delimiterSeen = False def __call__(self, m): text = m.group() if text == 'startdelim': self.delimiterSeen = True return text if text == 'enddelim': self.delimiterSeen = False return text if self.delimiterSeen: return text return '' delimRe = re.compile('\n|startdelim|enddelim') newText = delimRe.sub(subber(), a) print repr(newText) Kent From exarkun at divmod.com Wed Nov 9 13:23:07 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 9 Nov 2005 13:23:07 -0500 Subject: Lie Hetland book: Beginning Python.. In-Reply-To: Message-ID: <20051109182307.10365.1691044805.divmod.quotient.5822@ohm> On Wed, 09 Nov 2005 17:57:46 +0000, Steve Holden wrote: >Gerhard H?ring wrote: >> Vittorio wrote: >> > [snip] >> >> I think about the only place I wrote a bit about the differences was in >> the pysqlite 2.0 final announcement: >> >> http://lists.initd.org/pipermail/pysqlite/2005-May/000043.html >> >Unfortunately this appears to mean that pysqlite2 isn't fully DB >API-conformant. > > >>> import pysqlite2 > >>> pysqlite2.paramstyle >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'module' object has no attribute 'paramstyle' > >>> The DB-API2ness is at pysqlite2.dbapi2: >>> from pysqlite2 import dbapi2 >>> dbapi2.paramstyle 'qmark' >>> dbapi2.threadsafety 1 >>> etc. :) Jean-Paul From bertle at rob.kph.tuwien.ac.at Mon Nov 21 13:24:36 2005 From: bertle at rob.kph.tuwien.ac.at (Roman Bertle) Date: 21 Nov 2005 18:24:36 GMT Subject: Numeric array in unittest problem References: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> <1132586037.388588.323670@g44g2000cwa.googlegroups.com> <1h6da2y.qucyw7nzyjejN%aleax@mail.comcast.net> Message-ID: * Alex Martelli : > ajikoe at gmail.com wrote: > > > Sorry Peter, > > > > Try this.... > > > > import unittest > > import Numeric > > > > class myTest(unittest.TestCase): > > def runTest(self): > > var1 = Numeric.array([1,22]) > > var2 = Numeric.array([1,33]) > > self.assertEqual(var1,var2) > > > > if __name__ == '__main__': > > unittest.main() > > > i.e., thanks to element-by-element evaluation, == will generally return > a true value for ANY comparison of Numeric arrays, causing a very > frequent beginner's bug to be sure. Try Numeric.alltrue(c), or > Numeric.allclose(a,b) ... I extend unittest.TestCase as follows (uses numarray, not Numeric): class NumTestCase(unittest.TestCase): """Extends TestCase with equality tests for numarrays. """ def numAssertEqual(self, a1, a2): """Test for equality of numarray fields a1 and a2. """ self.assertEqual(a1.shape, a2.shape) self.assertEqual(a1.type(), a2.type()) self.assertTrue(N.alltrue(N.equal(a1.flat, a2.flat))) def numAssertAlmostEqual(self, a1, a2): """Test for approximately equality of numarray fields a1 and a2. """ self.assertEqual(a1.shape, a2.shape) self.assertEqual(a1.type(), a2.type()) if a1.type() == 'Float64' or a1.type() == 'Complex64': prec = 15 else: prec = 7 if isinstance(a1.type(), N.ComplexType): af1, af2 = a1.flat.real, a2.flat.real for ind in xrange(af1.nelements()): self.assertAlmostEqual(af1[ind], af2[ind], prec) af1, af2 = a1.flat.imag, a2.flat.imag for ind in xrange(af1.nelements()): self.assertAlmostEqual(af1[ind], af2[ind], prec) else: af1, af2 = a1.flat, a2.flat for ind in xrange(af1.nelements()): self.assertAlmostEqual(af1[ind], af2[ind], prec) From rurpy at yahoo.com Fri Nov 18 13:48:07 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 18 Nov 2005 10:48:07 -0800 Subject: examining python objects Message-ID: <1132339687.048155.252160@g47g2000cwa.googlegroups.com> Is there a function/class/module/whatever I can use to look at objects? I want something that will print the object's value (if any) in pretty-printed form, and list all it's attributes and their values. And do all that recursively. I want to be able to find out everything about an object that Python can introspectively find out. Something like the 'x' command does in the Perl debugger. Anything like this exist? (And why isn't something like this already in pdb?) From bonono at gmail.com Fri Nov 11 22:24:49 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 11 Nov 2005 19:24:49 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <43755c74.257202327@news.oz.net> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131627394.890394.200070@g44g2000cwa.googlegroups.com> <4373bcbc.150778327@news.oz.net> <1131675601.931303.177890@g14g2000cwa.googlegroups.com> <1h5tz2c.1lmc7tlk7ge03N%aleax@mail.comcast.net> <43755c74.257202327@news.oz.net> Message-ID: <1131765889.428337.77320@g14g2000cwa.googlegroups.com> Bengt Richter wrote: > Well, it seems you do have to put them in the scopes of different generators, > not just for-clauses, depending on the semantics you want e.g., > > >>> def stop(): raise StopIteration > ... > >>> list( ((x,y) for x in xrange(20) if x<5 or stop() for y in xrange(20) if y<3 or stop())) > [(0, 0), (0, 1), (0, 2)] > >>> list( ((x,y) for x in xrange(20) if x<5 or stop() for y in (y for y in xrange(20) if y<3 or stop()))) > [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), > (4, 0), (4, 1), (4, 2)] > thanks. it works and I have explained in another post why I initially confused and thought it didn't work. stand corrected. However, I found something interesting which I don't quite understand : list((x for x in [1,2,3] if x<2 or stop())) works but a = [ x for x in [1,2,3] if x <2 or stop() ] doesn't. From sybrenUSE at YOURthirdtower.com.imagination Thu Nov 3 04:44:58 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 3 Nov 2005 10:44:58 +0100 Subject: how to write a blog system with Python References: <1130986622.788569.225120@o13g2000cwo.googlegroups.com> Message-ID: ice enlightened us with: > I am a fresh here , and I have no idea of it. Do you have any > comments? Look up "turbogears" and watch the "20 minute Wiki" video tutorial. 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 rodney_garland at hotmail.com Sat Nov 26 19:59:57 2005 From: rodney_garland at hotmail.com (Rodney Garland) Date: Sat, 26 Nov 2005 16:59:57 -0800 Subject: SOAP - Beginner Desperately looking for Help Message-ID: Hi All, I am a relative beginner to Python and am looking for help with sending and XML message and getting back a return file. The server is: https://node.deq.state.or.us/node/node.asmx I have have successfully sent and recieved using the PING, AUTHENTICATE (send in username and password and return a secuirity token), SOLICIT(send in information for a query and get a number indicating the query), GETSTATUS(status of query) using SOAPpy. I am using Python 2.4 on a Window XP machine. What I want to do now is download the result of my query using the DOWNLOAD method. However, I cann't figure out how to do this. I have tried SOAPpy and httplib and I cann't send the correct XML outgoing message. Any help with this would be greatly appreciated. Following is the needed outgoing XML file and my successful SOAPpy code. Thank you, Rodney (rodney_garland at hotmail.com) POST /node/node.asmx HTTP/1.1 Host: node.deq.state.or.us Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "" string string string string string string string Below is an example of the code that does work. urlNode = 'https://node.deq.state.or.us/node/node.asmx?op=NodePing' namespace = 'http://www.ExchangeNetwork.net/schema/v1.0/node.xsd' server = SOAPProxy(urlNode, namespace) PING = server.NodePing('Ping') urlAuth = 'https://node.deq.state.or.us/node/node.asmx?op=Authenticate' # AUTHENTICATE - Returns a variable with the token server = SOAPProxy(urlAuth, namespace) token = server.Authenticate(userId='MYUSERNAME', credential='MYPASSWORD', authenticationMethod='Invoke') print token urlSolicit = 'https://node.deq.state.or.us/node/node.asmx?op=Solicit' server = SOAPProxy(urlSolicit, namespace) rowID='0' maxRows='1000' service='GetAirMeasurements' fieldEventStartDate='2005-01-01' fieldEventEndDate='2005-02-01' analyteName='PM10' parameters=[rowID,maxRows,'','','','','','','','','','','','','','','',fieldEventStartDate,fieldEventEndDate,'',analyteName] transID = server.Solicit(securityToken = token, returnURL = '', request = 'GetAirMeasurements', parameters = parameters) print transID From steve at REMOVETHIScyber.com.au Fri Nov 4 13:02:05 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 05:02:05 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: On Fri, 04 Nov 2005 07:46:45 +0000, Antoon Pardon wrote: >> Because b.a += 2 expands to b.a = b.a + 2. Why would you want b.a = >> to correspond to b.__class__.a = ? > > That is an implemantation detail. The only answer that you are given > means nothing more than: because it is implemented that way. You keep saying "that's an implementation detail" and dismissing the question, but that's the heart of the issue. What does b.a += 2 *mean*? It doesn't mean "sort the list referenced by b.a" -- we agree on that much. You seem to think that it means "increment the object currently named b.a by two". But that's not what it means. b.a += 2 has a precise meaning, and for ints and many other objects that meaning is the same as b.a = b.a + 2. Yes, it is an implementation detail. So what? It is an implementation detail that "b.a += 2" doesn't mean "sort the list referenced by b.a" too. In some other language, that's precisely what it could mean -- but Python is not that language. b.a has a precise meaning too, and again you have got it wrong. It doesn't mean "search b's namespace for attribute a". It means "search b's namespace for attribute a, if not found search b's class' namespace, and if still not found, search b's class' superclasses". It is analogous to nested scopes. In fact, it is a type of nested scope. In some other language, b.a could mean what you think it means, but Python is not that language. That's a deliberate design decision. Nested attribute search gives the most useful results in the most common cases, while still being easy to work around in the rare cases where it is not what is wanted. >> I'm not saying that it couldn't, if that was the model for inheritance you >> decided to use. I'm asking why would you want it? What is your usage case >> that demonstrates that your preferred inheritance model is useful? > > It has nothing to do with a model for inheritance, but with a model of > name resolution. Which is designed to act the way it does in order to produce the inheritance model. You can't have that inheritance model without that name resolution. > The hierarchie of searching an instance first in an object and then in > a class isn't that different from searching first in a local namespace > and then in a more global namespace. > > When we search names in a function we don't resolve the same name in > different name spacese each occurence of the same name in the same > function occurs in the same namespace. That's because it isn't needed for function namespaces. Names in a function don't inherit state or behaviour from names in a higher-level scope. Attribute names in classes do. > But with class variables we can have that one and the same name > on a line refers to two different namespaces at the same time. > That is IMO madness. You may argue that the madness is of little > importance, you can argue that because of the current implementation > little can be done about it. But I don't see how one can defend > it as sane behaviour. Because inheritance is useful, sensible, rational behaviour for OO programming. -- Steven. From jzgoda at o2.usun.pl Thu Nov 17 15:08:45 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 17 Nov 2005 21:08:45 +0100 Subject: sqlite utf8 encoding error In-Reply-To: References: <1132228020.486726.26630@g47g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh napisa?(a): >>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 13-18: >>unsupported Unicode code range >> >>does anyone have any idea on what could be going wrong? The string >>that I store in the database table is: >> >>'Keinen Text f?r ?bereinstimmungsfehler gefunden' > > $ more test.py > # -*- coding: iso-8859-1 -*- > u = u'Keinen Text f?r ?bereinstimmungsfehler gefunden' > s = u.encode("iso-8859-1") > u = s.decode("utf-8") # <-- this gives an error > > $ python test.py > Traceback (most recent call last): > File "test.py", line 4, in ? > u = s.decode("utf-8") # <-- this gives an error > File "lib/encodings/utf_8.py", line 16, in decode > return codecs.utf_8_decode(input, errors, True) > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 13-18: > unsupported Unicode code range I cann't wait for the moment when encoded strings go away from Python. The more I program in this language, the more confusion this difference is causing. Now most of functions and various object's methods accept strings and unicode, making it hard to find sources of Unicode*Errors. -- Jarek Zgoda http://jpa.berlios.de/ From dcrespo at gmail.com Wed Nov 9 13:13:26 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 9 Nov 2005 10:13:26 -0800 Subject: Application monitor In-Reply-To: References: <1131399761.209133.19690@g49g2000cwa.googlegroups.com> <1131541757.708350.72750@g14g2000cwa.googlegroups.com> Message-ID: <1131560006.422710.20130@g44g2000cwa.googlegroups.com> Magnus Lycka wrote: > You *could* use twisted.runner for process control even if you > don't use twisted for your networking code. It does seem like > a funny thing to do, but there's nothing stopping you from doing > that. The example code in twisted.runner starts up a few shell > scripts that die on their own accord, and make sure they get > restarted, so it doesn't rely on twisted being used in the > processes it controls. Ok. I'll take a look. Thank you very much! :) Daniel From mwm at mired.org Sat Nov 26 18:07:51 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 18:07:51 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> Message-ID: <863bljf1o8.fsf@bhuda.mired.org> "Martin v. L?wis" writes: > Mike Meyer wrote: >>>class mylist1(list): >>> def __hash__(self): return 0815 >>> >>>class mylist2(list): >>> def __hash__(self): return id(self) >>> >>>In the case of mylist1, everything is ok including semantics, but >>>performance suffers dramatically. In mylist2, performance is great, >>>but semantics suffers greatly. >>>Which of these user-defined types would you call "hashable"? >> The latter two, as the given __hash__ meets the specifications for >> __hash__. > This is not true. The second definition of __hash__ does not meet > the specifications: The specification isn't on the __hash__ method, but on objects. Instances of mylist2 that aren't otherwise tweaked won't meet the specification. > http://docs.python.org/ref/customization.html > "The only required property is that objects which compare equal have the > same hash value" That's pretty flaky. The same docs say: Should return a 32-bit integer usable as a hash value for dictionary operations. the dictionary implementation requires that a key's hash value is immutable Maybe those are only "recommended" properties, but any class that doesn't meet them is going to have instances with interesting behaviors in sets and as dictionary keys. FWIW, the mutable builtins have __hash__ methods that don't meet that requirement. Instances of them don't have has values at all. > However, I can have two instances of mylist2 which compare equal, > yet have different hash values. That's a problem with mylist2 instances, and may or may not be a problem in the mylist2 __hash__ method. You can't tell just by examining the __hash__ method whether or not it meets this specification. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From http Tue Nov 8 11:47:52 2005 From: http (Paul Rubin) Date: 08 Nov 2005 08:47:52 -0800 Subject: which feature of python do you like most? References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: <7xoe4vcchz.fsf@ruckus.brouhaha.com> Alex Stapleton writes: > People like Python as a whole usually. It's not like C++ or PHP or > anything where it's generally usable and occasionally pisses you off. As somebody once said about Lisp, "you can feel the bits between your toes". From cwilbur at chromatico.net Sat Nov 5 14:54:27 2005 From: cwilbur at chromatico.net (Charlton Wilbur) Date: Sat, 05 Nov 2005 14:54:27 -0500 Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> Message-ID: >>>>> "RW" == Rick Wotnaz writes: RW> Someone is sure to jump in now and point to sample code, which RW> nearly all reasonably major packages include. That's good RW> stuff. With (for example) wxPython, it's the only useful RW> documentation, or rather, it's the only thing that makes the RW> wxWidgets documentation useful. Links to code samples in the RW> documentation would be fine in lieu of snippets of example RW> calls. But there's not enough of either in most documentation. This is one of the places where Apple's Cocoa documentation shines: there are frequently snippets of code accompanying more complicated methods, which is nice, but there are a couple dozen small sample programs that demonstrate how to use particular aspects of the framework, available with full source code. RW> I would love to see examples for essentially every function RW> and method. And not just something that echoes the signature, RW> but some context to show how it might be useful. That would be RW> in the "intoxication" class of ultimate hopes. In most cases, RW> though, it would be *extremely* helpful for a casual user of RW> that part of the package. Well, at some level you have to consider - who is the target audience of the documentation? There's usually a tradeoff involved in that documentation aimed at novice users is usually not useful to advanced users; there's also a ridiculous amount of work involved in making *all* documentation available to all users, and there's usually a better payoff involved in writing documentation that shows novice users how to be intermediate users. To take another example: in Cocoa, there's a well-defined and well-documented approach to memory management, and conventions used consistently throughout the whole Cocoa framework. These conventions could be documented over again for each and every class, but it's a much better use of resources to document them once and to assume in the documentation for each class that the reader is familiar with the conventions. Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From onurb at xiludom.gro Tue Nov 15 12:44:23 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 15 Nov 2005 18:44:23 +0100 Subject: Default method arguments In-Reply-To: References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> Message-ID: <437a1e7a$0$6131$636a15ce@news.free.fr> Dennis Lee Bieber wrote: > > (snip) > but that may not be desirable if None is a valid value => myA.f(None), > so... > > class A(object): > def __init__(self, n): > self.data =n > def f(self, *arg): > if len(arg) == 0: > x = self.data > else: > x = arg[0] > print x Another solution to this is the use of a 'marker' object and identity test: _marker = [] class A(object): def __init__(self, n): self.data =n def f(self, x = _marker): if x is _marker: x = self.data print x -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Tue Nov 8 03:19:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Nov 2005 09:19:24 +0100 Subject: socket receive file does not match sent file References: <1131297183.385236.146170@g14g2000cwa.googlegroups.com> Message-ID: zelzel.zsu at gmail.com wrote: > while True: > data = f.read(8192) > if not data: break > else: > s.send(data) > What is the cause of the problem, can anyone tell me? using sendall instead of send should fix this. see the library reference for details: send( string[, flags]) Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. sendall( string[, flags]) Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent. From godoy at ieee.org Wed Nov 2 19:38:37 2005 From: godoy at ieee.org (Jorge Godoy) Date: 02 Nov 2005 22:38:37 -0200 Subject: How to print random strings References: <1130978067.685487.194530@g44g2000cwa.googlegroups.com> Message-ID: <878xw6tvjm.fsf@ieee.org> theboringdays at gmail.com writes: > Im at the end of chapter 3 of "Python Programming For The Absolute > Beginner, Michael Dawson " and he asks to make a fortune program that > displays a fortune each time its ran, and to have 5 unique fortunes. > > Whats confusing is that, he never discussed how to do this. The only > thing he talked about was using random.randrange() and I tried that > with text but it seems like its only for integers as it complains when > I put text in the argument. > > So how would I go about have 5 strings, and running a program that will > randomly pick one of those to print? > > I think he may have forgot to cover something? How about using the integer as an index to access the elements of a list? ;-) -- Jorge Godoy From claird at lairds.us Tue Nov 8 18:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 08 Nov 2005 23:08:03 GMT Subject: A Tcl/Tk programmer learns Python--any advice? References: Message-ID: In article , Russell E. Owen wrote: . [acute observations] . . >Features of Python that are well integrated and well worth using include: >- objects >- collection classes (including list, dict and set) >- exception handling >- default arguments for functions . . . Tcl procedures roughly correspond to Python functions. The arguments of Tcl procedures can have defaults. I find the rest of the summary quite apt. From maravilloso at gmail.com Sun Nov 20 03:09:27 2005 From: maravilloso at gmail.com (Maravilloso) Date: 20 Nov 2005 00:09:27 -0800 Subject: Problem printing in Win98 Message-ID: <1132474167.583323.137390@z14g2000cwz.googlegroups.com> Hi I'm trying to automatically send a postscript file to be printed to the default printer in a Win98 PC, by means of using the instrucction: win32api.ShellExecute (0, "print", "file.ps", None, ".", 0) but it raises an exception with the message: error: (31, 'ShellExecute', 'A device attached to the system is not functioning.') Curiously, that instruction does works on Win2K/XP, but trying to use this shortcut for easy printing in Win98 provokes such error. I've tried in different machines (all of them running with Win98) and I obtain the same output. Does anybody knows what happens with Win98 printing automation? Any idea? Thanks in advance From viridia at gmail.com Fri Nov 18 11:57:30 2005 From: viridia at gmail.com (Talin) Date: 18 Nov 2005 08:57:30 -0800 Subject: Speeding up multiple regex matches Message-ID: <1132333050.519695.96370@f14g2000cwb.googlegroups.com> I've run in to this problem a couple of times. Say I have a piece of text that I want to test against a large number of regular expressions, where a different action is taken based on which regex successfully matched. The naive approach is to loop through each regex, and stop when one succeeds. However, I am finding this to be too slow for my application -- currently 30% of the run time is being taken up in the regex matching. I thought of a couple of approaches, but I am not sure how to make them work: 1) Combine all of the regular expressions into one massive regex, and let the regex state machine do all the discriminating. The problem with this is that it gives you no way to determine which regex was the matching one. 2) Use the first character of the text string to cut down the search size. The problem here is that since I don't know the regex patterns in advance, I would need to inspect each regex and determine the possible set of starting characters that could be matched. This would require creating my own regex parser. 3) Use a lexical scannner. This is probably overkill for what I want to do. 4) Write my own regex system that does what I want. This is more work than I want to do. Any thoughts? From lycka at carmen.se Mon Nov 7 08:04:25 2005 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 07 Nov 2005 14:04:25 +0100 Subject: Python gui In-Reply-To: References: <3t4ac7Fr8nn7U1@uni-berlin.de> Message-ID: Philippe C. Martin wrote: > Thanks, Tkinter it is. It really depends on what you want to achieve. If you want to make any advanced GUI application, you'll probably want some third party extension to Tkinter anyway, and then you might as well choose another tool kit from the beginning, whether it's wxPython, PyGtk or PyQt. It's not more inconvenient to rely on wxPython than to rely on e.g. Pmw (2 years since last release). From fdu.xiaojf at gmail.com Thu Nov 17 22:01:14 2005 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Fri, 18 Nov 2005 11:01:14 +0800 Subject: Hot to split string literals that will across two or more lines ? Message-ID: <437D43FA.2060606@gmail.com> Hi, I need to print a long sting, which is two long so it must expand two lines. I know that we can use backslash(\) to explicitly join two lines into a logical line, but this doesn't work for string literals :( my code: ----------------------------------------------------------------------------- if sth.: print "a string whcih is very very looooooooooooooooooooooooooooooooooo\ oooooooooooooooooooong." ----------------------------------------------------------------------------- If I don't break the line, it will be very ugly, if I break the line,....but how ? Thanks in advance! xiaojf From jgrahn-nntq at algonet.se Wed Nov 9 16:12:05 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 9 Nov 2005 21:12:05 GMT Subject: triangulation References: Message-ID: On Wed, 9 Nov 2005 04:14:22 -0800, Shi Mu wrote: > is there any sample code to triangulation? many thanks! Don;t know if this is what you're looking for, but I have some code here: http://www.algonet.se/~jgrahn/comp/projects/geese-1.6.tar.gz find(neighbors) Find a (x, y) coordinate of a point, based on a sequence of (x, y, d) - neighbor coordinates and their individual distances from the desired point. It's completely unsupported, and probably sucks badly. But it works for my purposes, and there are unit tests. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From fredrik at pythonware.com Wed Nov 2 13:28:23 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Nov 2005 19:28:23 +0100 Subject: is open(...).read() a resource leak? References: <5vk6froruh.fsf@akron.bmi.ohio-state.edu> Message-ID: Benjamin Rutt wrote: > If I did the following in an infinite loop, would the host system/user > account soon run out of file descriptors? (I'm thinking no, since I'd > imagine that a file object has a __del__-like method that will call > close() automatically since it goes out of scope): > > open('/home/rutt/.bashrc,'r').read() under CPython, this is not a problem (the reference counting system will make sure that file handles are reclaimed as fast as new ones are opened). under an arbitrary Python implementation, it may be a problem, especially if the implementation doesn't trigger a collection if it runs out of handles (that can be seen as a bug, though...). From claird at lairds.us Tue Nov 8 13:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 08 Nov 2005 18:08:03 GMT Subject: Invoking Python from Python References: <1131466225.744361.7010@z14g2000cwz.googlegroups.com> Message-ID: In article , Thomas Guettler wrote: . . . >creating source code with a script, is no good solution. > >Once I had to maintain lisp code which stored its data in lisp code, too >(incl. conditions and loops). It was a nightmare. > >Please explain what you want to do, and we will find a better solution. . . . Yes and no. There are times when it's justified. I ENTIRELY agree, though, that many people who *think* that's what they want to do simply don't understand how dynamic base Python is, and therefore don't realize how much easier it can be to write a single, unified application. At this point, 'twould be appropriate to describe an instance or two in which code generation is a good idea. While I have some, they're tedious to make clear. Maybe I'll do so in a follow-up ... From dr.addn at gmail.com Fri Nov 4 22:50:30 2005 From: dr.addn at gmail.com (adDoc's networker Phil) Date: Fri, 4 Nov 2005 19:50:30 -0800 Subject: Cheapest pocket device to code python on In-Reply-To: <1131076503.645113.309940@g49g2000cwa.googlegroups.com> References: <1131076503.645113.309940@g49g2000cwa.googlegroups.com> Message-ID: <8fd4a2fe0511041950i5b9813d3tdae38214a41dc3bd@mail.gmail.com> On 3 Nov 2005 19:55:03 -0800, theboringdays at gmail.com wrote: > > What is the cheapest/affordable pocket device that I can code python > on? I think the closest I have seen is pocketpc from this page: > http://www.murkworks.com/Research/Python/PocketPCPython/Overview > *Cameron Laird * wrote: > > > .... achieves stunning results with his tiny PocketPC Magician > > http://wiki.tcl.tk/HTC%20Magician > > > . the cheapest pocketpc might be dell refurbished . > $319.00 Axim X50v Advanced Graphics 624 Mhz and VGA display > (remember vga -- that was desktop! ) > google dell axim refurbished . if your time is worth a lot, then a larger screen for $350 might be cheaper than the typical $200 . pda's have been my idea of a cheap desktop replacement; but I've been through a lot of add-on keyboards, . so now I'm looking at my python.ce as more for running programs that I wrote elsewhere, such as: my new walkable" Fujitsu P1500D (an xp pro tablet with a complete but reduced-sized kybd) [@] http://www.computers.us.fujitsu.com/images/swf/P1500D/P1500D.html . it should be here in 2 weeks; and then I can -- with harness holding the laptop on my chest -- walk around downtown Spokane Wa connected to the free wifi broadband and there are briefcase-sized batt`s to keep a walker`s costs down [@] http://www.lowes.com/lowes/lkn?action=productList&N=0&Ntk=i_products&Ntt=Garage%20Specialty%20Tools . even when tablets have a cheap screen that can't compete with the sun, walkables are convenient at libraries because I can easily touch-type my log while jumping between catalog and shelves -- I've already made one for my axim and it`s plug-in keyboard: I added straps and drawstrings to the clamshell of a spent palm keyboard . -- American Dream Documents http://www.geocities.com/amerdreamdocs/home/ "(real opportunity starts with real documentation) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mde at micah.elliott.name Fri Nov 18 17:45:02 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Fri, 18 Nov 2005 14:45:02 -0800 Subject: Adding through recursion In-Reply-To: References: <1132320167.127338.92460@g47g2000cwa.googlegroups.com> Message-ID: <20051118224502.GD9941@kitchen.client.attbi.com> On Nov 19, Ben Finney wrote: ... > This is just one of many reasons why I advocate always having a > *single* return statement, at the *end* of the function. Agreed that it's a good *general* practice, but sometimes early exit is useful and clear. This is somewhat of a religious topic. A good discussion is: http://c2.com/cgi/wiki?SingleFunctionExitPoint pychecker warns of fall-off-the-end functions. -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From ziga.seilnacht at gmail.com Tue Nov 1 18:20:40 2005 From: ziga.seilnacht at gmail.com (ziga.seilnacht at gmail.com) Date: 1 Nov 2005 15:20:40 -0800 Subject: Problems with emulation of numeric types and coercion rules Message-ID: <1130887240.155333.112920@o13g2000cwo.googlegroups.com> """ I am trying to write some classes representing the quaternion number. I wrote a base class, which implements only the numerical interface, and a few subclasses, which provide methods for their specific domain. Since the operator methods will be the same for all these classes, the base class operator methods don't explicitly return an instance of this base class, but rather an instance of the class that called them (ie 'return self.__class__(*args)' not 'return Quaternion(*args)') Documentation at http://docs.python.org/ref/coercion-rules.html says: Below, __op__() and __rop__() are used to signify the generic method names corresponding to an operator; __iop__() is used for the corresponding in-place operator. For example, for the operator `+', __add__() and __radd__() are used for the left and right variant of the binary operator, and __iadd__() for the in-place variant. For objects x and y, first x.__op__(y) is tried. If this is not implemented or returns NotImplemented, y.__rop__(x) is tried. If this is also not implemented or returns NotImplemented, a TypeError exception is raised. But see the following exception: Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class, the right operand's __rop__() method is tried before the left operand's __op__() method. This is done so that a subclass can completely override binary operators. Otherwise, the left operand's __op__ method would always accept the right operand: when an instance of a given class is expected, an instance of a subclass of that class is always acceptable. So I thought my plan would work. But it shows that even if the right operand is a subclass of left operand, its __rop__() method is called first _only_ when it overwrites the parent's method. If the method is inherited or just copied from its parent, the rule is ignored. Here is a simplified example: """ # file: number.py def convert(obj): if isinstance(obj, Number): return obj._value try: f = float(obj) except (TypeError, ValueError): return NotImplemented if f == obj: return f return NotImplemented class Number(object): def __init__(self, value=0.): value = float(value) self._value = value def __add__(self, other): """ Return sum of two real numbers. Returns an instance of self.__class__ so that subclasses would't have to overwrite this method when just extending the base class' interface. """ other = convert(other) if other is NotImplemented: return NotImplemented return self.__class__(self._value + other) __radd__ = __add__ # other methods class Broken(Number): pass class StillBroken(Number): __add__ = __radd__ = Number.__add__ class Working(Number): def __add__(self, other): return Number.__add__(self, other) __radd__ = __add__ __doc__ = \ """ If I now open the python interpreter:: >python Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from number import * >>> number = Number() >>> broken1 = Broken() >>> broken2 = StillBroken() >>> working = Working() When the subclass is on the left side of the operator, everything works as intended:: >>> print type(broken1 + number).__name__ Broken >>> print type(broken2 + number).__name__ StillBroken >>> print type(working + number).__name__ Working But when the sublass is on the right side of the operator, only the subclass that has owerwritten the operator method gets called first:: >>> print type(number + broken1).__name__ Number >>> print type(number + broken2).__name__ Number >>> print type(number + working).__name__ Working According to the coercion rule, the subclass should allways be called first. Is this a bug (either in documentation or in python), or should I stop trying to 'upcast' the return value? I did find a solution to this problem, but it isn't pretty and I'm not the only one using this method. Also if this is a bug could this mail be used as a bug report? Thanks in advance. Ziga """ if __name__ == '__main__': import doctest doctest.testmod() From mirandacascade at yahoo.com Sun Nov 20 14:23:07 2005 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 20 Nov 2005 11:23:07 -0800 Subject: PATH environment variable In-Reply-To: References: <1132451443.807757.251540@g43g2000cwa.googlegroups.com> <1132510146.835670.97990@o13g2000cwo.googlegroups.com> Message-ID: <1132514587.619457.134150@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > what part of your observations makes you think that the environment isn't "captured" (i.e. > copied from the process environment) when the os module is imported ? Answer: the part that was informed by a fundamental misunderstanding on my part of how the os module obtains information. Based on Mr. Lundh's 'copied from the process environment' remark and his hint, I would infer the following: 1) In the observations I detailed, the 'process' is the pythonwin application 2) When the pythonwin application is invoked, it obtains a copy of the current environment 3) the import os statement obtains information from the copy of the current environment that was obtained when the pythonwin process began 4) a reload(os) or a combination of del os followed by import os also get information from the copy of the current environment that was obtained when the pythonwin process began My questions: a) are the above inferences (albeit oversimplified) correct? b) when the hint refers to a new process, does the term 'process' refer to the same concept that is described in secion 6.1.5 of the Python Library Reference? From eternalsquire at comcast.net Wed Nov 16 16:25:50 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 16 Nov 2005 13:25:50 -0800 Subject: Python obfuscation In-Reply-To: <1132154202.424220.54450@g44g2000cwa.googlegroups.com> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> Message-ID: <1132176350.089366.55090@o13g2000cwo.googlegroups.com> >I'm asking coz i don't have any real world/industrial basis to better >understand the problem and factors involved when selling software - i'm >just a student A fair request. The teaching of legality and ethics of incorporating other peoples' works into one's own should begin at 6th grade and be repeated every year until the message is driven home. The concept of intellectual property (patent, copyright, trade secret) is an extension into the business world of issues regarding the proper usage of ideas (e.g. scientific principles) as treated in high school and college. >Do developers, when writing code consider how protected their >code will be when considering what language they will write it in >i.e ease of use, speed of language, maintainability and >'obfuscatability' ? Typically not due to a few well-known principles: 1) Essentially an optimized (not debug!) compilation from source code to machine language is nearly as good as encryption for hindering reverse engineering of the distributed code, 2) Network license servers residing on a seperate machine in the network apart from the executing software have become the method of choice for securing more valuable software, 3) User support and service is not an increasingly large component of the service provided by a software product, which can only be obtained through possession of a legal copy, 4) The time-to-market and obsolescense windows of software are continuing to decrease to the point where the time required to get around security is more expensive than the utility that software provides. Of course, all generally sweeping rules are false including this one, but those are the trends. All that being said: The greatest theft of sales opportunities resides in entertainment or gaming software. Little can be done to stop it except through repeated education at every grade level that copying without paying is as bad as plagiarism and just as dangerous to one's career in school. Ourselves and our children are lost generations with respect to ethics, manners, and respect for authority, perhaps we can train our grandchildren to behave more proprely. Productivity software is less so, the market is usually flooded with reverse engineered or lookalike competitors but brand name loyality usually wins out. Electronic Design Automation (EDA) software is rarely so, due to the huge need for customer support that is denied to an unregistered user. From apardon at forel.vub.ac.be Tue Nov 15 03:49:35 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 15 Nov 2005 08:49:35 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <86r79ji8lt.fsf@bhuda.mired.org> Message-ID: Op 2005-11-14, Mike Meyer schreef : > Antoon Pardon writes: >> Op 2005-11-10, Mike Meyer schreef : >>> [Context recovered from top posting.] >>> "bonono at gmail.com" writes: >>>> Daniel Crespo wrote: >>>>> Well, I hope that newcomers to Python don't confuse himselves :) >>>> This mutable/immutable object and name/variable is confusing. >>> Only if you have to overcome a conviction that variables behave in a >>> different way. If you've never seen them behave another way, or have >>> already gotten used to this model from another language (it dates back >>> to the 60s, if not the late 50s), then it's no problem. I'm sure the >>> problem exists in the opposite direction, except that few people >>> travel that route. >>> Most OO languages do the name/variable thing, but some of the popular >>> ones aren't consistent about it, giving some types "special" status, >>> so that sometimes "a = b" causes b to be copied onto a, and sometimes >>> it causes a to become a pointer to b. I find a consistent approach is >>> preferable. >> But what about a consistent approach, that allows choice. > > It's been done in other languages. But it requires more care than one > would think. That is possible. >> Like having an assignment operator (let use @= for it) next to a >> (re)bind operator. >> >> We could then have something like the following. >> >> a = 5 >> b = a >> a @= 7 >> b ==> would result in 7. > > You've just overwritten the object referred to by the token "5" in the > source code with the value 7, so you get: > > print 5 > 7 > > Not exactly a desirable outcome, but some language implementations > have allowed this kind of thing in the past. You either have to make > all objects mutable, or disallow assignment to immutable objects, > which sort of defeats the purpose. You have a valid point, but I think a different approach is possible. Don't make the distinction between mutable and immutable types but between mutable and immutable objects. So an int wouldn't be an immutable type, but 5 would be an immutable object. So the code above I gave would throw an exception, but the following might work. a @= 5 b = a b @= 7 a ==> would result in 7. > Another approach is to have a special object type if you want to allow > assignment to the object it refers to. That's what Python does now, it > just doesn't have a syntax just to support that. If it did, your > example might look like: > > a := 5 > b = @a > a := 7 > @b ==> would result in 7 Could it also work the other way? By somehow manipulating b change a? -- Antoon Pardon From samrobertsmith at gmail.com Tue Nov 22 00:43:41 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 21 Nov 2005 21:43:41 -0800 Subject: keys in dictionary Message-ID: <1d987df30511212143y2dc25acbl3d25d989a60cff16@mail.gmail.com> I run the following code and got wrong message, but I still want to make [1,2],[4,3] and [6,9] to be keys of the dictionary or change the style a little bit. How to do that? Thanks! >>> p=[[1,2],[4,3],[6,9]] >>> n=dict([(x,[]) for x in p]) Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable >>> From mwm at mired.org Tue Nov 29 18:27:55 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 29 Nov 2005 18:27:55 -0500 Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> Message-ID: <86u0dvowzo.fsf@bhuda.mired.org> Duncan Booth writes: > Dan Bishop wrote: >>> Is there any place in the language that still requires tuples instead >>> of sequences, except for use as dictionary keys? >> >> The % operator for strings. And in argument lists. >> >> def __setitem__(self, (row, column), value): >> ... >> > Don't forget the exception specification in a try..catch statement: > >> An object is compatible with an exception if it is either the object >> that identifies the exception, or (for exceptions that are classes) it >> is a base class of the exception, or it is a tuple containing an item >> that is compatible with the exception. > > Requiring a tuple here means that the code doesn't have to worry about a > possible recursive data structure. How so? except ExceptType1, (ExceptType2, ExceptType3, (ExceptType4, ExceptType5): I suspect this won't work, but meets the description. Lists could be used here with the same restrictions as tuples. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jjl at pobox.com Sun Nov 13 12:52:25 2005 From: jjl at pobox.com (John J. Lee) Date: 13 Nov 2005 17:52:25 +0000 Subject: IE Temporary Internet Files & Python References: <90DEA7ED93F71A4580CEDF76A02682EA03AD00@torexch.metrigenix.com> Message-ID: <873bm0e8py.fsf@pobox.com> "James Hu" writes: > Maybe the reason is ..\Content.IE5\index.dat can't be deleted! [...] IIRC, it can/could be from linux (with Win NT 4 installed on a VFAT partition), so I guess it is/was a normal file to that extent. John From duncan.booth at invalid.invalid Tue Nov 29 07:35:04 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Nov 2005 12:35:04 GMT Subject: Why I need to declare import as global in function References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> <1133265470.979764.157620@g14g2000cwa.googlegroups.com> Message-ID: wrote: > I have remarq that this problem is raised when I execute code in an > imported module (during importation) > > I think I will be able to isolate it and have a simple sample soon .... > Meanwhile, try adding: import math to the top of TU_05_tools.py. From sjmaster at gmail.com Sun Nov 6 15:29:52 2005 From: sjmaster at gmail.com (Steve M) Date: 6 Nov 2005 12:29:52 -0800 Subject: So, Which Version is Suitable for Beginners In-Reply-To: References: Message-ID: <1131308992.344182.14120@g44g2000cwa.googlegroups.com> There is a new gratis VMWare player at http://www.vmware.com/download/player/ You can download an image http://www.vmware.com/vmtn/vm/browserapp.html that they call a Browser Appliance, but if I remember correctly it is Ubuntu. From mde at micah.elliott.name Mon Nov 14 14:22:28 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Mon, 14 Nov 2005 11:22:28 -0800 Subject: replacing multiple instances of commas beginning at specific position In-Reply-To: <1131990237.288604.137690@z14g2000cwz.googlegroups.com> References: <1131990237.288604.137690@z14g2000cwz.googlegroups.com> Message-ID: <20051114192228.GD18475@kitchen.client.attbi.com> On Nov 14, striker wrote: > I have a comma delimited text file that has multiple instances of > multiple commas. Each file will contain approximatley 300 lines. > For example: > > one, two, three,,,,four,five,,,,six > one, two, three,four,,,,,,,,,,eighteen, and so on. > > There is one time when multiple commas are allowed. Just prior to > the letters ADMNSRC there should be one instance of 4 commas. ( > ,eight,,,,ADMNSRC,thirteen, ). The text ADMNSRC is NOT in the same > place on each line. > > What would be the best approach to replace all instances of multiple > commas with just one comma, except for the 4 commas prior to > ADMNSRC? One possible approach: #! /usr/bin/env python import re # This list simulates the actual opened file. infile = [ 'one, two, three,four,,,,,,ADMNSRC,,,,eighteen,', 'one, two, three,four,five,six' ] # Placeholder for resultant list. result = [] for item in infile: # Use a regex to just reduce *all* multi-commas to singles. item = re.sub(r',{2,}', r',', item) # Add back the desired commas for special case. item = item.replace('ADMNSRC', ',,,ADMNSRC') # Remove spaces?? item = item.replace(' ', '') # Add to resultant list. result.append(item) -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From robert.kern at gmail.com Sun Nov 13 00:46:02 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Nov 2005 21:46:02 -0800 Subject: circle and point In-Reply-To: <8c11e4350511122051hc4ae8b9tc4ef54818ba44318@mail.gmail.com> References: <8c11e4350511122051hc4ae8b9tc4ef54818ba44318@mail.gmail.com> Message-ID: Ben Bush wrote: > is there any code to decide whether a point is located within the circle > by three other points? # Converted from my C++ code. # C.f. http://www.ics.uci.edu/~eppstein/junkyard/circumcenter.html def circumcenter(x0, y0, x1, y1, x2, y2): x0m2 = x0 - x2 y1m2 = y1 - y2 x1m2 = x1 - x2 y0m2 = y0 - y2 x0p2 = x0 + x2 y1p2 = y1 + y2 x1p2 = x1 + x2 y0p2 = y0 + y2 D = x0m2*y1m2 - x1m2*y0m2 # You probably want to test for D being close to 0 here centerx = (((x0m2*x0p2 + y0m2*y0p2)/2*y1m2) - (x1m2*x1p2 + y1m2*y1p2)/2*y0m2) / D centery = (((x1m2*x1p2 + y1m2*y1p2)/2*x0m2) - (x0m2*x0p2 + y0m2*y0p2)/2*x1m2) / D return centerx, centery def incircle(x0, y0, x1, y1, x2, y2, x, y): centerx, centery = circumcenter(x0, y0, x1, y1, x2, y2) return ((x-centerx)**2 + (y-centery)**2 <= (x0-centerx)**2 + (y0-centery)**2) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at commonlawgov.org Sun Nov 13 08:29:00 2005 From: peter at commonlawgov.org (Peter) Date: Sun, 13 Nov 2005 05:29:00 -0800 Subject: How to avoid "f.close" (no parens) bug? In-Reply-To: References: Message-ID: <43773F9C.4080009@commonlawgov.org> o wrote: > plez send me > > First off, please explain what you are talking about better next time. Second, What on earth are you talking about? "f" is a file object, correct? Are you trying to close a file by typing f.close or is the file closing when you type f.close? If you are trying to close a file with f.close without parenthasies, then i _realy_ hope that this did not work, as f.close is nothing but a class method and should be treated like one except when called. You may want to check out the Python tutorial at python.org http://docs.python.org/tut/tut.html HTH, Peter From pythonnew at gmail.com Tue Nov 22 11:02:20 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 22 Nov 2005 08:02:20 -0800 Subject: the first element in the list of list In-Reply-To: References: <8c11e4350511220636p59b22d63pced73232aed06379@mail.gmail.com> Message-ID: <8c11e4350511220802o3de6724dh72a01faea86fc6d4@mail.gmail.com> On 11/22/05, Fredrik Lundh wrote: > Ben Bush wrote: > > > I have a lis: > > [[1,3],[3,4],[5,6],[8,9],[14,0],[15,8]] > > I want a code to test when the difference between the first element in > > the list of list is equal to or larger than 6, then move the previous > > lists to the end of the list. that is: > > [[14,0],[15,8],[1,3],[3,4],[5,6],[8,9]] > > have you tried doing this yourself? how far did you get? can you > post the code so we can help you figure out what you need to fix? > is this a homework assignment? > > here's a oneliner: > > L = [x for x in L if x[0]-x[1] >= 6] + [x for x in L if x[0]-x[1] < 6] > > depending on how you define "difference", you may need to replace > x[0]-x[1] with abs(x[0]-x[1]) Thanks! it works! This question just came to my mind and not assigned by anyone. I did not know '+' can be used to link the tow lists. By the way, where i can find more information about how to use List and data structure in Python. really amazed by its use! From pwatson at redlinepy.com Sun Nov 20 22:08:01 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 20 Nov 2005 21:08:01 -0600 Subject: Web-based client code execution In-Reply-To: <1132402656.285350.146460@z14g2000cwz.googlegroups.com> References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> <1132402656.285350.146460@z14g2000cwz.googlegroups.com> Message-ID: <43813A11.6090606@redlinepy.com> David Wahler wrote: > Steve wrote: > >>AJAX works because browsers can execute javascript. I don't know of a >>browser that can execute python. Basically your stuck with java or >>javascript because everything else really isn't cross platform > > > Don't jump to conclusions... > http://dwahler.ky/python/ > > If you really, really want Python in a browser, it's certainly > possible. :) > > -- David This looks interesting, but looks even more fragile than CrackAJAX. http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework All of this comes down to Javascript which will still not allow me to read local, client files. Right? From SSchukat at dspace.de Mon Nov 7 11:29:39 2005 From: SSchukat at dspace.de (Stefan Schukat) Date: Mon, 7 Nov 2005 17:29:39 +0100 Subject: Python, COM Servers, and Multi-Threading Message-ID: Hi, you get best performance if you make your servers local servers, since then every interpreter runs in ist own process. If you make it an inproc server you synchronize all threads/CPUs with the GIL. Even better multithreading support you will get if you mark your server to run in an multithreaded apartment (MTA). e.g. class COMClass: _public_methods_ = [ 'Method', ... ] _reg_verprogid_ = "COMServer.COMClass.1" _reg_progid_ = "COMServer.COMClass" _reg_desc_ = "COMServer COMClass" _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}" _reg_class_spec_ = "win32com.servers.COMServer.COMClass" _reg_threading_ = "free" # <--- Threading model _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER # <-- own exe Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of Carl Waldbieser > Sent: Tuesday, October 11, 2005 12:46 AM > To: python-list at python.org > Subject: Python, COM Servers, and Multi-Threading > > I have been considering using Python and the Reportlab > library for generating PDF reports for the back-end of a web > based application. The application runs most of its > background tasks on a dedicated server that is Windows based > (Win2K or Win2k3). The program that launches the tasks > requires a COM-based interface, so I wrote a Python COM > server using Mark Hammond's PythonCom libraries and import > and run the reporlab modules from there. > > I had been reading up on Python and it's handling of the > multiple threads, specifically the Global Interpreter Lock > (GIL). I got to wondering if a multi-processor machine > machine would be able to take advantage of its extra > processing power using this setup. I am guessing that the > GIL is global with respect to each instance of a running > Python interpreter, so if say 4 interpreters were running, a > 4 processor machine would be able to take advantage of this. > However, I am not quite sure how launching my reports via COM > behaves-- if I launched 4 reports this way, would that be > like launching 4 seperate instances of the Python > interpreter, or would it be just a single instance, and > therefore run into the limitations of the GIL? If so, can > anybody offer suggestions as to a design that would be better > able to take advantage of a multi-processor machine? > > Thanks, > Carl Waldbieser > > -- > http://mail.python.org/mailman/listinfo/python-list > From jaywgraves at gmail.com Tue Nov 29 17:42:38 2005 From: jaywgraves at gmail.com (jay graves) Date: 29 Nov 2005 14:42:38 -0800 Subject: xpath support in python 2.4 References: <1133278253.523473.110800@g49g2000cwa.googlegroups.com> Message-ID: <1133304158.672327.120480@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > sounds like you've installed > http://pyxml.sourceforge.net/ > on one of your machines, but not on the other. or ActiveState Python on one and python.org Python on the other??? Just a guess. No STFWing was done before posting this message. ;-) From getkaizer at gmail.com Wed Nov 30 05:37:05 2005 From: getkaizer at gmail.com (Kaizer) Date: 30 Nov 2005 02:37:05 -0800 Subject: Newbie question: Getting "unstaisfied" error while installing scipy Message-ID: <1133347025.226160.38810@g14g2000cwa.googlegroups.com> Hello! I'm trying to install scipy_core_0.6.1-1.i586 on my Mandrake Linux (via RPM) 10.2 machine. I double click on the rpm icon but it gives the following error... scipy_core_0.6.1-1.i586 failed due to unstaisfied libg2c.so.0 What do i do?? I know this query is not directly related to Python.. but i'd appreciate your inputs Thanks in advance, Have a great day From mwm at mired.org Thu Nov 3 11:26:59 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 03 Nov 2005 11:26:59 -0500 Subject: Getting a function name from string References: <436943e0$0$2083$edfadb0f@dtext02.news.tele.dk> <86vezabnv9.fsf@bhuda.mired.org> <4369b966.1683182818@news.oz.net> Message-ID: <86zmolitnw.fsf@bhuda.mired.org> bokr at oz.net (Bengt Richter) writes: >>For a lot of uses, it'd be better to build the dictionary by hand >>rather than relying on one of the tools that turns a namespace into a >>dictionary. > IMO it would be nice if name lookup were as cleanly > controllable and defined as attribute/method lookup. > Is it a topic for py3k? I'm not sure what you mean by "cleanly controllable and defined". I'd say name lookup is well defined and clean, as it's the same as it is in pretty much any language that supports nested scopes, modulo assignment creating things in the local scope. If you're talking about letting users control that mechanism, that's definitely py3k material, if not "python-like-language-that's-not-python" material. On the other hand, if you just want to provide tools that let users do name lookups the way they can do attribute lookups, that's easy, and we could add that now: getname(name) - returns the object name is bound to. setname(name, value) - binds the variable name. And maybe you want an optional third argument of a callable, which causes the functions to work on names starting in the callables name space. The real question is (as always) - what's the use case? In particular, what's the use case that we really want to encourage? As I said, you're usually better off separating dynamically built names into their own dictionary rather than trying to plug them into - or pull them out of - one of the language namespaces. If you plug them in, there's no way to get them back out except by mechanisms similar to how you got them in, so you might as well let those mechanisms include a dictionary. If you pull it out, you might as well have referenced the bare name rather than the string. If you constructed the name in some way, then changing the constructor to do a dictionary lookup should be straightforward. All of these technics avoid problems that come from overloading a language namespace. Of course, I'm not omniscient, so you may have something that doesn't fit those cases in mind - in which case, let's hear about it. You can even arrange to run python code with your dictionary as a namespace. Following are excerpts from a tool I'm currently not working on. class P: def __init__(self): self.variables = dict(In = self.set_input, Out = self.set_output, Labels = self.set_labels, Float = DoubleVar, String = StringVar, Int = IntVar) def calculate(self): for name, var in self.inputs.items(): self.variables[name] = var.get() self.variables['calculate']() for name, var in self.outputs.items(): var.set(self.variables[name]) def run(self): self.app.mainloop(self.calculate) def main(args): app = P() execfile(argv[1], app.variables) app.run() Here I create a dictionnary - P().variables - and populate it with names and their values. I then run the code of interest with that dictionary as the global namespace. The code will add things to the namespace - in particular, "calculate". I then run a loop which will, at unspecified times, set names in the P().variables dictionary, run the "calculate" callable created by the code of interest, then copy values out of the dictionary. This works ilke a charm. If you don't want to deal with entire files, you can use exec, or even eval if you just want to get a value back. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From andrea_gavana at tin.it Tue Nov 22 14:33:34 2005 From: andrea_gavana at tin.it (Andrea Gavana) Date: Tue, 22 Nov 2005 20:33:34 +0100 Subject: wxPython Licence vs GPL References: Message-ID: <43837289$0$27610$4fafbaef@reader1.news.tin.it> Hello John & Sarah, > (This assumes the wxPython Licence is compatible with the GPL -- if not, > do we just cosmetically change any remaining lines, so none remain from > the orignal?) IIRC, wxPython license has nothing to do with GPL. Its license is far more "free" than GPL is. If you want to create commercial apps with wxPython, you can do it without messing with licenses. With GPL code is somewhat harder. I am not an expert but someone has suggested me to change my widgets' license from GPL to "LGPL with exceptions", that means wxWidgets/wxPython license, in order to include those widgets inside his applications. Sorry if that does not help a lot. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77 From aleax at mail.comcast.net Fri Nov 4 00:34:22 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 21:34:22 -0800 Subject: Can Anyone Help me on this References: Message-ID: <1h5gzpu.12vbiw59vgyrfN%aleax@mail.comcast.net> blah at blah.blah wrote: > Thanks Guys, Wow, i didnt knew that there was alist reverse function. > thx. also. i need a good documentation of the os and sys modules as > well as builtin functions of python. > > the standard python documentation doesnt work for me. can u recommend > something? I'm biased, but I'd recommend the book "Python in a Nutshell". My suggestion: take advantage of the "Safari" online library for 2 weeks' of free subscription -- make sure you cancel after 13 days if you want to avoid being billed for the subscription's fee. In those 2 weeks you get to read for free a few books in the online library -- I'd suggest sampling the Nutshell, the Cookbook and possibly a couple more... Alex From mwm at mired.org Wed Nov 30 15:15:09 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 15:15:09 -0500 Subject: General question about Python design goals References: <86k6estfkd.fsf@bhuda.mired.org> <7xu0du64zo.fsf@ruckus.brouhaha.com> <86psoiodat.fsf@bhuda.mired.org> <7xhd9u63bv.fsf@ruckus.brouhaha.com> Message-ID: <86iru9opte.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> > An awful lot of the time in this newsgroup, "practicality beats >> > purity" translates as "the programmer can just be a lazy slob". >> You post that as if it were a bad thing. > Yes. The idea of using a program that someone else wrote, is that > they do the work so I don't have to. If their doing less work means > that I have to do more, the program isn't as good as it might be. No, it's not as good *for your purpose* as it might be. But they didn't write it for your purpose, they wrote it for theirs. The latter is really the only standard of judgement. > A program like Python intended for wide distribution and use by large > numbers of people whose needs aren't known in advance, should do as > much to help its users as development resources allow. True. You seem to disagree about how they choose to allocate the resources. The fix for that is well-known. > Are you familiar with R. Gabriel's piece "Worse is better"? That's > not what I see "practicality beats purity" as being intended to mean. Why not? That seems to summarise a couple of the points in the more successful design philosophy, most notably: The design most not be overly inconsistent. The design must cover as many important situations as is practical. If these don't reflet what you think "Practicality beats purity" means, then what do you think it means? Actually, I've been thinking about that bit recently, and noting that a number of things from "import this" seem to espouse the more successful approach from that section: Simple is better than complex. Complex is better than complicated. Special cases aren't special enough to break the rules. Although practicality beats purity. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. >> > If following POLA costs that much, at least in the kinds of examples >> > we talk about all the time here, something is probably wrong with the >> > implementation (or the design) to begin with. >> True, but not constructive. Knowing that something is wrong is >> easy. Diagnosing the problem is harder. Curing it is even harder. > Look at the list.count() example at the start of this thread. > Diagnosing it isn't hard. Curing it isn't hard. It doesn't bloat > Python by an order of magnitude. Did somebody actually use "Practicality beats purity" as an excuse for not making list.count and string.count have the same arguments? If so, I missed it. I certainly don't agree with that - count ought to work right in this case. > A suitably factored implementation might handle lists and strings > with the exact same code and not incur any extra cost at all. That > type of thing happens all the time here. If it happens all the time, you shouldn't have any trouble nameing a number of things that a majority of users think are misfeatures that aren't being fixed. Could you do that? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Fri Nov 25 03:16:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Nov 2005 08:16:04 +0000 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: References: <1132772142.500020.16360@g44g2000cwa.googlegroups.com> <1132782865.993175.92340@g43g2000cwa.googlegroups.com> Message-ID: Magnus Lycka wrote: > bonono at gmail.com wrote: > >>Oh, find a need to shut other up ? >> > > Oh, find a need to get the last word? > > /Magnus > > P.S. Yes, this *is* a test. Looks like you hooked him, Magnus ;-) -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From thakadu at gmail.com Mon Nov 21 17:16:41 2005 From: thakadu at gmail.com (thakadu) Date: 21 Nov 2005 14:16:41 -0800 Subject: bsddb185 question Message-ID: <1132611401.426797.143120@g47g2000cwa.googlegroups.com> I have an application that needs to create and delete records in a Berkeley DB version 1.85 database. If I use the bsdddb185 module I dont see any of the record manipulation methods in there that are available in the newer bsddb module. (put(), get(), pop() etc) I know the docs say that one should always use the newer bsddb module however it appears that the bsddb module is unable to open version 1.85 databases. So it seems I am forced to use the bsddb185 module which does not have convenient record level methods. Am I missing something here or have others eperienced tha same? From kxroberto at googlemail.com Fri Nov 4 13:21:47 2005 From: kxroberto at googlemail.com (Robert) Date: 4 Nov 2005 10:21:47 -0800 Subject: Monster python24.dll / stripping off asian codecs to separate package(s) ? Message-ID: <1131128507.202717.252620@g47g2000cwa.googlegroups.com> Martin v. L?wis schrieb: > Robert wrote: > > Wouldn't it be an issue to think about if future win-python distributions > > should keep on including the asian codecs in the main-dll? > > Indeed, it would. As I said before: if somebody defines a clear, fair > policy which finds agreement in the community, I'm willing to change the > current policy on what goes into python24.dll, and what is built > separately. Bonus points if the policy is accompanied with a patch. > The policy should not be static, i.e. it should also give a guideline > for modules introduced in the future. > At the moment, the policy is this: "everything that does not depend on > an external library should go into pythonXY.dll". As a result of this reducing the big python24.dll is still a tangling issue: keeping up with new python versions. creating an installer or copying files around. unsecurty, if the compiler is error free ... for me the big DLL size is the only reason to rebuild python. Guess there are more people suffering from the doubled size of python24.dll vs python23.dll I guess there is no good mathematical policy. But maybe a practical one (as pythons policy is practicability - not to be a LISP): the size of the libraries. 'd perfectly happy if the asian codecs are out. A practical policy: respect size + usage frequency : For future independent libs: Check their size. If they they are monsters, check if the lib is used in more than 80% of applications. if not, keep monster libs sparately, as they blow up installers and memory usage. Robert From sybrenUSE at YOURthirdtower.com.imagination Fri Nov 11 08:42:51 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 11 Nov 2005 14:42:51 +0100 Subject: creating single-instance executables using python/py2exe References: Message-ID: Satchidanand Haridas enlightened us with: > a new instance is created when I double click on two different > files. Is there a way in which I can make sure only one instance is > created? You could open a listening socket to listen for "open file" commands. If opening that socket fails (address already in use), connect a client socket to it, send the appropriate "open file" command, and exit. That way, you even have a cross-platform solution. 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 python-url at phaseit.net Sun Nov 6 12:53:36 2005 From: python-url at phaseit.net (Cameron Laird) Date: Sun, 06 Nov 2005 17:53:36 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 6) Message-ID: QOTW: "- don't use SAX unless your document is huge - don't use DOM unless someone is putting a gun to your head" - Istvan Albert "I wouldn't fret too much about a sharp remark from Fredrik Lundh. They're pretty much all that way. ;) It looks like you already did the right thing - read past the insults, and gleaned the useful information that he included in between. It takes a little training to get used to him, but if you can look past the nasty bite, he's really a valuable resource." - Steven Bethard Alex Martelli and Bengt Richter rely on the galilean property and set function to compute whether a list is duplicate-free: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4b1da706b9f9e622/ You needn't just pine for syntax from other languages missing in Python, such as Perl's "start..end"; if you're Peter Otten, you can add it to Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/506412e06dfea965/ Python as podcast! You might have *thought* you knew about the language, but it's a big Python world. http://www.awaretek.com/python/index.html Similarly, yes, Python can do what strtok() does in C, although it's expressed more readably: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5e71a1da4f5934dc/ Larry Bates demonstrates how simple use of ConfigParser can be: http://groups.google.com/group/comp.lang.python/browse_thread/thread/321ec0512ed8c926/ With the new-style object model, type() is a stylish indirection: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f0fbfae9a69580a3/ Enthusiastic Alex accuses Van Roy and Hariri of having written the 21st century SICP, and more. Much more. With references. Yet he (and Magnus Lycka and others) remain faithful: http://groups.google.com/group/comp.lang.python/browse_thread/thread/77c2035ee4150c11/ Python's a great general-purpose language. It can address storage devices directly: http://groups.google.com/group/comp.os.linux.misc/browse_thread/thread/28eb92576280d3f0/ it can operate at high level, and 'most everything in between. ======================================================================== 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/topics/pythonurl/ (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 mensanator at aol.com Fri Nov 11 21:14:28 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 11 Nov 2005 18:14:28 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> <1131517112.247477.35030@g14g2000cwa.googlegroups.com> <1h5rxho.nxmo0z15zne5jN%aleax@mail.comcast.net> <1h5su7m.vwmk96qm9qplN%aleax@mail.comcast.net> <1131690799.409160.36930@g49g2000cwa.googlegroups.com> <1h5up32.1fa670mkz6a6bN%aleax@mail.comcast.net> Message-ID: <1131761668.269236.151100@g43g2000cwa.googlegroups.com> Alex Martelli wrote: > wrote: > > > I've created Windows binaries for Python 2.3 and 2.4. It should be > > compatible with PentiumPro or later processors. > > Thanks! I hope to package up a release early next week, and to include > these. > > > Alex I downloaded the binaries and ran some Big Arithmetic tests: First, I wanted to see how version 1.0 handled the test which is a typical problem for which I use gmpy. A Type [1,2] Mersenne Hailstone is an object I encounter in my Collatz Conjecture research. There are an infinite number of them. Every 9th (starting from the 5th) generation 1 hailstone is a generation 2 hailstone. Every 9th (starting from the 5th) generation 2 hailstone is a generation 3 hailstone, etc. In this case, a closed form equation can be used to directly find the ith member of the kth generation. But not all hailstone types have closed form equations. For those, I use a recursive function that uses divm(). The test makes three passes. The first is a brute force search through every Mesenne Number from 1 to 177150 bits. A test determines what generation each is (most are not Type [1,2] and evaluate to generation 0). The test prints the first occurrence of each generation. The second pass uses the closed form equation to directly calculate the 1st member of each generation. These results must match those found in the brute force search. Finally, the third pass takes each hailstone found in the second pass, calculates it's absolute offset from the first general Type [1,2] hailstone of the corresponding generation, and calls the recursive function to see if it calculates the same hailstone found in pass 2 and pass 1. ========================================== gmpy.version: 1.0 (with divm() replaced by invert()) Brute force search: gclass(2**i-1,xyz) Find 1st Generation k Type [1,2] Mersenne Hailstone 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 7.031 seconds Closed form: Type12MH(k,i) Find ith, kth Generation Type [1,2] Mersenne Hailstone using the closed form equation 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 0.657 seconds Verify Type12MH Hailstones: Find ith, kth Generation Type (xyz) Hailstone using the recursive equation (gmpy.divm(y**(k-1)-prev_gen[2],y-x,y**(k-1))/y**(k-2))*y**(k-1)+prev_gen[3] where i=((hailstone-geni(k,1,xyz))/(y**k))+1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 0.078 seconds ========================================== NOTE: Brute force search could not reach generation 6 without locking up Switching to gmpy version 1.01 ========================================== gmpy.version: 1.01 (now using divm()) Brute force search: gclass(2**i-1,xyz) Find 1st Generation k Type [1,2] Mersenne Hailstone 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 0.579 seconds Closed form: Type12MH(k,i) Find ith, kth Generation Type [1,2] Mersenne Hailstone using the closed form equation 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 0 seconds Verify Type12MH Hailstones: Find ith, kth Generation Type (xyz) Hailstone using the recursive equation (gmpy.divm(y**(k-1)-prev_gen[2],y-x,y**(k-1))/y**(k-2))*y**(k-1)+prev_gen[3] where i=((hailstone-geni(k,1,xyz))/(y**k))+1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 0.015 seconds ========================================== NOTE: Wow, what an improvement! How far can I go now? ========================================== gmpy.version: 1.01 Brute force search: gclass(2**i-1,xyz) Find 1st Generation k Type [1,2] Mersenne Hailstone 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 31.92 seconds Closed form: Type12MH(k,i) Find ith, kth Generation Type [1,2] Mersenne Hailstone using the closed form equation 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 0.234 seconds Verify Type12MH Hailstones: Find ith, kth Generation Type (xyz) Hailstone using the recursive equation (gmpy.divm(y**(k-1)-prev_gen[2],y-x,y**(k-1))/y**(k-2))*y**(k-1)+prev_gen[3] where i=((hailstone-geni(k,1,xyz))/(y**k))+1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 8.766 seconds ========================================== NOTE: Brute force can now reach generation 6, but won't try anything higher. Generation 9 is a 129 million bit number! Can we get to generation 10? ========================================== gmpy.version: 1.01 Brute force search: gclass(2**i-1,xyz) Find 1st Generation k Type [1,2] Mersenne Hailstone 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 32.14 seconds Closed form: Type12MH(k,i) Find ith, kth Generation Type [1,2] Mersenne Hailstone using the closed form equation 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 2**1162261469-1 generation:10 51.83 seconds Verify Type12MH Hailstones: Find ith, kth Generation Type (xyz) Hailstone using the recursive equation (gmpy.divm(y**(k-1)-prev_gen[2],y-x,y**(k-1))/y**(k-2))*y**(k-1)+prev_gen[3] where i=((hailstone-geni(k,1,xyz))/(y**k))+1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 Traceback (most recent call last): File "C:\Python23\user\gmpy ver 1.01\MHtest.py", line 64, in ? i = (h-a0)/(xyz[1]**g) ========================================== NOTE: No, ran out of virtual memory. Probably due to the recursion and having to store the pass 2 numbers. I used to have a sign in my lab saying "Test to Destruction" But the paranoid schizophrenic field engineer got freaked out by it and the boss made me take it down. ========================================== Excellent work guys! Not only is the divm() bug fixed but it looks like we got a significant performance increase. From cito at online.de Fri Nov 25 15:46:38 2005 From: cito at online.de (Christoph Zwerschke) Date: Fri, 25 Nov 2005 21:46:38 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> Message-ID: It seems everybody is in full agreement here. I have the same mixed feeling about letting keys/values/items become both managed list attributes and still returning copies of the lists when called in the usual way as methods. I don't know any precedent for doing things that way and i'm unsure whether it meets the Zen of Python. But anyway the idea is nice enough to try it out. -- Chris From anton.vredegoor at gmail.com Sun Nov 20 09:49:27 2005 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: 20 Nov 2005 06:49:27 -0800 Subject: Python obfuscation In-Reply-To: <1h69rhd.a4a8g3p83u9jN%aleax@mail.comcast.net> References: <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> <1132249511.886027.93990@g14g2000cwa.googlegroups.com> <1h662eo.95qjyvd1bcnuN%aleax@mail.comcast.net> <437d0b86.63834689@news.oz.net> <1132325798.806457.91170@g47g2000cwa.googlegroups.com> <1h67rkl.1rkx0mm1hpdql9N%aleax@mail.comcast.net> <1132406038.650352.323390@g14g2000cwa.googlegroups.com> <1h69rhd.a4a8g3p83u9jN%aleax@mail.comcast.net> Message-ID: <1132498167.619516.188540@g43g2000cwa.googlegroups.com> Alex Martelli wrote: > Anton Vredegoor wrote: > ... > > Suppose I grant all your theories about optimal marketing strategies. I wish I hadn't done that :-) But seriously, I'm having trouble answering in detail all of your points (which doesn't mean I don't value them highly) because my online time is limited by the time period this library is open, and I also want to scavange as much offline reading material as possible while I'm connected. > > This still doesn't account for the way the market is behaving *now*. It > > isn't in any way logical or optimal. For example in Holland (where I > > live) complete governmental departments are dedicated to make life > > What makes you think that governmental departments are part of the > *market*?! Government behavior is controlled by laws that are vastly > different from those controlling market behavior; if you're interested, > you could study the "theory of public choice". I don't think so, so the question can't be answered. It's the same logic that enabled me to say "payed webservices can only work well if" when in context of replacing obfuscation techniques. From 1+1 == 3 I can derive anything. I know its lame, but my time limitation forces me to go back (or up) one level in order to refute you. > > You seem to tackle the problem of python obfuscation by first proving > > that it isn't feasible and then giving some kind of solution that will > > work and give the desired result: webservices. However when I look at > > That seems to me to be a practicable technical approach, yes. > > > obfuscation techniques I see a desire to profit from giving some person > > the idea that he or she is superior to someone else because he has a > > better product. In order to avoid copying we now need obfuscation. The > > You're discussing the *motivation* for obfuscating, while what I was > giving was a possible way of *implementing* similar effects. Yes, that's the point. If you can produce at zero cost then the whole economic theory falters. You enter another continuum where traditional economic values become meaningless. From obfuscation to webservices is a big step in that direction. > Since redistribution of value, as long as a lot of value is created, can > be dealt with by other means, maximizing the creation of value tends to > be the goal I prefer -- a policy that quashes part or all of value > creation based on redistributive precepts is, by this very fact, going > to be something I look askance at (making the pie smaller to try to > ensure that what little is left gets sliced according to your political > preferences, rather than ensuring the pie is as big as possible as the > first order of business, and dealing with the slicing issues as > _secondary_ ones). I agree with your sentiment, but in order to maximize value creation we should leave material payments out of the equation when they only slow things down. From your writing I gather you already live in those quarters but you are still using materialistic concepts to describe the world. I don't blame you for it because I wouldn't know myself what would be applicable to a zero cost - maximal gain economy. Anton From ms at cerenity.org Wed Nov 9 12:37:05 2005 From: ms at cerenity.org (Michael) Date: Wed, 09 Nov 2005 17:37:05 +0000 Subject: [OT] Map of email origins to Python list References: Message-ID: <43724f6f$0$82665$ed2619ec@ptn-nntp-reader03.plus.net> Paul McGuire wrote: > "Claire McLister" wrote in message > news:mailman.221.1131384118.18701.python-list at python.org... > We've been working with Google Maps, and have created a web service to > map origins of emails to a group. As a trial, we've developed a map of > emails to this group at: > > http://www.zeesource.net/maps/map.do?group=668 > > This represents emails sent to the group since October 27. > > Would like to hear what you think of it. > ------------------------------ > > > Another sleepless camera pointed at the fishbowl that is my online life. > > I guess it's a great way to find where there might be Python jobs to be > found, or at least kindred souls (or dissident Python posters in countries > where Internet activity is closely monitored...) > > To me, it's either cool in a creepy sort of way, or creepy in a cool sort > of way. As long as it gets my location WRONG, I'm happy. :-| Michael. From steven.bethard at gmail.com Thu Nov 17 23:56:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Nov 2005 21:56:38 -0700 Subject: textwrap.dedent() drops tabs - bug or feature? Message-ID: So I've recently been making pretty frequent use of textwrap.dedent() to allow me to use triple-quoted strings at indented levels of code without getting the extra spaces prefixed to each line. I discovered today that not only does textwrap.dedent() strip any leading spaces, but it also substitutes any internal tabs with spaces. For example:: py> def test(): ... x = ('abcd efgh\n' ... 'ijkl mnop\n') ... y = textwrap.dedent('''\ ... abcd efgh ... ijkl mnop ... ''') ... return x, y ... py> test() ('abcd\tefgh\nijkl\tmnop\n', 'abcd efgh\nijkl mnop\n') Note that even though the tabs are internal, they are still removed by textwrap.dedent(). The documentation[1] says: """ dedent(text) Remove any whitespace that can be uniformly removed from the left of every line in text. This is typically used to make triple-quoted strings line up with the left edge of screen/whatever, while still presenting it in the source code in indented form. """ So it looks to me like even if this is a "feature" it is undocumented. I'm planning on filing a bug report, but I wanted to check here first in case I'm just smoking something. STeVe [1] http://docs.python.org/lib/module-textwrap.html From mardy at users.sourceforge.net Mon Nov 21 13:05:29 2005 From: mardy at users.sourceforge.net (Mardy) Date: Mon, 21 Nov 2005 18:05:29 GMT Subject: Advice on distutils and distribution policies Message-ID: Hi, I've built a small project (http://eligante.sf.net) which I'm actually trying to package using distutils. The directory structure is going to be like this: eligante/ eligante.py sitobase.py personas.py [...other python files...] modulos/ mbox.py gaim.py [...other python files...] web/ indice.py cerca.py [...other python files...] stylo.css testata.html [and maybe, in the future, other HTML files] The python files in the eligante/web directory are intended to be called by a webserver (now Apache, but soon I'll switch to the python module CGIHTTPServer for simplicity) as CGIs. Currently, these CGIs read the testata.html file and use it as the beginning of their output, while the style.css is served by the HTTP server. However, I don't know if this directory layout is suitable for site-packages, since at a first glance it looks to me that datafiles might not be welcome under it. Is it so? In that case, where should I move the .html files, and how should I access them from inside python? If, on the other hand, this layout is OK for site-packages, how do I instruct distutils to put the .html and .css files under the eligante/web directory? Sorry for the long post, and thanks in advance for any help or suggestion. -- Saluti, Mardy http://interlingua.altervista.org From jparlar at cogeco.ca Sat Nov 5 11:02:43 2005 From: jparlar at cogeco.ca (Jay Parlar) Date: Sat, 5 Nov 2005 08:02:43 -0800 Subject: python gc performance in large apps In-Reply-To: References: Message-ID: You may also want to look at the following Summer of Code project: http://pysizer.8325.org/ Their SVN repo is at http://codespeak.net/svn/user/nick8325/sizer/ I haven't had a chance to try it yet, but it might be exactly what you need. The project is described as "PySizer is a library for measuring memory use of Python code" Jay P. From ex_ottoyuhr at hotmail.com Wed Nov 30 22:46:58 2005 From: ex_ottoyuhr at hotmail.com (ex_ottoyuhr) Date: 30 Nov 2005 19:46:58 -0800 Subject: Recursion bug... In-Reply-To: <1133407543.433860.160960@g44g2000cwa.googlegroups.com> References: <1133405155.154823.134620@g47g2000cwa.googlegroups.com> <1133407543.433860.160960@g44g2000cwa.googlegroups.com> Message-ID: <1133408818.214418.208010@g44g2000cwa.googlegroups.com> bonono at gmail.com wrote: > ex_ottoyuhr wrote: > > class TreeCommand: > > opcode = 0 > > children = [] > > def __init__(self, anOpcode) : > > opcode = anOpcode > > > opcode and children in this case is more like "class" variable in C++. > If you want "instance" variable, you need to do it as self.opcode, > self.children, in all methods. Thanks a lot. I'm sorry to have bothered you and the newsgroup with such a simple problem, but then again, I'm glad it was simple, and I suppose that's what newsgroups are for... :) From max at alcyone.com Mon Nov 21 01:07:42 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Nov 2005 22:07:42 -0800 Subject: best cumulative sum In-Reply-To: References: <9Qbgf.8204$BC2.5713@trnddc04> Message-ID: Micah Elliott wrote: > On Nov 21, David Isaac wrote: > >> What's the good way to produce a cumulative sum? > >>>> import operator >>>> x = 1,2,3 >>>> reduce(operator.add, x) > 6 Or just sum(x). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Never contend with a man who has nothing to lose. -- Baltasar Gracian From lycka at carmen.se Thu Nov 24 10:38:06 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 24 Nov 2005 16:38:06 +0100 Subject: Writing big XML files where beginning depends on end. In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > what's the typical overall structure for this tree ? is it short and wide, or tall and > narrow ? That varies quite a bit. It's basically a call graph for a functional language, where also aggregated results are stored in the XML tree. In other words, the shape depends on the program we're analyzing. With a loop in the top level, we could get plenty of nodes in the root, but we need to handle different cases. Typically, the language in question isn't used to build very complex things, so this hasn't really been an issue before... I tried to look at a 100MB xml file in a browser, to see the shape, but Mozilla died after growing to several GB in size... From duncan.booth at invalid.invalid Wed Nov 16 03:48:15 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Nov 2005 08:48:15 GMT Subject: Shutdown hook References: <1132094726.985460.97110@g14g2000cwa.googlegroups.com> Message-ID: Lawrence Oluyede wrote: > Il 2005-11-15, Ben Finney ha > scritto: >> Steve wrote: >>> Does any one know if python has the ability to run a shutdown hook. >> >> When the Python runtime system wants to exit, it raises a SystemExit >> exception. >> >> Catch that exception at the top level of your code, and do whatever >> you like. (It might be polite to actually exit at some point, of >> course. sys.exit(exitcode) will do so -- raising another SystemExit >> exception.) >> > > I think using atexit module - > http://docs.python.org/lib/module-atexit.html is cleaner > Correct, although this won't catch all cases where a program is exiting. For example, on Windows, if you use Ctrl+C to terminate a program the atexit function *is* called, but if you use Ctrl+Break the atexit function is not called unless you install a suitable signal handler: import signal def sigbreak(signum, frame): sys.exit("***break") signal.signal(signal.SIGBREAK, sigbreak) Even then there are still other ways to terminate a process which will not be caught. From samrobertsmith at gmail.com Thu Nov 17 19:10:27 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Thu, 17 Nov 2005 16:10:27 -0800 Subject: Tkinter's coordinates setting In-Reply-To: <56190b6c0511171432y578a6d88qe6b5ff69b4b19443@mail.gmail.com> References: <8c11e4350511171233t5c984a13ua88fd71634fdaeff@mail.gmail.com> <56190b6c0511171432y578a6d88qe6b5ff69b4b19443@mail.gmail.com> Message-ID: <1d987df30511171610l7942831cs7f76a690329e91a8@mail.gmail.com> On 11/17/05, Steve Juranich wrote: > On 11/17/05, Ben Bush wrote: > > Tkinter's coordinates setting are: the left upper corner is the smallest X > > and Y, which is different from our usual think that Y is largest in that > > location. If i draw some lines on the canvas and show some relationship > > among them, do I need transfer the coordinates? > > Transfer the coordinates of what? > > When you go from the standard right-handed system to the system used > in computer graphics, you use these simple formulas: > > max_x, max_y = image size > screen_x = original_x > screen_y = max_y - original_y - 1 > > HTH > -- > Steve Juranich why subtract 1 from max_y - original_y? From amfr.org at gmail.com Mon Nov 21 19:00:45 2005 From: amfr.org at gmail.com (amfr) Date: 21 Nov 2005 16:00:45 -0800 Subject: BaseHTTPServer module In-Reply-To: References: <1132521453.100699.199850@g43g2000cwa.googlegroups.com> Message-ID: <1132617645.116476.293320@z14g2000cwz.googlegroups.com> Thanks, all I wanted to know where the post data was stored from the request From dcrespo at gmail.com Tue Nov 1 11:21:40 2005 From: dcrespo at gmail.com (dcrespo) Date: 1 Nov 2005 08:21:40 -0800 Subject: python.org offline In-Reply-To: References: Message-ID: <1130862100.694549.276860@f14g2000cwb.googlegroups.com> The answer is here: "The server is temporarily unable to service your request due to maintenance downtime or capacity problems." -- 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 pythonnew at gmail.com Thu Nov 17 19:21:00 2005 From: pythonnew at gmail.com (Ben Bush) Date: Thu, 17 Nov 2005 16:21:00 -0800 Subject: about try and exception Message-ID: <8c11e4350511171621p17034516u85ec7044efa69a2f@mail.gmail.com> I wrote the following code to test the use of "try...exception", and I want n to be printed out. However, the following code's output is: Traceback (most recent call last): File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\py\use\tryExVa.py", line 7, in ? print n NameError: name 'n' is not defined the code is here: try: m=2/0 n=1/2 except ZeroDivisionError: pass print "Yes!!! This line will always print" print n -------------- next part -------------- An HTML attachment was scrubbed... URL: From davideugenewarren at gmail.com Mon Nov 14 17:50:55 2005 From: davideugenewarren at gmail.com (davideugenewarren at gmail.com) Date: 14 Nov 2005 14:50:55 -0800 Subject: Searching date and and time from a text file In-Reply-To: <1132005880.158423.45690@g43g2000cwa.googlegroups.com> References: <1132005880.158423.45690@g43g2000cwa.googlegroups.com> Message-ID: <1132008655.722383.200220@g47g2000cwa.googlegroups.com> masudtarek at gmail.com wrote: > Hi, I am new in Python programming. Can anybody give me any idea about > how to detect more than one date and time (like 11/11/2005 , > 10-12-2006, 12:30 etc) from a text file and keep them in a list. http://docs.python.org/lib/bltin-file-objects.html http://docs.python.org/lib/typesseq.html http://docs.python.org/lib/typesseq-mutable.html http://www.amk.ca/python/howto/regex/ and possibly http://docs.python.org/lib/module-datetime.html From bonono at gmail.com Sun Nov 20 19:09:35 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 16:09:35 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: Message-ID: <1132531775.399671.93120@o13g2000cwo.googlegroups.com> Fredrik Lundh wrote: > but you can easily generate an index when you need it: > > index = dict(d) > > name, type = index["pid"] > print name > > the index should take less than a microsecond to create, and since it > points to the members of the original dict, it doesn't use much memory > either... > Using the same logic, we don't need types other than string in a DBMS as we can always convert a string field into some other types when it is needed. Of course there are more than one way to skin a cat(well it may be against the general idiom of python) but in some situation certain way is preferred. From plucek at ssaris.com Thu Nov 10 09:59:27 2005 From: plucek at ssaris.com (PL) Date: 10 Nov 2005 06:59:27 -0800 Subject: need an example of Python numarray to C++ and back again, Boost / SWIG? In-Reply-To: References: <1131547248.473442.313820@g47g2000cwa.googlegroups.com> Message-ID: <1131634767.323353.110480@g14g2000cwa.googlegroups.com> I looked at Stefan's post - but he remarks that "Unfortunately, Blitz jealously guards its data (restricted pointers), so that it is not so easy to do the conversion in the other direction. If anyone knows an answer to this problem, I'd be glad to hear it" I've previously looked at Phillip Austin's 'num_util' and Paulo J. S. Silva's 'COIN' example, but even from those two, I can't figure out a way to do: Python 2D numarray --> C++ (process array) --> Python 2D numarray. I forgot about "weave" - I had looked there before and will revisit it to see if it will work. But I was intending to do this with a compiled extension. I wish there was a simple example of this in either the SWIG or Boost docs or a faq/howto posted somewhere . . . -Paul Fernando Perez wrote: > PL wrote: > > > I want to pass a 2D array from Python to C++, manipulate it in C++ (for > > example, add 1 to each element) and pass it back to Python. > > > > With these building blocks I will be able to figure out all the rest of > > what I need to do for my project. I am very familiar with Python, but > > less so with C++ and Boost or SWIG. > > > > Does anyone have an example with all steps that I can follow? More > > specifically I am looking for the C++ code, ".i" file for SWIG and/or > > the analagous setup files that Boost would need to do this. > > You may want to look into weave.inline or weave.blitz, from scipy. Typemaps for > conversion to blitz++ were recently posted on the scipy list: > > http://aspn.activestate.com/ASPN/Mail/Message/numpy-discussion/2883831 > > In particular look at Stefan's post. > > For info on weave, here you can find some old slides and example code: > > http://amath.colorado.edu/faculty/fperez/python/ > > Cheers, > > f From cito at online.de Thu Nov 24 08:00:21 2005 From: cito at online.de (Christoph Zwerschke) Date: Thu, 24 Nov 2005 14:00:21 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> <1h6f39h.n2wpx91c4cc2qN%aleax@mail.comcast.net> Message-ID: Duncan Booth schrieb: > On IE this will go through elements in the order 0, 1, 2, 4, 3. Oops! I bet most people would not expect that, and it is probably not mentioned in most Javascript tutorials. I think this is a weakpoint of the ECMA definition, not MSIE. -- Christoph From tim.golden at viacom-outdoor.co.uk Wed Nov 23 09:01:05 2005 From: tim.golden at viacom-outdoor.co.uk (Tim G) Date: 23 Nov 2005 06:01:05 -0800 Subject: Problems with threaded Hotkey application In-Reply-To: <1132727579.268059.60120@g47g2000cwa.googlegroups.com> References: <1132727579.268059.60120@g47g2000cwa.googlegroups.com> Message-ID: <1132754465.629098.11240@g49g2000cwa.googlegroups.com> One obvious point is that, according to: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wceui40/html/cerefWM_HOTKEY.asp the WM_HOTKEY message is posted to the queue *of the thread which registered the hotkey*. I haven't yet tried it myself to see, but in your example the main thread registers the hotkey, and the KeyCatch thread is waiting to receive it. TJG From larry.bates at websafe.com Tue Nov 8 19:57:08 2005 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 08 Nov 2005 18:57:08 -0600 Subject: plugin interface / list In-Reply-To: References: Message-ID: <43714964.6000804@websafe.com> webograph wrote: > hi, > i'm about to write a script to play various audio files. what i want to > write is a directory (module) containing wrappers around various players > that supply a player object (inheriting from a general player object > defined earlier) and an entry in a list of mime types (which player is > for which type). > i've tried various forms of import and __init__.py configurations, but i > repeatedly have problems with the following steps: > - create an object inheriting from the main script > - fill the dictionary declared there > (i guess the problem is actually the same) > > is there a standard way of doing such things? > > thanks in advance > webograph Assuming that I understand your problem. One way is (not tested): class audioBase: def __init__(self, **kwargs): self.__dict__.extend(**kwargs) return # # Define base methods # class mp3player(audioBase): def __init__(self, **kwargs): audioBase.__init__(self, **kwargs) return # # Define mp3player specific methods # # Main program # obj=mp3Player(file='abc.mp3', ) -Larry Bates From edhotchkiss at gmail.com Tue Nov 1 18:25:14 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Tue, 1 Nov 2005 18:25:14 -0500 Subject: WTF? In-Reply-To: <200511011456.35872.jstroud@mbi.ucla.edu> References: <11mfqsibenjoqff@corp.supernews.com> <200511011456.35872.jstroud@mbi.ucla.edu> Message-ID: happens to me too. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fuzzyman at gmail.com Tue Nov 22 10:39:12 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 22 Nov 2005 07:39:12 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <861x1ahhqk.fsf@bhuda.mired.org> Message-ID: <1132673952.619481.19780@f14g2000cwb.googlegroups.com> Of course ours is ordered *and* orderable ! You can explicitly alter the sequence attribute to change the ordering. I think we're looking at improving performance based on some of the suggestions here - as well as possibly widening it to include some of the alternative use cases. (Or at least Nicola Larosa will do it and I'll criticise it). All for another day though... Fuzzyman http://www.voidspace.org.uk/python/index.shtml From bokr at oz.net Sat Nov 19 21:08:19 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 20 Nov 2005 02:08:19 GMT Subject: Behaviour of enumerated types References: <437d6711.87269326@news.oz.net> <437e3cb3.141959727@news.oz.net> <437e8f52.163110430@news.oz.net> Message-ID: <437fa2e8.233660836@news.oz.net> On Sun, 20 Nov 2005 08:42:48 +1100 (EST), Ben Finney wrote: >Bengt Richter wrote: >> On Sat, 19 Nov 2005 11:10:42 +1100 (EST), Ben Finney wrote: >> >Bengt Richter wrote: >> >> If [an enumeration has a fixed sequence], what is more natural >> >> than using their index values as keys to other ordered info? >> >I don't see why. If you want sequence numbers, use enumerate(). If >> >not, the enum object itself can be used directly as an iterable. >> >> I changed mine so the enum _class_ is iterable, but enum instances >> are not. > >I'm not really understanding your design. > >In my enum package, an enumeration is an instance of Enum. Those >instances are iterable, producing EnumValue instances; the EnumValue >instances are also available as named attributes of the Enum instance. I have a similar situation, except I have an enum factory function makeEnum instead of a class Enum, and the factory returns not an instance of Enum, but an enum as a unique type, i.e., a class. But it is functionally analogous, except I differentiate by > > >>> from enum import Enum > >>> colours = Enum('red', 'blue', 'green') > >>> for val in colours: > ... print str(val) > ... > red > blue > green > That corresponds to >>> from makeenum import makeEnum >>> Colours = makeEnum('Colours', 'red blue green') >>> for val in Colours: ... print str(val),'-(repr)->', repr(val) ... red -(repr)-> Colours.red blue -(repr)-> Colours.blue green -(repr)-> Colours.green I added the repr to show that the vals were instances of something, and they are actuall instances of the Colours type, which was uniquely created to represent the enumeration, along with its fixed set of internally cached immutable instances, references to which are returned by the Colours constructor (__new__) instead of creating potentially duplicate instances. So these instances can serve as sentinels too. The id's don't change, no matter how many you construct (of a given member of the instance set). Of course there are len(Colours) fixed (once created and cached) instances of Colours in all. >>> list(Colours) [Colours.red, Colours.blue, Colours.green] >>> map(str, Colours) ['red', 'blue', 'green'] >>> map(int, Colours) [0, 1, 2] >>> int(Colours.blue) 1 >>> Colours[1] Colours.blue >Why would the Enum *class* be iterable? That corresponds to asking why my makeEnum should be iterable, and the it is not. What makeEnum makes functionally corresponds to your Enum instance, except my "instance" is a unique manufactured class. > >> >> OTOH, the index values (and hence my enums) are[1] not very good >> >> as unique dict keys, since they compare[2] promiscuously with >> >> each other and other number types. >> >Indeed, that's why (in my design) the values from the enum are only >> >useful for comparing with each other. This, to me, seems to be the >> >purpose of an enumerated type. >> >> Have you tried yet to use two different enum instances as keys in >> the same dict? > >What do you mean by "enum instances"? I presume you mean "values from >a single enum". Yes, by analogy to your functionality, but since my "single enum" is actually a class returned by makeEnum, not an instance of Enum, i.e., >>> Colours and the "values" are immutable singleton instances that you can access via the class (which I gave some unusual capabilities -- i.e., some methods that apply to it as an ordered collection of immutable instances, and which aren't accessible as methods of the instances (though the instances have special methods of their own, and inherit methods from int). > > >>> colour_german = { colours.red: "rot", colours.green: "gr??n", > >>> colours.blue: "blau" } > >>> for val in colours: > ... print colour_german[val] > ... > rot > blau > gr??n That's a plain dict with colour "values" as keys. Same as (checking the order first to get the zip correspondence right ;-) >>> list(Colours) [Colours.red, Colours.blue, Colours.green] >>> colour_german = dict(zip(Colours, ('rot', 'blau', 'gr?n'))) >>> for val in Colours: ... print 'colour_german[%r] => %s' %(val, colour_german[val]) ... colour_german[Colours.red] => rot colour_german[Colours.blue] => blau colour_german[Colours.green] => gr?n > >> Then try to sort the keys(or items is the values are misc different >> enums). > >Oh, perhaps you mean "enum values from different enum instances". No, Yes, again by analogy. >those won't compare against each other; there's no meaningful >relationship, since different enum instances are conceptually >different types. Well, yes, I made that the strict default cmp, but I can optionally make "Enum instances" (makeEnum returned classes) whose values cmp differently. But now that I think of it, sorting is pretty controllable anyway, e.g, suppose we had a Coins enum: >>> Coins = makeEnum('Coins', 'penny nickel dime quarter') >>> Colours[:] + Coins[:] [Colours.red, Colours.blue, Colours.green, Coins.penny, Coins.nickel, Coins.dime, Coins.quarter] >>> sorted(Colours[:] + Coins[:], key=repr) [Coins.dime, Coins.nickel, Coins.penny, Coins.quarter, Colours.blue, Colours.green, Colours.red] >>> sorted(Colours[:] + Coins[:], key=str) [Colours.blue, Coins.dime, Colours.green, Coins.nickel, Coins.penny, Coins.quarter, Colours.red] >>> map(str, sorted(Colours[:] + Coins[:], key=str)) ['blue', 'dime', 'green', 'nickel', 'penny', 'quarter', 'red'] >>> map(str, sorted(Colours[:] + Coins[:], key=int)) ['red', 'penny', 'blue', 'nickel', 'green', 'dime', 'quarter'] >>> map(str, sorted(Colours[:] + Coins[:], key=type)) ['red', 'blue', 'green', 'penny', 'nickel', 'dime', 'quarter'] >>> map(str, sorted(Colours[:] + Coins[:], key=lambda x:(type(x).__name__, int(x)))) ['penny', 'nickel', 'dime', 'quarter', 'red', 'blue', 'green'] >>> sorted(Colours[:] + Coins[:], key=lambda x:(type(x).__name__, int(x))) [Coins.penny, Coins.nickel, Coins.dime, Coins.quarter, Colours.red, Colours.blue, Colours.green] >>> sorted(Colours[:] + Coins[:], key=repr) [Coins.dime, Coins.nickel, Coins.penny, Coins.quarter, Colours.blue, Colours.green, Colours.red] > >> I hit that, and changed __cmp__ to compare (typename, > other if not int subtype>) tuples. > >I think this is a flaw, based on expecting too strong a relationship >between the enum value instance, and an integer value. Actually, I'm not "expecting" it, I am defining it that way ;-) Note the parallels between >>> Bool = makeEnum('Bool', 'False True') >>> issubclass(Bool, int) True >>> issubclass(bool, int) True >>> isinstance(Bool.False, int) True >>> isinstance( False, int) True >>> isinstance(Bool.True, int) True >>> isinstance( True, int) True >>> bf = bool(0) >>> bf2 = bool(0) >>> bf is bf2 True >>> Bool >>> Bf = Bool(0) >>> Bf2 = Bool(0) >>> Bf is Bf2 True >>> Bf Bool.False >>> Bf2 Bool.False >>> bf False >>> bf2 False >>> map(int, [True, False]) [1, 0] >>> map(int, [Bool.True, Bool.False]) [1, 0] > >> That sorts items grouped by enum type if they're keys. > >Why should colours.blue compare before fruits.orange? How is that >meaningful? Like Finneys come before Richters in the telephone book ;-) > >> >I think I've addressed all your current concerns; I don't believe >> >an inherent correlation to integers is necessary at all. >> >> Necessary wasn't the question for me. It's whether it's desirable. >> YMMV ;-) > >I'm still trying to understand what is served by having some exposed >relationship between an enum value instance and an integer value. The relationship is effectively __int__ giving the index position in the originally specified sequence of names, without having to do an index operation, and without having to do anything but use a reference to the value in a context where the integer value is useful. > >> >It's no more necessary than saying that ["a", "b", "c"] requires >> >that there be some specific correlation between the values of that >> >list and the integers 0, 1, 2. If you *want* such a correlation, in >> >some particular case, use enumerate() to get it; but there's >> >nothing about the values themselves that requires that >> >correspondence. That's true for arbitrary values in a list, but IMO it's not true for values whose names were originally specified in a particular order for (presumably -- or doesn't your enum care about the order??) a reason. Enums in other languages have that default correspondence typically, from what I can recall, and promotion to integer in arithmetic contexts is also common. Having different enumerations be distinct _types_ is exactly what C++ does. And Pascal. >> >> Yet it is comforting to know that ['a', 'b', 'c'][0] will interpret >> the [0] to mean the first in the sequence (unless someone is doing a >> list-like repr trick based on some other type ;-). > >Again, you're only talking about *sequence*, not correspondence to >integers. Your case above isn't an argument in favour of "the 'a' >value should coerce to the 0 value". Why then should an enum value >instance coerce to any particular integer value? The particular integer values have no relation to their position in an _arbitrary_ list, but they do have that relation to their position in the originally specified sequence of their names. > >> The class methods are introduced via metaclass in the makeEnum factory >> and it's a very hacky workaround for the fact that execution of a >> class definition body only has local and module global namespace, so >> you can't directly reference anything local to the factory function. > >Here you've lost me, since I don't understand why you want >enumerations to be classes at all. Are you going to be making >instances of an entire enumeration? If not, why make classes instead >of objects? For the same reason C++ does. Different enumerations are logically different types, not just different objects. Somehow ISTM maybe you are using the enum name in an extended way that really maybe calls for another name. Some kind of homogeneous frozen list with names for the elements, which e.g. is more like struct than enum in C++. What are the real use cases for your enums? And how are the same problems usually solved? I guess I see the default case for C++ as a model, and might extend that to a sparse sequence of integer values with names, but without allowing instances of intervening values like C++. I don't know, I have a feeling some experiments are just featuritis. Since sorts can easily be controlled with a key function, maybe configuring with different __cmp__ and __eq__ etc. is overkill. What's needed is some real use cases. Maybe there is a place for both kinds of enums, if we give them different names ;-) Regards, Bengt Richter From http Wed Nov 23 18:14:01 2005 From: http (Paul Rubin) Date: 23 Nov 2005 15:14:01 -0800 Subject: FTP over TLS References: Message-ID: <7xirujvtxi.fsf@ruckus.brouhaha.com> Carl Waldbieser writes: > Does anyone know of any good examples for writing client side code > to upload files over a secure FTP connection? I am referring to > FTPS, *not* SFTP, which I found out the hard way are two different > things. I am not really all that familiar with FTPS, but from what > I understand, when the client sends the "AUTH" command, it can > request a TLS connection from the server. The standard is not yet finalized: ftp://ftp.rfc-editor.org/in-notes/rfc4217.txt > I wasn't sure how to do this in Python, and Googling around didn't really > produce any useful Python-related results for me. I don't know of any Python code that does it. You could adapt the existing Python ftp client to use one of the Python TLS packages. From ntv1534 at gmail.com Wed Nov 9 11:09:23 2005 From: ntv1534 at gmail.com (MooMaster) Date: 9 Nov 2005 08:09:23 -0800 Subject: parse data In-Reply-To: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> References: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> Message-ID: <1131552563.829632.49640@g14g2000cwa.googlegroups.com> If you know the indices of where the data should be in your string, you can use substrings... ie: >>> stringy = " Happy Happy Cow, 50, 1234 Your Mom's House AllTheTime,USA " >>> stringy[0:16] ' Happy Happy Cow' If the data isn't set all the time (for example, and address doesn't have a mandatory length), then you're probably stuck using the index function...unless you have everything separated by a delimiter, such as a ","...then this would work: >>> listy = stringy.split(",") >>> print listy [' Happy Happy Cow', ' 50', " 1234 Your Mom's House AllTheTime", 'USA '] Hope this helps! From rhettinger at gmail.com Wed Nov 23 11:53:41 2005 From: rhettinger at gmail.com (rhettinger at gmail.com) Date: 23 Nov 2005 08:53:41 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: <1132764821.340622.321850@g47g2000cwa.googlegroups.com> [Steven Bethard] > >Then why document itertools.izip() as it is? The documentation there is > >explicit enough to know that izip(it, it) will work as intended. Should > >we make the documentation there less explicit to discourage people from > >using the izip(it, it) idiom? [Dave Hansen] > In any case, the solution seems obvious: if you want the guarantee, > use the tool that provides it. True enough :-) FWIW, the itertools documentation style was intended more as a learning device than as a specification. I combined regular documentation, approximately equivalent generator code, examples, and recipes. Hopefully, reading the module docs creates an understanding of what the tools do, how to use them, how to combine them, and how to roll your own to extend the toolset. Another goal was providing code fragments to support scripts needing to run on Py2.2 (itertools were introduced in Py2.3). Raymond From cito at online.de Tue Nov 22 15:24:29 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 21:24:29 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: Carsten Haese wrote: > That could easily be fixed by making the sequence a "managed property" > whose setter raises a ValueError if you try to set it to something > that's not a permutation of what it was. Ok, a managed attribute would be an option. You would allow people to do what they want with the sequence, and then fix the dictionary accordingly (if items were deleted from the sequence, they are deleted from the dictionary, it items were added which are not in the directory, a ValueError is raised etc.). But probably it is still better to hide the sequence and instead of letting people do list operations like sort() on the odict.sequence, let them do these operations on odict directly. >>d1[0] + d1[2] ==> OrderedDict( (1, 11), (3, 13) ) > What do you think you're doing here? Sorry, what I meant was d1[0:0] + d1[2:2] ==> OrderedDict( (1, 11), (3, 13) ) Ordered dictionaries could allow slicing and concatenation. -- Christoph From rupole at hotmail.com Sat Nov 5 01:46:40 2005 From: rupole at hotmail.com (Roger Upole) Date: Sat, 5 Nov 2005 01:46:40 -0500 Subject: putting an Icon in "My Computer" References: <1131071030.209405.37800@z14g2000cwz.googlegroups.com> Message-ID: <1131173451_3241@spool6-east.superfeed.net> There's an example of how to add an item to the shell namespace in the Pywin32 demos: \win32comext\shell\demos\servers\shell_view.py hth Roger "yaipa" wrote in message news:1131071030.209405.37800 at z14g2000cwz.googlegroups.com... > All, > > I've been asked by my boss to put an Icon in WinXP's "My Computer" for > a utility we use around the shop. My tool of choice is of course > Python and therefore what I am using to attempt my given task. I have > no trouble putting Icons in the WinXP Toolbar using Python, but have > totally failed to get an Icon to appear in My Computer. Any Idea on > why and maybe how to get around this using Python? > > Thanks, > > Alan > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-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 bokr at oz.net Fri Nov 18 05:40:25 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 18 Nov 2005 10:40:25 GMT Subject: Immutable instances, constant values References: Message-ID: <437d6711.87269326@news.oz.net> On Fri, 18 Nov 2005 14:32:46 +1100 (EST), Ben Finney wrote: >Howdy all, > >I've recently packaged 'enum' in PyPI. In its description, I make the >claim that it creates "immutable" enumeration objects, and that the >enumeration values are "constant" values. > >This raises questions. > >Is there any difference between a Python immutable value, and a >constant? I suppose "constant" also implies that the *name* binds >unchangeably to a particular value. Is that meaningful? > >How does one actually ensure an object is immutable? Is it a matter of >overriding a bunch of methods, or is ther a neater way? > >Is it bad style to make a user-defined class that creates immutable >objects? Why? > >In the case of 'enum', can anyone argue for or against an enumerated >type being immutable? Its values being constant? > My notion of enum comes from (what I remember of) Pascal, which is basically an ordered set of names of integers forming a type, and ord(one_of_the_names) gets you the index value. Python's ord seems to demand a string of length one, and doesn't seem to attempt coercion, so that might not fly without a mod. But what we have is named integers, much as True and False are built in names for integer subtypes with value 1 and 0. So I'd say enums should also be int subtypes... Anyway, I would hope that the name->ord(name) mapping would be immutable once defined (though not necessarily obsessively preventing the ususal end runs). Hm, might as well be more concrete ... >>> def makeEnum(ename, names): ... names = names.split() ... top = len(names) ... # define method functions outside class so they'll be closures accessing nested names ... def __new__(cls, name=names[0]): ... try: ... i = names.index(name) ... return int.__new__(cls, i) ... except ValueError: ... if isinstance(name, int) and 0< name < top: return int.__new__(cls, name) ... raise ValueError, 'illegal %s enum value %r'%(cls.__name__, name) ... def __repr__(self): return '%s(%s)' %(self.__class__.__name__, names[self]) ... # return names with names attribute of class or instance ... class getnames(object): ... def __set__(*ignore): raise AttributeError, 'names protected' ... getnames.__get__ = lambda *ignore: names[:] ... return type(ename, (int,),{'__new__':__new__, '__repr__':__repr__, '__str__':__repr__, ... 'names':getnames()}) ... ... >>> Colors = makeEnum('Color', 'red green blue') >>> Colors >>> Colors() Color(red) >>> Colors(1) Color(green) >>> r,g,b = (Colors(name) for name in Colors.names) >>> r Color(red) >>> g Color(green) >>> b Color(blue) >>> 'ABC'[g] 'B' >>> int(g) 1 >>> Colors(5) Traceback (most recent call last): File "", line 1, in ? File "", line 11, in __new__ ValueError: illegal Color enum value 5 >>> Colors('blue') Color(blue) >>> Colors(2) Color(blue) >>> Colors('orange') Traceback (most recent call last): File "", line 1, in ? File "", line 11, in __new__ ValueError: illegal Color enum value 'orange' Just some thoughts. Oh, names are kind of protected by [:], but really should throw an exception if you try to mutate. >>> Colors.names ['red', 'green', 'blue'] >>> Colors.names[2] 'blue' >>> Colors.names[2] = 'indigo' >>> Colors.names[2] 'blue' It would be easy to return a tuple. It's not that easy to protect against Colors.names = something since __metaclass__ skips factory local to global if not in class scope, and passing a '__metaclass__': mcdefinition in the dict arg to type does not result in a call, it just becomes another passive class variable. Must be a way though. Too tired for now... Regards, Bengt Richter From nk67v8o02 at sneakemail.com Fri Nov 25 14:30:46 2005 From: nk67v8o02 at sneakemail.com (mojosam) Date: 25 Nov 2005 11:30:46 -0800 Subject: Which License Should I Use? Message-ID: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> I've been watching the flame war about licenses with some interest. There are many motivations for those who participate in this sector, so disagreements over licenses reflect those agendas. I don't have an agenda, at least not right now. I do plan on writing a few programs. These will be tools I need for firmware testing. They will be relatively simple things like tools for breaking down data by its structure for easy viewing, sending commands/macros over serial ports, etc. Similar things exist, but they don't do everything I need. These will also be excellent learning opportunities for me, since I'm still pretty shaky on Python. How do I decide on a license? Are there any web sites that summarize the pros and cons? I guess I don't care too much about how other people use it. These things won't be comprehensive enough or have broad enough appeal that somebody will slap a new coat of paint on them and try to sell them. I guess I don't care if somebody incorporates them into something bigger. If somebody were to add features to them, it would be nice to get the code and keep the derivative work as open source, but I don't think that matters all that much to me. If somebody can add value and find a way of making money at it, I don't think I'd be too upset. I will be doing the bulk of the coding on my own time, because I need to be able to take these tools with me when I change employers. However, I'm sure that in the course of using these tools, I will need to spend time on the job debugging or tweaking them. I do not want my current employer to have any claim on my code in any way. Usually if you program on company time, that makes what you do a "work for hire". I can't contaminate my code like that. Does that mean the GPL is the strongest defense in this situation? I'm open to suggestions as to which licenses to consider. However, please try to keep the conversation to the decision process or what sounds like it is best for this purpose. Let's keep the broader issue of which license will bring about the fall of Western Civilization on the other thread. Ron Britton (The gibberish on the next line really is my email address.) nk67v8o02 at sneakemail.com From bonono at gmail.com Wed Nov 30 21:05:29 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 30 Nov 2005 18:05:29 -0800 Subject: Making immutable instances In-Reply-To: <86acfloox6.fsf@bhuda.mired.org> References: <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> <86u0duodzl.fsf@bhuda.mired.org> <1133333467.677454.134110@g49g2000cwa.googlegroups.com> <86acfloox6.fsf@bhuda.mired.org> Message-ID: <1133402729.430608.21400@g43g2000cwa.googlegroups.com> Mike Meyer wrote: > bonono at gmail.com writes: > > I am puzzled, and could have read what you want wrong. Are you saying > > you want something like this : > > > > a={} > > a.something = "I want to hang my stuff here, outside the intended use > > of dict" > > Exactly. For a use case, consider calling select.select on lists of > file objects. If the processing is simple enough, the clearest way to > associate a handler with each socket is just to add it as an > attribute. But that doesn't work - sockets are bulitin types. So you > consider less light-weight solutions, like subclassing socket (now > that that's possible), or a dictionary of handlers keyed by socket. > > This works by default with classes written in Python. That it doesn't > work for builtins is inconsistent, non-orthogonal, and > incomplete. However, it's easy to work around, and the obvious fix - > adding a dictionary to every builtin - is rather costly. So we'll live > with it since practicality beats purity. > While I agree with the use case(I want it sometimes too), it seems that the language creator may also deliberately disallow that, not because it is not doable or costly. So how, the built-in types still need to have some form of dictionary or else how would dir(a) of the above dictionary work ? From cito at online.de Mon Nov 21 11:54:18 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 21 Nov 2005 17:54:18 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <861x1ahhqk.fsf@bhuda.mired.org> References: <861x1ahhqk.fsf@bhuda.mired.org> Message-ID: Ben Finney wrote: >>> Another possibility: ordered dictionaries are not needed when Python >>> 2.4 has the 'sorted' builtin. Christoph Zwerschke wrote: >> The 'sorted' function does not help in the case I have indicated, >> where "I do not want the keys to be sorted alphabetically, but >> according to some criteria which cannot be derived from the keys >> themselves." Mike Meyer wrote: > And how would an ordered dictionary help in this case? Maybe there is some confusion between an "orderable" and an "ordered" dictionary. When I talk about "ordered dictionary", then in the simplest case I just set up my ordered dictionary with my preferred key order and it stays like that. This allows me to later iterate through the dictionary in this preferred order, while being still able to randomly access data from the dictionary at other places. -- Christoph From fredrik at pythonware.com Wed Nov 9 14:51:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 20:51:57 +0100 Subject: xml.minidom and user defined entities References: Message-ID: Nick Craig-Wood wrote: > I'm using xml.minidom to parse some of our XML files. Some of these > have entities like "°" in which aren't understood by xml.minidom. ° is not a standard entity in XML (see below). > These give this error. > > xml.parsers.expat.ExpatError: undefined entity: line 12, column 1 > > Does anyone know how to add entities when using xml.minidom? the document is supposed to contain the necessary entity declarations as an inline DTD, or contain a reference to an external DTD. (iirc, mini- dom only supports inline DTDs, but that may have been fixed in recent versions). if you don't have a DTD, your document is broken (if so, and the set of entities is known, you can use re.sub to fix replace unknown entities with the corresponding characters before parsing. let me know if you want sample code). From apardon at forel.vub.ac.be Fri Nov 4 06:09:36 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 11:09:36 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <86irv8hg74.fsf@bhuda.mired.org> Message-ID: Op 2005-11-04, Mike Meyer schreef : > Antoon Pardon writes: >> Op 2005-11-03, Mike Meyer schreef : >>> Antoon Pardon writes: >>>>> What would you expect to get if you wrote b.a = b.a + 2? >>>> I would expect a result consistent with the fact that both times >>>> b.a would refer to the same object. >>> Except they *don't*. This happens in any language that resolves >>> references at run time. >> Python doesn't resolve references at run time. If it did the following >> should work. > > You left out a key word: "all". > >> a = 1 >> def f(): >> a = a + 1 >> >> f() > > If Python didn't resolve references at run time, the following > wouldn't work: > >>>> def f(): > ... global a > ... a = a + 1 > ... >>>> a = 1 >>>> f() >>>> Why do you think so? I see nothing here that couldn't work with a reference resolved during compile time. >> But letting that aside. There is still a difference between resolving >> reference at run time and having the same reference resolved twice >> with each resolution a different result. > > The second is a direct result of the first. The environment can change > between the references, so they resolve to different results. No the second is not a direct result of the first. Since there is only one reference, I see nothing wrong with the environment remebering the reference and reusing it if it needs the reference a second time. Take the code: lst[f()] += 1 Now let f be a function with a side effect, that in succession produces the positive integers starting with one. What do you think this should be equivallent to: t = f() lst[t] = lst[t] + 1 or lst[f()] = lst[f()] + 1 If you think the environment can change between references then I suppose you prefer the second approach. -- Antoon Pardon From steve at REMOVEMEcyber.com.au Mon Nov 21 21:52:15 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 22 Nov 2005 13:52:15 +1100 Subject: Backwards compatibility [was Re: is parameter an iterable?] References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com><1h62slm.up4s2tqyk1gjN%aleax@mail.comcast.net> <437C36EA.8010600@REMOVEMEcyber.com.au> Message-ID: <438287DF.8030506@REMOVEMEcyber.com.au> Fredrik Lundh wrote: > Steven D'Aprano wrote: > > >>Alas and alack, I have to write code which is backwards >>compatible with older versions of Python: [snip] >>What should I do when I can't rely on functions that >>don't exist in older versions of Python? > > > python 2.1 doesn't support iterators, so that question doesn't > make much sense. The _question_ doesn't make much sense? I could understand you saying that backwards-compatibility is "not important [to me]" but to say that the very question of how to maintain backwards compatibility makes little sense is a bit extreme, don't you think? Fredrik, I bow to your superior knowledge about Python, no sarcasm intended, and I've learnt a lot from your posts, thank you. But this is not one of your shining moments. Your attitude was utterly dismissive: the "right way" to solve the problem of recognising iterables was to use iter, and that's all that needs to be said. The problem of how to recognise iterables did not come into existence with version 2.2, and backwards compatibility is sometimes a real requirement. A few months back I had to mangle some Py2.4 code so that it would run under version 2.0, and wasn't that fun. > if you want to write code that runs under 2.1, you have to write > your code in terms of what 2.1 supports. Do you think I don't know this? I never imagined for an instant that Python 2.1 would somehow magically be able to use features that didn't exist in Python 2.1. But then it wasn't me saying that there was nothing to discuss, the "right way" is to use iter(), end of story. If I have to write code that can't rely on iter() existing in the language, what should I do? Are there practical idioms for solving the metaproblem "solve problem X using the latest features where available, otherwise fall back on older, less powerful features"? For instance, perhaps I might do this: try: built_in_feature except NameError: # fall back on a work-around from backwards_compatibility import \ feature as built_in_feature Do people do this or is it a bad idea? Are there other techniques to use? Obviously refusing to run is a solution (for some meaning of "solution"), it may even be a practical solution for some cases, but is it the only one? In the specific case of iter(), are there good alternative ways of detecting an iterable without consuming it? -- Steven. From phoolimin at gmail.com Mon Nov 28 05:48:44 2005 From: phoolimin at gmail.com (phoolimin at gmail.com) Date: 28 Nov 2005 02:48:44 -0800 Subject: ANN: Dao Language v.0.9.6-beta is release! Message-ID: <1133174924.322968.273370@o13g2000cwo.googlegroups.com> Dear all, This is just to let you know that the lastest version Dao language is released. This Dao was previously called Tao, and now is changed to Dao to avoid confusion with another Tao langauge. There are a number of new features implemented in this version, of which the most important one is the supporting for multi-threaded programming. A new concurrent garbage collector is also implemented to for the multi-threaded interpreter. Now unicode is also supported for string manipulation and regular expression (regex) matching etc. The algorithm for regex matching is enhanced with fixing of a few bugs which prevent finding the most reasonable matching in some case, and allowing reverse matching from the end of string. The interface for creating Dao plugin in C++ is further simplified and matured. Of course, many bugs are also fixed. For more information, please visite: http://www.xdao.org. By the way, a console named DaoConsole with graphical user interface is also released. With best regards, Limin Fu ----------------------------- ChangLog for this release: ----------------------------- + : added ! : changed * : fixed - : removed MULTITHREADING: + Multi-threaded programming is supported as a kernel feature of Dao language. Posix thread library is used in the implementation. And the thread API in Dao is similar to that in Posix thread. Parts of the Dao interpreter is re-structured for multithreading. + A novel concurrent garbage collector based on reference counting is implemented to support multithreading. + A upper bound for GC amount is applied to prevent memory "avalanche", where mutators generate garbage faster than GC can collect them. gcmin(), gcmax(). UNICODE: + UNICODE is supported. String quotated with double quotation symbol is internally represented as Wide Character String(WCS), while string quotated with single quotation symbol is internally represented Multi Bytes String(MBS). Corresponding operations on WCS is also supported. REGEX: + Regex reverse matching is supported. + Now internal representation of Regex uses both MBS and WCS for both efficiency and proper matching character class for unicode. When a regex is applied to MBS or WCS, the corresponding representation is used. + Regex datatype is added, a regex pattern can be compiled and stored for later use, by using: define regex: rgx = /\d+\w/; or, rgx = regex( "\\d+\\w" ); + New character class abbreviations \u and \U are added for unicode. + Customized character class abbreviations are support. Users can define their own character class abbreviations by: define regex: \2 = [WhateverChars]; ! Algorithm for regex matching is modified to extend matching when possible, and is also modified to match regex group correctly. NUMERIC ARRAY: + Specification of precision in numeric array enumeration is supported: num=[@{numtype} array]; ! Transpose operator(right operator) is changed from ' to ~. - Function convolute() for numeric arrays is removed. EXTENDING AND EMBEDDING: + Some abstract classes are added for supporting easy embedding of Dao interpreter ( the daoMain.cpp source file is an example for embedding ). + Some wrapper classes for Dao data objects are provide in daoType.h to faciliate the using of Dao data objects in plugins or other programs in which Dao is embedded. ! A new technique is implemented to allow more tranparent passing data between Dao interpreter and C++ modules. Creation of shadow classes is also supported by the way. IO: + Instead of using STL stream classes, new DaoStream classes are added mainly for handling unicode in many places. + For file IO, more open modes such as "rwat" are supported, and more methods such as eof(), seek(), tell() ... are implemented. read() is enhanced such that it can read until meeting EOF. OTHERS: + Multi inheritance is supported for OOP. And the passing parameters and calling to parent constructor is simplified. + Negative subindex is supported for string. + Added a feature that allows using Alternate KeyWord (*.akw) to write Dao scripts in non-english languages. The only requirement is the character encoding for the .akw file must be the same as the script files. ! Variable scope specification keyword "global" is added; keyword "extern" is remove; keyword "share" is changed to "shared" ! Data states are added for constant and frozen data. Now a const data is a really const, and can not be modified anymore. Function freeze() is added to freeze some data structures as well as those are reachable from them, to prevent them from being modified; And defreeze() is added to defreeze them. ! The using namespace is simplified(compile(),eval(),source()). From greg.steffensen at gmail.com Fri Nov 25 18:25:58 2005 From: greg.steffensen at gmail.com (gsteff) Date: 25 Nov 2005 15:25:58 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132961158.430293.83010@f14g2000cwb.googlegroups.com> I learned pygtk via the tutorial and reference manual, and found most things to be pleasantly simple to do. A message dialog, for example, can be done via dialog = gtk.MessageDialog(buttons=gtk.BUTTONS_OK_CANCEL, message_format="Test message here.") response = dialog.run() All that can be found by looking up the MessageDialog class in the reference manual, noticing that there's not much there, and looking and the documentation for its parent "Dialog" class. That may be one source of confusion you may have experiened while reading the reference manual. In general, I've found pygtk to be remarkably pythonic (for an interface to a library that has been ported to many other languages as well). For example, when using tree views, you can access the tree model underlying it using the normal python list syntax, which I think is very cool. If you have other examples of things that are confusing, post them (here, or to the pygtk list). Greg From bignose+hates-spam at benfinney.id.au Thu Nov 10 22:05:19 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Nov 2005 14:05:19 +1100 (EST) Subject: derived / base class name conflicts References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> Message-ID: christopherlmarshall at yahoo.com wrote: > Suppose you want to write a subclass of some existing class you are > importing from a module you didn't write and that you don't want to > study the internals of No need to study its internals. Fire up a Python interpreter and inspect its outside: >>> import foomodule >>> dir(foomodule.FooClass) Any attributes named there should be avoided in your subclasses if you don't want to clobber existing behaviour. -- \ "Those who will not reason, are bigots, those who cannot, are | `\ fools, and those who dare not, are slaves." -- "Lord" George | _o__) Gordon Noel Byron | Ben Finney From rupole at hotmail.com Sun Nov 20 04:17:19 2005 From: rupole at hotmail.com (Roger Upole) Date: Sun, 20 Nov 2005 04:17:19 -0500 Subject: Problem printing in Win98 References: <1132474167.583323.137390@z14g2000cwz.googlegroups.com> Message-ID: <1132478493_13609@spool6-east.superfeed.net> According to MSDN, err code 31 from ShellExecute is SE_ERR_NOASSOC, meaning there's not an application registered for printing that file type. Roger "Maravilloso" wrote in message news:1132474167.583323.137390 at z14g2000cwz.googlegroups.com... > Hi > > I'm trying to automatically send a postscript file to be printed to the > default printer in a Win98 PC, by means of using the instrucction: > > win32api.ShellExecute (0, "print", "file.ps", None, ".", 0) > > but it raises an exception with the message: > > error: (31, 'ShellExecute', 'A device attached to the system is not > functioning.') > > > Curiously, that instruction does works on Win2K/XP, but trying to use > this shortcut for easy printing in Win98 provokes such error. I've > tried in different machines (all of them running with Win98) and I > obtain the same output. > > Does anybody knows what happens with Win98 printing automation? > Any idea? > > Thanks in advance > ----== 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 casevh at comcast.net Wed Nov 30 02:51:27 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 29 Nov 2005 23:51:27 -0800 Subject: ANN: DecInt 0.3 - Arithmetic for very large decimal integers Message-ID: DecInt is a class that support arithmetic on very large decimal integers. For example, it can calculate the decimal form of the 42nd Mersenne prime, all 7,816,230 digits, in less than 21 seconds. And less than 6 seconds if gmpy 1.01 is available. This version is significantly faster than the prior version. Multiplication used a combination of 4-way Toom-Cook and Nussbaumer convolution. Pure Python multiplication is less than 10x slower than GMP's hand optimised assembler code! Division uses a new algorithm based on David M. Smith's division algorithm. Pure Python division is 16x slower than GMP but can actually be faster in some instances; for example, dividing a 2,000,000 digit number by an 800,000 digit number. DecInt can be found at http://home.comcast.net/~casevh/ (DecInt used to be called BigDecimal; I renamed it to avoid confusion with the "decimal" class include with Python.) Enjoy, casevh From mwm at mired.org Thu Nov 24 19:29:07 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 19:29:07 -0500 Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> Message-ID: <86y83dvacs.fsf@bhuda.mired.org> "Giovanni Bajo" writes: > Mike Meyer wrote: >>>> Note that this property of __slots__ is an implementation detail. >>>> You >>>> can't rely on it working in the future. >>> I don't "rely" on it. I just want to catch bugs in my code. >> I certainly hope you're not relying on it to catch bugs. You should do >> proper testing instead. Not only will that catch pretty much all the >> bugs you mention later - thus resolving you of the need to handcuff >> clients of your class - it will catch lots of other bugs as well. > My feeling is that you're trying to get too much out of my words. I'm not > trying to handcuff anyone. You seem to concentrate on me trying to avoid people > adding attributes to my precious objects. Because *that's* the use case that you're preventing that I have problems with. > It's not that. If I write a class and want it to be immutable, it is > because it has to be so. If I write a queue class and I say that > people shouldn't call pop() if it's empty, I mean it. If I enforce > it with a RuntimeError, I'm not thinking I'm handcuffing someone. I > don't see a ImmutableError to be so different from it. And I have no problems with that. If you believe your class should throw an error if someone calls an instances pop() method when it's empty, do so. Likewise, if you want to make it so a client can't change your attributes, feel free to do so. However, when you prevent a client from adding an attribute, you're not merely making your objects immutable, you're making them static. Python isn't a static language, it's a dynamic language. I consider parts of it that are static to be warts. > In my view, enforcing immutability is no different from other forms of > self-checks. Do you reckon all kind of asserts are useless then? Surely they > don't help for anything that a good unittest couldn't uncover. But they help > catching bugs such as breakage of invariants immediately as they happen. > Immutability can be such an invariant. Adding an attribute can't break an invariant. The only way an attribute can affect an invariant is if the invariant references it. If it references it it, then it must exist - so I can't add it. >>>>> If it's not a wart, why would it be a wart for user-defined types >>>>> to >>>>> have the same behaviour? >>>> >>>> It's a wart because user-defined classes *don't* have the same >>>> behavior. >>> Then *my* solution for this would be to give user-defined classes a >>> way to behave like builtins, eg. explicitally and fully implement >>> immutability. >> >> Well, if you want to propose a change to the language, you need a good >> use case to demonstrate the benefits of such a change. Do you have >> such a use case? Catching bugs doesn't qualify, otherwise Python would >> be radically different from what it is. > > One good reason, in my opinion, is that there *are* immutable objects in > Python, among builtins. And people can easily build extension objects which are > immutable. So being impossible to write a regular object in Python which is > immutable is not orthogonal to me. I didn't ask for a reason, I asked for a use case. Orthogonality is a good thing, but so is generality. So I'll argue that the correct way to make this situation orthogonal is to make builtin objects more general by making it possible to add attributes to all of them. On the other hand, practicality beats purity, and doing the above has a significant cost in the current implementation, so leave it like it is. > Now let me ask you a question. What is a good use case for "assert" that > justifies its introduction in the language? What is a good usecase for module > 'unittest' which justifies its introduction in the standard library? Unittesting doesn't change the language, and is part of any good development methodology. Assert is a shorthand for "if ... ; raise ...." that vanishes when you turn on optimization. It's cleaner and more clearly expresses the intent of the programmer, and saves a fair amount of boilerplate in the best case. > Why do you think tuples are immutable and *enforced* to be so? That you can't add attributes to a tuple is a detail of the implementation; it's true for non-immutable types as well. >> I'm not sure it's more important than >> things like interned strings and the sharing of small integers. Most >> of the discussion of immutables here seems to be caused by newcomers >> wanting to copy an idiom from another language which doesn't have >> immutable variables. Their real problem is usually with binding, not >> immutability. > I'm not such a newcomer, but (how funny) Python is *the* language that > introduced me to the concept of immutable objects and their importance in > design :) Well, that would explain why you think it's so important - it's where you first encountered it. I'd argue that it's no more important than identity - which is what I was searching for when I talked about interned strings sharing small integers. There are builtin types that preserve identity for equal instances, at least under some conditions. There are no constructs for helping you do that with user-defined objects. Should we add them for the sake of orthogonality? I don't think so - not without a good use case. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bj_666 at gmx.net Wed Nov 9 17:02:18 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 09 Nov 2005 23:02:18 +0100 Subject: user account logon from python References: Message-ID: In , Philippe C. Martin wrote: > I am attempting to write a linux logon manager with python. Have you considered looking at the sources of xdm/gdm/kdm/... to see how they solve the problems you have? Ciao, Marc 'BlackJack' Rintsch From csubich.spam.block at spam.subich.block.com Fri Nov 4 09:22:51 2005 From: csubich.spam.block at spam.subich.block.com (Christopher Subich) Date: Fri, 04 Nov 2005 09:22:51 -0500 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > Op 2005-11-03, Stefan Arentz schreef : >>The model makes sense in my opinion. If you don't like it then there are >>plenty of other languages to choose from that have decided to implement >>things differently. > > > And again this argument. Like it or leave it, as if one can't in general > like the language, without being blind for a number of shortcomings. > > It is this kind of recations that make me think a number of people is > blindly devoted to the language to the point that any criticism of > the language becomes intollerable. No, it's just that a goodly number of people actually -like- the relatively simple conceputal model of Python. Why /shouldn't/ >>>a.x = foo correspond exactly to >>>setattr(a,'x',foo) #? Similarly, why shouldn't >>>foo = a.x correspond exactly to >>>foo = getattr(a,'x') #? With that in mind, the logical action for >>>a.x = f(a.x) is >>>setattr(a,'x',f(a,'x')) #, and since >>>a.x += foo is equal to >>>a.x = A.__iadd__(a.x,foo) # (at least for new-style classes >>> # that have __iadd__ defined. Otherwise, it falls back on >>> # __add__(self,other) to return a new object, making this >>> # evern more clear), why shouldn't this translate into >>>setattr(a,'x',A.__iadd__(getattr(a,'x'),foo)) #? Looking at it this way, it's obvious that the setattr and getattr may do different things, if the programmer understands that "instances (can) look up object attributes, and (always) set instance attributes." In fact, it is always the case (so far as I can quickly check) that += ends up setting an instance attribute. Consider this code: >>> class foo: >>> x = [5] >>> a = foo() >>> a += [6] >>> a.x [5,6] >>> foo.x [5,6] >>> foo.x = [7] >>> a.x [5,6] In truth, this all does make perfect sense -- if you consider class variables mostly good for "setting defaults" on instances. From kylotan at gmail.com Wed Nov 2 08:59:18 2005 From: kylotan at gmail.com (Ben Sizer) Date: 2 Nov 2005 05:59:18 -0800 Subject: Python's website does a great disservice to the language In-Reply-To: <87pspjw7b4.fsf@lucien.dreaming> References: <1130926738.909385.138190@g49g2000cwa.googlegroups.com> <87pspjw7b4.fsf@lucien.dreaming> Message-ID: <1130939958.355064.154980@g49g2000cwa.googlegroups.com> Bj?rn Lindstr?m wrote: > Actually it does set some fonts ("avantgarde" and > "lucidasomethignorother") as first choices. I guess you, like me, and > probably most people in here, doesn't have those installed. As far as I can tell, those fonts are only set for 'pre' and 'h' tags. -- Ben Sizer From istvan.albert at gmail.com Tue Nov 29 15:53:26 2005 From: istvan.albert at gmail.com (Istvan Albert) Date: 29 Nov 2005 12:53:26 -0800 Subject: CGI question References: Message-ID: <1133297606.952324.251210@g44g2000cwa.googlegroups.com> See urlparse: http://www.python.org/doc/current/lib/module-urlparse.html From edreamleo at charter.net Thu Nov 3 12:17:28 2005 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 3 Nov 2005 11:17:28 -0600 Subject: ANN: Leo 4.4a2 released Message-ID: Leo 4.4 alpha 2 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 To learn about Leo, see: http://webpages.charter.net/edreamleo/intro.html Leo 4.4a2 contains some of the most important changes to Leo's look (tabbed log) and feel (per-pane key bindings) in Leo's history. This release is a big step forward in meeting the following goals: - To allow Emacs and Vim users to retain their present 'finger habits'. - To support an emacs-like minibuffer, complete with typing completion. - To make Leo usable without a mouse (mouseless Leo). This is an alpha release: there are known bugs (see below). However, you should be able to use this version safely. In particular, the Leo 4.4 code base recovers from errors more reliably than all previous versions. The highlights of Leo 4.4: ---------------------------------- - An Emacs-like mini-buffer: you can now execute any command by typing its long name. Support for tab completion. - A tabbed log pane. The Find and Spell Check commands now use tabs instead of dialogs, making those commands much easier to use. Plugins or scripts can easily create new tabs. The 'Completion' tab shows possible typing completions. - Support for almost all commands in the Emacs Cmds menu, including cursor and screen movement, basic character, word and paragraph manipulation, and commands to manipulate buffers, the kill ring, regions and rectangles. - Per-pane key bindings. You can bind shortcuts to multiple commands depending on which of Leo's panes presently has focus. For example, you can use arrow keys to move nodes in the outline pane, while retaining their defaults in Leo's body pane. Per-pane key binds are essential for mouseless Leo. - @command nodes create minibuffer commands. You can bind key shortcuts to @button and @command nodes. - A rewrite of Leo's keystroke handling. In particular, Leo handles key events immediately rather than queuing them for idle time. - Several fixes made to the 4.3 code base. In particular, Leo 4.4 continues after crashes much more reliably than in any previous version. Known bugs in Leo 4.4a2 ----------------------- - (Reported after a2 released): Canceling the Open dialog crashes. Leo recovers without incident. - Typing in the minibuffer doesn't work if the focus is 'in limbo', that is, not in the outline, body or log panes. Leo usually forces the focus to the body pane in such cases, but the code doesn't always work and sometimes causes other problems. This *minor* annoyance will be fixed completely in Leo 4.4a3. - Several minibuffer commands do not work; many new features lack unit tests. Coming in later releases of Leo 4.4: ------------------------------------ - More support for mouseless Leo. There will be commands to manipulate all aspects of Leo using commands, so your fingers will never have to leave the keyboard. - Support for Vim and other 'plain-key' input modes. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward K. Ream November 2, 2005 -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From wagner at inet-nb.de Tue Nov 15 10:13:45 2005 From: wagner at inet-nb.de (Stefanie Wagner) Date: 15 Nov 2005 07:13:45 -0800 Subject: wxpython and EVT_KILL_FOCUS Message-ID: <1132067625.490060.304310@g43g2000cwa.googlegroups.com> Hello, I am fighting with EVT_KILL_FOCUS for quite a time now and I don't succeed at all. Situation: If a user leaves a textfield the entered information should be checked and an additional window should be opened to make a search possible to complete the entry. Basic solution: def __init__(...): ... self.artikelnrBox = wxTextCtrl(self.bestelldialog, -1, artikelnr, wxPoint(60,290), wxSize(60, -1)) ... EVT_KILL_FOCUS(self.artikelnrBox, self.OnArtikel) ... def OnArtikel(self,event): event.Skip() .... artikelnr = self.artikelnrBox.GetValue().strip() ... dialog = dialog_stamm_artikel.ArtikelSucheDialog(self.bestelldialog,artikelnr) ergebnis,artikelid = dialog.GetValues() dialog.Destroy() ... Problem: If I don't open any dialog everything works fine. But if there is a dialog around the window opens, I can count to two and the whole application crashes. The error message is: (gui.py:29768): Gtk-WARNING **: GtkEntry - did not receive focus-out-event. If you connect a handler to this signal, it must return FALSE so the entry gets the event as well Gtk-ERROR **: file gtkentry.c: line 4919 (blink_cb): assertion failed: (GTK_WIDGET_HAS_FOCUS (entry)) aborting... Reason of the problem: I found a very good description for the reason: > This is a lot easier to understand with a timeline: > - focus into GtkEntry > - GtkEntry installs timeout for cursor blinking > - focus out of entry > - GtkEntry emits focus-out-event > - your handler runs **before the default handler**. > - your handler traps exception and creates dialog box > - dialog box runs nested event loop > - event processing continues, focus goes to another widget > - entry's cursor blink timeout is still installed, and runs again. > entry does not have focus, but timeout has run, so the widget > is in an invalid state and calls g_error() with a nastygram. > - default handler runs, uninstalls cursor blink timeout > The problem is that you're allowing the event loop to run in your handler for focus-out. Ok, if I use EVT_KILL_FOCUS the event has not finished completly, this timeout is still around. That's ok with me but I thought this is what event.Skip() is for, to call the standard handler. Solution: And there I am. event.Skip() doesn't help at all. And the other source gives the following suggestion: > a) use signal_connect_after to have your handler run *after* the default handler for focus-out-event instead of before. > b) leave the signal connected normally, but in your "catch" block, instead of running the dialog right then, defer it with an idle, like this: I couldn't find signal_connect_after anywhere in wxpython and I don't know how to use idle in this case. And I have the problem more than once (every time a have an error message in other EVT_KILL_FOCUS routines). There must be some solution to use EVT_KILL_FOCUS and a dialog without killing the application. Please help! Steffi From rutt at bmi.osu.edu Wed Nov 2 12:57:26 2005 From: rutt at bmi.osu.edu (Benjamin Rutt) Date: Wed, 02 Nov 2005 12:57:26 -0500 Subject: is open(...).read() a resource leak? Message-ID: <5vk6froruh.fsf@akron.bmi.ohio-state.edu> If I did the following in an infinite loop, would the host system/user account soon run out of file descriptors? (I'm thinking no, since I'd imagine that a file object has a __del__-like method that will call close() automatically since it goes out of scope): open('/home/rutt/.bashrc,'r').read() Can anyone confirm that I'm right in seeing (1) the file object's actual destructor is below and seems to call a close method if not already done (at the <-- indicated lines) and (2) the method table that makes this method the destructor? Both are in Objects/fileobject.c in python sources. (1) static void file_dealloc(PyFileObject *f) { if (f->f_fp != NULL && f->f_close != NULL) { <---- Py_BEGIN_ALLOW_THREADS (*f->f_close)(f->f_fp); <---- Py_END_ALLOW_THREADS } Py_XDECREF(f->f_name); Py_XDECREF(f->f_mode); Py_XDECREF(f->f_encoding); drop_readahead(f); f->ob_type->tp_free((PyObject *)f); } (2) PyTypeObject PyFile_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, "file", sizeof(PyFileObject), 0, (destructor)file_dealloc, /* tp_dealloc */ <---- 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc)file_repr, /* tp_repr */ 0, /* tp_as_number */ [...] Thanks, -- Benjamin Rutt From mwm at mired.org Wed Nov 16 18:42:46 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 16 Nov 2005 18:42:46 -0500 Subject: JMS yet again References: <1132136625.101816.40520@g49g2000cwa.googlegroups.com> Message-ID: <86ek5gnoqx.fsf@bhuda.mired.org> Ben Finney writes: > Aahz wrote: >> Am I the only person who immediately thought of Babylon 5 and >> wondered if I was in the wrong newsgroup? > > I plead guilty. Well, I thought of Crusade. But I'd just finished watching those. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From eternalsquire at comcast.net Sun Nov 13 15:54:30 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 13 Nov 2005 12:54:30 -0800 Subject: Copyright [was Re: Python obfuscation] In-Reply-To: <868xvt147q.fsf@bhuda.mired.org> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <1131859100.890118.317030@g14g2000cwa.googlegroups.com> <868xvt147q.fsf@bhuda.mired.org> Message-ID: <1131915269.961526.93330@g49g2000cwa.googlegroups.com> >As far as I know, only one country ever claimed to have that, so your >"we" only applies to citizens of that country, and not to everyone who >may be reading the letter - and the status of the person you quoted >but did not attribute is unclear. It applies to not only the US, which explicitly has "We The People" in our Constitution, but to all other countries who model on republican systems: Japan, Germany, France, South Korea, Taiwan, and more. >Further, recent evidence is that this is no longer true in that >country, assuming it ever was. Wow, how Machiaviellian. >Copyright by itself does not pay >the rent, put food on the table or put people through college. It's >strong enough to be do that *if* the public values what you create >enough and *if* you work hard enough at marketing it and *if* you >produce enough. Those are some mighty big ifs. Yes, profitable innovation is 1 percent inspiration plus 99 percent persperation. >Maybe "the people" you're talking about above are "the rich corporations >with the congresscritters in their pockets." But that's hardly "the >majority". It sometimes works that way, unfortunately. But at least we can vote the bastards out when we hear of such things. >You apparently think that taking the opportunity for the creator to be >rewarded for their efforts is ok if you deride other people who do >that very thing. And in what way is piracy a form of creation? >So what's the difference between the RIAA and a >pirate who publicly points out that what the RIAA is up to? The difference is that the RIAA does not copy software without the copyright holder's consent. From bonono at gmail.com Sun Nov 20 19:00:37 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 16:00:37 -0800 Subject: Underscores in Python numbers In-Reply-To: <7LKdnRwmT9dzTh3eRVn-uQ@powergate.ca> References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> <1132476670.992305.106250@o13g2000cwo.googlegroups.com> <1132497336.495571.142540@g43g2000cwa.googlegroups.com> <7LKdnRwmT9dzTh3eRVn-uQ@powergate.ca> Message-ID: <1132531237.193719.8890@z14g2000cwz.googlegroups.com> Peter Hansen wrote: > bonono at gmail.com wrote: > > Peter Hansen wrote: > > > >>But why would anyone want to create numeric literals for credit card > >>numbers? > >> > > May be for space saving ? But storage space being so cheap, this is not > > a very good reason, but still a reason. > > Space saving where? Why would you have any credit card numbers stored > in any application? Even a credit card company isn't going to write > code that has the numbers stored as *literals*! I am not the one asking for it, only guessing the reason and credit card company does save it in the database. So saving as half byte numeric(or 64 bit integer) does save a bit of space comparing with string. > > There's only one place I can think of right now where you might want > that: in automated tests for code that processes credit card numbers. > And you definitely do not need to "save space" in that situation... > That usually don't need it as one big number but usually more easier to code if treating as string(like checksum), something like: for digits in cc: checksum += int(digits) From jeremy.d.brewer at gmail.com Wed Nov 23 01:21:44 2005 From: jeremy.d.brewer at gmail.com (jbrewer) Date: 22 Nov 2005 22:21:44 -0800 Subject: PIL FITs image decoder References: <1132681491.921657.291860@z14g2000cwz.googlegroups.com> <1132684114.165243.33310@g43g2000cwa.googlegroups.com> <1132696821.259981.199190@g47g2000cwa.googlegroups.com> Message-ID: <1132726904.882246.249870@g14g2000cwa.googlegroups.com> I tried following your simple example (I already had something similar) but with no luck. I'm completely stumped as to why this doesn't work. I even tried manually scaling the data to be in the range 0-255 out of desperation. The data is definitely contiguous and 32 bit floating point. At this point I've tried everything I can think of. Any ideas? Jeremy # open the fits file using pyfits fits = pyfits.open(fitsfile) xsize, ysize = fits[0].data.shape data = fits[0].data.astype("Float32") fits.close() # now create an image object image = Image.frombuffer("F", (xsize, ysize), data) # scale the data be 256 bit unsigned integers #int_data = numarray.zeros((xsize, ysize)).astype("UInt8") #min = data.min() #max = data.max() #for i in arange(xsize): # for j in arange(ysize): # scaled_value = (data[i, j] - min) * (255.0 / (max - min)) # int_data[i, j] = int(scaled_value + 0.5) #image = Image.frombuffer("L", (xsize, ysize), int_data) From fredrik at pythonware.com Tue Nov 8 01:26:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Nov 2005 07:26:06 +0100 Subject: Returning a value from a Tk dialog References: <0qqdnfVlLqpIYPLenZ2dnUVZ_tudnZ2d@comcast.com> Message-ID: Gordon Airporte wrote: > The dialogs in tkColorChooser, tkFileDialog, etc. return useful values > from their creation somehow, so I can do stuff like this: > > filename = tkFileDialog.askopenfilename( master=self ) > > I would like to make a Yes/No/Cancel dialog that can be used the same > way (returning 1/0/-1), but I just cannot figure out how to do it. At > best I've been able to get some kind of instance id from the object. How > does this work? if you want a message box, use the tkMessageBox module. there's no ready-made wrapper for yes/no/cancel, but you can call the _show directly: import tkMessageBox result = tkMessageBox._show( "title", "message", tkMessageBox.QUESTION, tkMessageBox.YESNOCANCEL ) result will be tkMessageBox.YES, tkMessageBox.NO, or tkMessageBox.CANCEL. if result == tkMessageBox.YES: return 1 if result == tkMessageNox.No: return 0 return -1 # assume cancel From gaudetteje at gmail.com Wed Nov 30 12:22:08 2005 From: gaudetteje at gmail.com (NavyJay) Date: 30 Nov 2005 09:22:08 -0800 Subject: Automate decryption using GnuPGInterface In-Reply-To: <1133371012.587954.282540@g49g2000cwa.googlegroups.com> References: <1133371012.587954.282540@g49g2000cwa.googlegroups.com> Message-ID: <1133371328.295763.61150@g44g2000cwa.googlegroups.com> Are you able to run a dummy Python script using crontabs? For troubleshooting purposes, I would verify this before trying to debug my code. Check your permissions, paths, etc. Can you post your entry into cron? What exactly happens when it "blows up"? From mwm at mired.org Tue Nov 22 23:28:02 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 22 Nov 2005 23:28:02 -0500 Subject: Anyway to clarify this code? (dictionaries) References: <1132711108.860281.59900@g49g2000cwa.googlegroups.com> <86ek5812a3.fsf@bhuda.mired.org> <1132716816.034104.325340@o13g2000cwo.googlegroups.com> Message-ID: <86sltoyoml.fsf@bhuda.mired.org> "bonono at gmail.com" writes: > Mike Meyer wrote: >> def my_search(another, keys, x): >> return dict([[k, v] for k, v in another.items() if v >= x and k in keys]) >> But then you're looking through all the keys in another, and searching >> through keys multiple times, which probably adds up to a lot more >> wasted work than indexing another twice. > Would you mind clarify ? Do you mean "k in keys" is a scan rather than > a lookup ? I find it to be pretty clean and straight forward. I assumed keys was a simple sequence of some kind, because you passed it to fromkeys. I guess it could be set or a dictionary, in which case "k in keys" would be a lookup. Were you trying to force a lookup by creating a dict with the keys from k via fromkeys? If so, using a set would have the same effect, and be a lot clearer: temp = set(keys) return dict([[k, v] for k, v in another.items() if v >= x and k in temp]) > I think one way or another, one need to loop through one of them, then > index search the other. It may help a bit to take the len() and loop > through the shorter one. First, remember the warnings about premature optimization. The following might be worth looking into: use = set(another) - set(keys) return dict([[k, another[k]] for k in use if another[k] >= x] Though I still think I prefer the longhand version: out = dict() for key in set(another) - set(keys): if another[k] >= x: out[k] = another[k] The set difference is still going to loop through one and do lookups in the other, but it'll happen in C instead of Python. Unless your lists are *very* long, the performance differences will probably negligible, and are liable to change as you change the underlying platform. So I'd recommend you choose the form that's mostt readable to you, and go with that. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From just_another_guy287 at yahoo.com Tue Nov 22 21:44:12 2005 From: just_another_guy287 at yahoo.com (Warren Francis) Date: Tue, 22 Nov 2005 21:44:12 -0500 Subject: Any royal road to Bezier curves...? References: Message-ID: > If you go right to the foot of my code, you'll find a simple test routine, > which shows you the skeleton of how to drive the code. Oops... my request just got that much more pitiful. :-) Thanks for the help. Warren From fredrik at pythonware.com Mon Nov 7 04:24:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 7 Nov 2005 10:24:35 +0100 Subject: pls help me with strange result References: <1131353588.072795.320660@g14g2000cwa.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > db = Sybase.connect(DSN) .... > ... > def x_dml(SQL,conn): > ''' Connects to database specified, exec the SQL and returns > value''' > try: > c = conn.cursor() > try: > c.execute(SQL) > res = c.rowcount > conn.commit() > return res > except : > return -1 > except: > return -2 > stmt = """ > update table1 set col = '%s' where col = '%s' > update table2 set col = '%s' where col = '%s' > """ % ( blah, blah ,blah,blah) > > try: > r = x_dml(stmt,db) > if r > 0: > print r > except: > print "some error" > > > Whenever i execute x_dml , it raise the exeception what exception? to see what really happens in there, temporarily change *all* "except:" clauses to except "foo": and run your script again, and let us know what it prints. when you've done that, change the except clauses to except Sybase.Error: (you should only use catch-all except clauses if you report the error in some other way; e.g. by inspecting sys.exc_info, or by using the traceback module. using catch-all to hide errors from yourself is a rather lousy idea) if you want to do things in a more pythonic way, remove *both* try-except clauses from the x_dml function, and leave it to the caller to use try-except to look for errors: import Sybase as DB conn = DB.connect(DSN) .... def x_dml(SQL,conn): c = conn.cursor() c.execute(SQL) res = c.rowcount conn.commit() return res ... try: r = x_dml(stmt,db) except DB.Error, v: print "some error", v else: print r, "rows updated" From pinkfloydhomer at gmail.com Tue Nov 8 04:04:13 2005 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: 8 Nov 2005 01:04:13 -0800 Subject: Addressing the last element of a list In-Reply-To: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> Message-ID: <1131440653.015221.324460@g43g2000cwa.googlegroups.com> Or alternatively: Is there a way to make reference to the last element of a list, to use as a shorthand: ref := &lst[len(lst) - 1] # I know syntax is wrong, but you get the idea and then using the last element of the list by (assuming the element is a dict): ref["foo"] = 42 ref["bar"] = "Ni!" etc. /David From aisaac0 at verizon.net Wed Nov 23 11:51:41 2005 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 23 Nov 2005 16:51:41 GMT Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <1132708265.941224.186550@g44g2000cwa.googlegroups.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:dm263o$b8b$02$1 at news.t-online.com... > - allows arbitrary iterables, not sequences only > - smaller memory footprint if sequential access to the items is sufficient Sure; I meant aside from that. > - fewer special cases, therefore > - less error prone, e. g. > + does your implementation work for functions with > f(a, b) != f(b, a)? See news:Mzpgf.12794$NN2.4089 at trnddc02 > + won't users be surprised that > cumreduce(f, [1]) == cumreduce(f, [], 1) > != > cumreduce(f, [0]) == cumreduce(f, [], 0) THANKS! > Of course nothing can beat a plain old for loop in terms of readability and > -- most likely -- speed. OK. Thanks, Alan Isaac From holovaty at gmail.com Wed Nov 16 11:03:58 2005 From: holovaty at gmail.com (Adrian Holovaty) Date: 16 Nov 2005 08:03:58 -0800 Subject: ANN: Django 0.90 Message-ID: <1132157038.456578.253670@g49g2000cwa.googlegroups.com> After a months-long "pre-release" period, we're pleased to announce the first release of Django, the Web framework for perfectionists (with deadlines). Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It lets you write high-quality Web apps very quickly, with very little code. It gives you: * An object-relational mapper, which currently works with PostgreSQL, MySQL and SQLite. (Oracle and MS-SQL support are coming.) This lets you query databases in Python; there's no need to write SQL if you don't want to. * A template system. * A beautiful, production-ready admin interface -- for free. * Full internationalization (i18n) support. * A super-cool community! * An RSS/Atom-producing framework. * Tons of other niceties, such as generic views (which abstract common Web-development patterns), based on several years' worth of solving Real Problems in the Real World. Django has been used on production sites -- lawrence.com, ljworld.com, 6newslawrence.com, kusports.com, visitlawrence.com -- since late 2003. It also powers chicagocrime.org and a host of other sites all over the world. See http://code.djangoproject.com/wiki/DjangoPoweredSites . This release is version 0.90. Our goal is to wrap up remaining changes for 1.0 in the coming weeks/month, and release 1.0 with a guarantee of backwards compatibility. There's not yet a guarantee of backwards compatibility between releases. http://www.djangoproject.com/ http://www.djangoproject.com/download/ Enjoy! Adrian -- Adrian Holovaty holovaty.com | djangoproject.com | chicagocrime.org From robbyd at u20.org Fri Nov 4 15:43:30 2005 From: robbyd at u20.org (Robby Dermody) Date: Fri, 04 Nov 2005 15:43:30 -0500 Subject: python gc performance in large apps In-Reply-To: <43594BD5.7050104@u20.org> References: <43594BD5.7050104@u20.org> Message-ID: <436BC7F2.7020902@u20.org> Hey guys, An update (along with a request for paid help at the end): Over the past week and a half I've improved the memory usage situation by quite a bit. Going to python 2.4, linux kernel 2.6, twisted 2.0 and altering some code have reduced the severity by an order of a magnitude. However, on a simulated call center environment (constant 50 conversations, switching every 300 seconds) the director component still consumes an average of 1MB more per hour and the harvester is taking an average of 4MB more per hour. With the director, 2/3 of this is resident (1/3 in swap). With the harvester, about 88% of this is resident (~ 12% in swap). After looking into things more, based on the helpful input I got from the very intelligent individuals who responded to the thread, I know a few more things: -Neither component has any uncollectable trash problems. gc.garbage never has any items after a full collection (and there are never any uncollectable cycles). -Running the harvester through valgrind under very light load showed 2 minor memory leaks of my making in the "harvester core" (pyrex code). Both were fixed. Subsequent runs yielded nothing in my pyrex modules. -len(gc.get_objects()) will show linearly increasing counts over time with the director (that match the curve of the director's memory usage exactly), but with the harvester, the object count doesn't increase over time (although memory usage does). This might mean that we are dealing with two separate problems on each component....uncollected object count growth on the director, and something else on the harvester. ...OR the harvester may have an object count growth problem as well, it might just be in a C module in a place not visible to gc.get_objects() ? -I have some code that looks through gc.get_objects() to find the 10 biggest lists and dicts, and I see no tell tale signs there (nothing growing out of control). -Running the harvester on python 2.4 (and 2.5, same results) compiled with COUNT_ALLOCS reported some interesting results with lists and dicts that may explain some of the memory usage: t = 0: list alloced: 19167, freed: 8231, max in use: 10937 dict alloced: 47943, freed: 34108, max in use: 13837 t = 120 seconds (1st run after being fully initialized): list alloced: 2394620, freed: 17565, max in use: 2377056 dict alloced: 2447968, freed: 67999, max in use: 2379969 t = ~20 hours: list alloced: 834032375, freed: 4625810, max in use: 829406570 dict alloced: 845149422, freed: 15715727, max in use: 829433695 The numbers for the other types mostly looked normal, but these two kept growing after every subsequent call to sys.getcounts(). I have not yet run the director with COUNT_ALLOCS yet, due to a problem dynamically loading in the kinterbasdb (Firebird SQL interface) module. -Memory usage is constant on both components when x conversations are started but never stopped. The code that handles that is just in the harvester, and is in pure C (in pyrex)... when a conversation is started or stopped, etc, python and pyrex code in both components runs, and things like twisted PB are used. This 1MB/hour and 4MB/hour increase is happening just by having the active convos stop and restart, but I can't see what would cause that kind of growth. -Running on Python 2.5 (latest CVS HEAD) didn't change anything At this point I think I've done all that I can do on my own with this, given my meager level of knowledge in this field :). I would be interested in retaining some professional help to see if, working together, we can trace down some likely culprits. I am also very interested in learning more on how to avoid these problems in the future, if they are my doing. I doubt we can remove all the memory problems, but if we can get this down by another 150 - 200%, that will be good enough for me. With that said, I would be prepared to pay someone to help me out with this problem (and offer tips on improving the code... I am very interested in improving both my skills and the code's quality). The director and harvester programs can both run on a single box running Linux kernel 2.6, python 2.4. There aren't that many dependencies, and I have a simple loadtester program that can be used to stress test the environment. I've also already written a module for both components that logs a bunch of useful memory usage statistics out to disk at whatever interval desired. I would be looking for an experienced python developer with the following knowledge: -python internals, python "best practices" -twisted framework -pyrex (and python C API) -previous experience fixing similar problems in python If anyone is interested in helping out, or know someone who might be interested, please get back to me with your asking rate (hourly, or by the project if you prefer). We can go from there. Also, as this project is starting to generate revenue, I will be hiring someone full time soon to take over primary development. This person doesn't need to be a python god. Someone with 2-3+ years of experience with python, subversion, etc. would be good enough, as long as they are a geek at heart, intelligent and adaptive, passionate about this kind of work and self motivated. Even a bright recent college grad with open source experience under his/her belt would be fine. If anyone knows of anyone who might love this kind of job, let me know. This is truly a _very_ interesting product. Robby Robby Dermody wrote: > Hey guys (thus begins a book of a post :), > > I'm in the process of writing a commercial VoIP call monitoring and > recording application suite in python and pyrex. Basically, this > software sits in a VoIP callcenter-type environment (complete with agent > phones and VoIP servers), sniffs voice data off of the network, and > allows users to listen into calls. It can record calls as well. The > project is about a year and 3 months in the making and lately the > codebase has stabilized enough to where it can be used by some of our > clients. The entire project has about 37,000 lines of python and pyrex > code (along with 1-2K lines of unrelated java code). > > Now, some disjointed rambling about the architecture of this software. > This software has two long-running server-type components. One > component, the "director" application, is written in pure python and > makes use of the twisted, nevow, and kinterbasdb libraries (which I > realize link to some C extensions). The other component, the > "harvester", is a mixture of python and pyrex, and makes use of the > twisted library, along with using the C libs libpcap and glib on the > pyrex end. Basically, the director is the "master" component. A single > director process interacts with users of the system through a web and/or > pygtk client application interface and can coordinate 1 to n harvesters > spread about the world. The harvester is the "heavy lifter" component > that sniffs the network traffic and sifts out the voice and signalling > data. It then updates the director of call status changes, and can > provide users of the system access to the data. It records the data to > disk as well. The scalibility of this thing is really cool: given a > single director sitting somewhere coordinating the list of agents, > multiple harvester can be placed anywhere there is voice traffic. A user > that logs into the director can end up seeing the activity of all of > these seperate voice networks presented like a single giant mesh. > > Overall, I have been very pleased with python and the 3rd party > libraries that I use (twisted, nevow, kinterbasdb and pygtk). It is a > joy to program with, and I think the python community has done a fine > job. However, as I have been running the software lately and profiling > its memory usage, the one and only Big Problem I have seen is that of > the memory usage. Ideally, the server application(s) should be able to > run indefinitely, but from the results I'm seeing I will end up > exhausting the memory on a 2 GB machine in 2 to 3 days of heavy load. > > Now normally I would not raise up an issue like this on this list, but > based on the conversations held on this list lately, and the work done > by Evan Jones (http://evanjones.ca/python-memory.html), I am led to > believe that this memory usage -- while partially due to some probably > leaks in my program -- is largely due to the current python gc. I have > some graphs I made to show the extent of this memory usage growth: > > http://public.robbyd.fastmail.fm/iq-graph1.gif > > http://public.robbyd.fastmail.fm/iq-graph-director-rss.gif > > http://public.robbyd.fastmail.fm/iq-graph-harv-rss.gif > > The preceding three diagrams are the result of running the 1 director > process and 1 harvester process on the same machine for about 48 hours. > This is the most basic configuration of this software. I was running > this application through /usr/bin/python (CPython) on a Debian 'testing' > box running Linux 2.4 with 2GB of memory and Python version 2.3.5. > During that time, I gathered the resident and virtual memory size of > each component at 120 second intervals. I then imported this data into > MINITAB and did some plots. The first one is a graph of the resident > (RSS) and virtual memory usage of the two applications. The second one > is a zoomed in graph of the director's resident memory usage (complete > with a best fit quadratic), and the 3rd one is a zoomed in graph of the > harvester's resident memory usage. > > To give you an idea of the network load these apps were undergoing > during this sampling time, by the time 48 hours had passed, the > harvester had gathered and parsed about 900 million packets. During the > day there will be 50-70 agents talking. This number goes to 10-30 at night. > > In the diagrams above, one can see the night-day separation clearly. At > night, the memory usage growth seemed to all but stop, but with the > increased call volume of the day, it started shooting off again. When I > first started gathering this data, I was hoping for a logarithmic curve, > but at least after 48 hours, it looks like the usage increase is almost > linear. (Although logarithmic may still be the case after it exceeds a > gig or two of used memory. :) I'm not sure if this is something that I > should expect from the current gc, and when it would stop. > > Now, as I stated above, I am certain that at least some of this > increased memory usage is due to either un-collectable objects in the > python code, or memory leaks in the pyrex code (where I make some use of > malloc/free). I am working on finding and removing these issues, but > from what I've seen with the help of gc UNCOLLECTABLE traces, there are > not many un-collectable reference issues at least. Yes, there are some > but definitely not enough to justify growth like I am seeing. The pyrex > side should not be leaking too much, I'm very good about freeing what I > allocate in pyrex/C land. I will be running that linked to a memory leak > finding library in the next few days. Past the code reviews I've done, > what makes me think that I don't have any *wild* leaks going on at least > with the pyrex code is that I am seeing the same type of growth patterns > in both apps, and I don't use any pyrex with the director. Yes, the > harvester is consuming much more memory, but it also does the majority > of the heavy lifting. > > I am alright with the app not freeing all the memory it can between high > and low activity times, but what puzzles me is how the memory usage just > keeps on growing and growing. Will it ever stop? > > What I would like to know if others on this list have had similar > problems with python's gc in long running, larger python applications. > Am I crazy or is this a real problem with python's gc itself? If it's a > python gc issue, then it's my opinion that we will need to enhance the > gc before python can really gain leverage as a language suitable for > "enterprise-class" applications. I have surprised many other programmers > that I'm writing an application like this in python/pyrex that works > just as well and even more efficiently than the C/C++/Java competitors. > The only thing I have left to show is that the app lasts as long between > restarts. ;) > > > Robby From steve at holdenweb.com Mon Nov 14 14:35:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 14 Nov 2005 19:35:59 +0000 Subject: more newbie help needed In-Reply-To: <20051114192046.64486.qmail@web35901.mail.mud.yahoo.com> References: <20051114192046.64486.qmail@web35901.mail.mud.yahoo.com> Message-ID: john boy wrote: > using the following program: > > fruit = "banana" > index = 0 > while index < len (fruit): > letter = fruit[index-1] > print letter > index= index -1 > > this program is supposed to spell "banana" backwards and in a vertical patern...it does this....but after spelling "banana" it gives an error message: > refering to line 4: letter = fruit[index-1] > states that it is an IndexError and the string index is out of range > Anybody know how to fix this? > Change the termination condition on your loop. If you print out the values of index as the loop goes round you'll see you are printing characters whose index values are -1, -2, ..., -6 Unfortunately -7 is less than -6, so your loop keeps on going, with the results you observe. Note, however, that there are more pythonic ways to perform this task. You might try: for index in range(len(fruit)): letter = fruit[-index-1] print letter as one example. I'm sure other readers will have their own ways to do this, many of them more elegant. 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 bokr at oz.net Fri Nov 11 02:41:10 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 11 Nov 2005 07:41:10 GMT Subject: Recompile AST? References: <1131657716.197347.167740@g47g2000cwa.googlegroups.com> <4373d1cb.156169219@news.oz.net> <1131667676.954609.211800@o13g2000cwo.googlegroups.com> Message-ID: <43744a37.186997287@news.oz.net> On 10 Nov 2005 16:07:56 -0800, "Paul Boddie" wrote: >Bengt Richter wrote: >> I've also posted sporadic musings about the possibilities for AST-transforming >> custom import functions to do optimizations and macros and special forms etc., >> but no one seemed much interested (or maybe they quietly went off to do >> something of their own ;-) > >For an example of AST transformations, take a look at the >libxml2macro.py script in the libxml2dom distribution [1]: it contains >code which transforms ASTs based on simple rules (changing method calls >to function calls) as well as the magic sequence of instructions to >generate .pyc files from ASTs. Originally, the analysis distribution >[2] also compiled modified ASTs to Python bytecode, but such activities >didn't really fit in with the goals of that particular project. > >Paul > >[1] http://www.python.org/pypi/libxml2dom >[2] http://www.python.org/pypi/analysis > Thanks for the links. I downloaded the tgzs but it will be a while before I get into anything ;-) Regards, Bengt Richter From cjw at sympatico.ca Thu Nov 10 13:18:30 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 10 Nov 2005 13:18:30 -0500 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <1h5rz3b.1mpfn381yc51d9N%aleax@mail.comcast.net> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594460.098689.64140@g43g2000cwa.googlegroups.com> <1h5rz3b.1mpfn381yc51d9N%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > George Sakkis wrote: > ... > >>>>FP functions like dropwhile/takewhile etc. >>> >>>No way -- the itertools module is and remains a PRECIOUS resource. >>>If you want an iterator rather than a list, itertools.ifilter is quite >>>appropriate here. >> >>What about the future of itertools in python 3K ? IIRC, several >>functions and methods that currently return lists are going to return >>iterators. Could this imply that itertools.(imap/ifilter/izip) will >>take the place of map/filter/zip as builtins ? > > > I think the builtin namespace shouldn't get too crowded. But what I > think matters little -- what __GvR__ thinks is more important...!-) > > > Alex Are there generally accepted guidelines on what is appropriate for the builtin namespace? Colin W. From fredrik at pythonware.com Thu Nov 3 03:50:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Nov 2005 09:50:47 +0100 Subject: when and how do you use Self? References: <3C5387E42DA62B4EA1F1EBD2DB498381596DE7@usmtm-emh3.USMTM.SPPN.AF.MIL> Message-ID: "Tieche Bruce A MSgt USMTM/AFD" wrote: > Could someone explain (in English) how and when to use self? > > I have been reading, and haven't found a good example/explanation consider a class C: >>> class C: ... def method(self): ... print self ... >>> C you can create unique instances of this class by "calling" the class itself: >>> a = C() >>> a <__main__.C instance at 0x00925FD0> >>> b = C() >>> b <__main__.C instance at 0x00927030> here, "a" and "b" are two separate objects, that both refer to the same class object, but are otherwise distinct (the cryptic codes are object identities). now, if you call a method on one of those objects, Python will use the method code from the class, but the method will get a reference to the instance as its first argument (self). when you call the method via the "a" object, the method gets a reference to the "a" object as the first argument: >>> a.method() <__main__.C instance at 0x00925FD0> when you call the method via the "b" object, the method gets a reference to the "b" object as the first argument: >>> b.method() <__main__.C instance at 0x00927030> the instance object is usually used to store instance-specific variables (usually known as "attributes" or "members"). an example: >>> class Counter: ... def __init__(self): ... self.value = 0 ... def increment(self): ... self.value = self.value + 1 ... return self.value ... >>> a = Counter() >>> b = Counter() >>> a.increment() 1 >>> a.increment() 2 >>> a.increment() 3 >>> b.increment() 1 (the __init__ method is automatically called for each new instance) you can also access the instance attributes "from the outside": >>> print a.value 3 >>> print b.value 1 for more on this, see: http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 From mde at micah.elliott.name Mon Nov 21 01:45:08 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Sun, 20 Nov 2005 22:45:08 -0800 Subject: best cumulative sum In-Reply-To: <9Qbgf.8204$BC2.5713@trnddc04> References: <9Qbgf.8204$BC2.5713@trnddc04> Message-ID: <20051121064508.GD30817@kitchen.client.attbi.com> On Nov 21, David Isaac wrote: > What's the good way to produce a cumulative sum? >>> import operator >>> x = 1,2,3 >>> reduce(operator.add, x) 6 -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From fredrik at pythonware.com Fri Nov 11 18:08:40 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Nov 2005 00:08:40 +0100 Subject: directory listing References: <14cltzqwyklwl.17i7f7qnfnlh0$.dlg@40tude.net><192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu><1d987df30511111423o572172eay36870d09220233d7@mail.gmail.com><1d987df30511111444m1ddfaca2qcf0acc32e49fc108@mail.gmail.com> <1d987df30511111500j57418032p12c5f30b85aaa594@mail.gmail.com> Message-ID: "Shi Mu" wrote: > print buildList() gets lots of stuffs from my temp directory(there do > exist lots of files). > But why "print x' has nothing? C:\>more script.py import os def buildList( directory='c:\TEMP' ): dirs = [ ] listing = os.listdir(directory) for x in listing: x = os.path.join(directory, x) print x if os.path.isdir(x): dirs.append(x) return dirs print buildList() C:\>dir temp ... 2005-11-12 00:00 . 2005-11-12 00:00 .. 2005-11-12 00:00 20 bacon.dat 2005-11-12 00:00 egg 2005-11-12 00:00 20 spam.txt 2 fil(er) 40 byte 3 katalog(er) 9 818 021 888 byte ledigt C:\>python script.py c:\TEMP\bacon.dat c:\TEMP\egg c:\TEMP\spam.txt ['c:\\TEMP\\egg'] From onurb at xiludom.gro Wed Nov 23 13:18:37 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 23 Nov 2005 19:18:37 +0100 Subject: a new design pattern for Python Library? In-Reply-To: <1132759269.421882.303340@g47g2000cwa.googlegroups.com> References: <1132709883.708313.279720@g44g2000cwa.googlegroups.com> <1132738181.664201.272500@g44g2000cwa.googlegroups.com> <43847514$0$21623$636a15ce@news.free.fr> <1132759269.421882.303340@g47g2000cwa.googlegroups.com> Message-ID: <4384b27e$0$21217$626a54ce@news.free.fr> Ben Sizer wrote: > bruno at modulix wrote: > >>Ben Sizer wrote: >> >>>I'm afraid I've read this paragraph and the code 3 times and I still >>>have no idea what you're trying to convey. >> >> > > > Got anything more constructive to add? > Why do you think I used this tag ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed Nov 9 12:55:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 18:55:00 +0100 Subject: append to non-existing list References: <4371EFBC.1030502@sitasoftware.lu> <4371FA57.40206@sitasoftware.lu><1131549196.831764.104480@g47g2000cwa.googlegroups.com> <86wtjh90ti.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Float doesn't handle implicit conversion to anything but but builtin types. > In particular, it doesn't check to see if the object beinng added has a > __float__ method, and invoke that to do the conversion if it does. that's because __float__ is there to let you control what float() does, not to get automatic type conversion for mixed operations. From barthelemy.georges at neuf.fr Tue Nov 22 12:09:48 2005 From: barthelemy.georges at neuf.fr (Georges Barthelemy) Date: Tue, 22 Nov 2005 11:09:48 -0600 Subject: keys in dictionary References: Message-ID: use (1,2) , (3,4).... "Shi Mu" a ?crit dans le message de news: mailman.987.1132638229.18701.python-list at python.org... I run the following code and got wrong message, but I still want to make [1,2],[4,3] and [6,9] to be keys of the dictionary or change the style a little bit. How to do that? Thanks! >>> p=[[1,2],[4,3],[6,9]] >>> n=dict([(x,[]) for x in p]) Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable >>> From gregor.jan at NOSPAMquick.cz Sat Nov 5 09:34:14 2005 From: gregor.jan at NOSPAMquick.cz (Jan Gregor) Date: Sat, 5 Nov 2005 15:34:14 +0100 Subject: modifying source at runtime - jython case References: Message-ID: In article , Alan Kennedy wrote: > [Jan Gregor] >> I want to apply changes in my source code without stopping jython >> and JVM. Preferable are modifications directly to instances of >> classes. My application is a desktop app using swing library. >> >> Python solutions also interest me. >> >> Solution similiar to "lisp way" is ideal. > > OK, I'll play 20 questions with you. > > How close is the following to what you're thinking? I see. Following try showed me that instances aren't affected by modification in class definition. but this helped x.test = a().test OR x.test = y.test The only thing left is how to initiate modification, it's a swing application and i think interp.exec don't stop until it's done. Maybe somehow call it from jython itself - but need to pass PythonInterpreter instance. Thanks. class a: def test(self): print 'first' x= a() class a: def test(self): print 'second' y= a() x.test() y.test() > > begin SelfMod.java ------------------------------------------- > //************************************************************ > import org.python.util.PythonInterpreter; > import org.python.core.*; > > class SelfMod > { > > static String my_class_source = > "class MyJyClass:\n" + > " def hello(self):\n" + > " print 'Hello World!'\n"; > > static String create_instance = "my_instance = MyJyClass()\n"; > > static String invoke_hello = "my_instance.hello()"; > > static String overwrite_meth = > "def goodbye():\n"+ > " print 'Goodbye world!'\n" + > "\n" + > "my_instance.hello = goodbye\n"; > > public static void main ( String args[] ) > { > PythonInterpreter interp = new PythonInterpreter(); > interp.exec(my_class_source); > interp.exec(create_instance); > interp.exec(invoke_hello); > interp.exec(overwrite_meth); > interp.exec(invoke_hello); > } > > } > //************************************************************ > end SelfMod.java --------------------------------------------- > > need-to-complete-my-coursework-for-telepathy-101-ly y'rs > From fuzzyman at gmail.com Mon Nov 21 10:10:57 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Nov 2005 07:10:57 -0800 Subject: Web-based client code execution In-Reply-To: <43813CB6.4030209@redlinepy.com> References: <3u6ngeFvh3v1U1@individual.net> <43813CB6.4030209@redlinepy.com> Message-ID: <1132585857.365884.74930@z14g2000cwz.googlegroups.com> Paul Watson wrote: > John J. Lee wrote: [snip..] > I appreciate your long list of references. For this task, I think the > first answer may have to be the one with which to go. A standard > application that talks through port 80 and perhaps can use proxies. > > My desire to have the code distributed through a web page is just to > ensure that the user is running the correct version and has not hacked > it in any way. I suppose I can checksum the local client application > and compare it with what is on the server. Then, make a way to > update... ARGH! > If you can run it as a client application (i.e. not through the browser but still across the internet) - then this all seems quite easy to achieve. It also allows you to access the local filesystem without dropping out of Python or using ActiveX objects. If you know the version of Python the machines are using (or create a loader program using py2exe) then you only need dsitribute the 'pyc' bytecode files. (Making it *much* harder to hack for the average user). I don't know if anyone has released an 'auto-update' framework for applications, but it would be a nice project. I guess each time it's needed the requirements will be slightly different though - but there are a lot of general principles. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From samrobertsmith at gmail.com Sat Nov 12 06:44:22 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 03:44:22 -0800 Subject: about array,arange In-Reply-To: References: <1d987df30511120252w3b07b187l71db482bffe35a11@mail.gmail.com> Message-ID: <1d987df30511120344t7d68d5bj5994fc9df651ae7b@mail.gmail.com> On 11/12/05, Robert Kern wrote: > Shi Mu wrote: > > i got confused by the use of array and arange. > > arange get array and range get list, why we need the two different types? > > When you're asking questions about a third-party module, it's a good > idea to mention the module. In this case you're asking about scipy_core > (hopefully) or else numarray or Numeric. > > The answer to your question is that sometimes we need to get largish > arrays (not lists) of consecutive numbers quickly. array(range(N)) is > wasteful of memory and time because it has to create a list of Python > ints that are simply going to be thrown away once we're done converting > to the needed array. > > -- > Robert Kern > rkern at ucsd.edu sorry to forget to mention the module name : Numeric From sybrenUSE at YOURthirdtower.com.imagination Tue Nov 1 14:25:24 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 1 Nov 2005 20:25:24 +0100 Subject: Python's website does a great disservice to the language References: <11mfb4el2kk5b00@corp.supernews.com> <1130869543.556662.81220@z14g2000cwz.googlegroups.com> Message-ID: bearophileHUGS at lycos.com enlightened us with: > I strongly agree with you, the web is full of web sites that are > nice "looking" but have microscopic fixed fonts (against the very > spirit of Html), are full of useless flash, have lots of html > structures nested inside other ones (PHP sites are often like this, > with dirty sourcecode), are difficult/slow to render on differnt/old > browsers (best viewed with its webmaster browser only), are two > times bigger than necessary, etc. Python web site can be improved, > but there are lot of ways to make it worse. I agree to the fullest! I'd rather have a website that I can read and can click through in seconds. 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 scott.daniels at acm.org Fri Nov 18 17:15:06 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 18 Nov 2005 14:15:06 -0800 Subject: How to do "new_variable = (variable) ? True : False;" (php) on python? In-Reply-To: References: <1132338596.452441.139200@g44g2000cwa.googlegroups.com> Message-ID: <437e50f6$1@nntp0.pdx.net> Peter Otten wrote: > Daniel Crespo wrote: >>new_variable = (variable) ? True : False; >>in Python in one line? > new_variable = variable Of course to answer your actual question: new_variable = variable and True or False But you should consider that Peter has given you a better answer than you think. Don't try to force everything to the type you expect, use things as they are; embrace duck-typing. :-) --Scott David Daniels scott.daniels at acm.org From larry.bates at websafe.com Thu Nov 3 17:14:20 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 03 Nov 2005 16:14:20 -0600 Subject: How to read all files in a directory In-Reply-To: References: Message-ID: <436A8BBC.3070703@websafe.com> Not tested: import glob import os path=r'C:\datafiles\' for fileName in glob.glob(os.path.join(path,'*.DAT')): dataFile=open(fileName, 'r').readlines() . . Continue yur code here . -Larry Bates hungbichvo wrote: > Dear All, > > My python application is small. It reads data from a file. > My code is: > fileName = '900128.DAT' > dataFile = open(fileName, 'r').readlines() > I have to run 100 input files .DAT. Each time I run application, I have > to change code fileName to a new one. For example, fileName > = 'NewFile.DAT'. > I do not know how I can process all file with extension .DAT in a > specific directory once only. > > Any suggestion will be appreciated, > > Thank you. > > > From cfbolz at gmx.de Wed Nov 30 13:17:58 2005 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 30 Nov 2005 19:17:58 +0100 Subject: python speed In-Reply-To: <1133358884.407477.219560@g47g2000cwa.googlegroups.com> References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133358884.407477.219560@g47g2000cwa.googlegroups.com> Message-ID: Hi! Harald Armin Massa wrote: > And I could see real development just from watching the BDFL: 3 years > ago PyPy was 2000times slower then CPython, and Guido was joking "and > that number is growing", this year there were not officially negated > romours that sometime maybe PyPy could be the reference implementation > of Python; and also reports that PyPy is only 18 times slower then > CPython. well, currently PyPy is around 9-11 times slower than CPython. Since a few weeks ago we are now able to switch stacklessness on and off at compile time to be able to have an interpreter that supports very deeply recursive algorithms, if that is needed. Cheers, Carl Friedrich Bolz From tdwdotnet at gmail.com Wed Nov 2 11:39:28 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Wed, 2 Nov 2005 16:39:28 +0000 Subject: dictionary that have functions with arguments In-Reply-To: <1130903698.450993.268680@f14g2000cwb.googlegroups.com> References: <1130903698.450993.268680@f14g2000cwb.googlegroups.com> Message-ID: <9afea2ac0511020839v1aa45120h@mail.gmail.com> On 1 Nov 2005 20:02:41 -0800, s99999999s2003 at yahoo.com wrote: > hi > i have a dictionary defined as > > execfunc = { 'key1' : func1 } ################## def __HELLO(x=' '): print 'HELLO',x def __BYE(x=' '): print 'BYE',x def __PRINT(x=None, y=None): print 'PRINT',x,y cmds = { 'HELLO' : __HELLO, 'BYE' : __BYE, 'PRINT' : __PRINT, } a = 'HELLO JOE' b = a.split() if cmds.has_key(b[0]): cmds[b[0]](b[1]) # -> HELLO JOE cmds[b[0]]() # -> HELLO cmds['BYE']('TOM') # -> BYE TOM cmds['PRINT']( 'TOM','JOE' ) # -> PRINT TOM JOE cmds['PRINT'] # -> *No output - No exception ##################### Inside a class use cmds = { 'HELLO' : self.__HELLO, # etc def __HELLO(self, x=' '): #etc HTH :) From bonono at gmail.com Sat Nov 26 21:41:32 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 26 Nov 2005 18:41:32 -0800 Subject: scanl in python Message-ID: <1133059292.212429.4300@o13g2000cwo.googlegroups.com> >I think that the test for an empty iterator makes ireduce() unintuitive. Try >asking someone who has not followed the discussion >what list(ireduce(add, [], 42)) might produce, given that >list(ireduce(add, [1], 42)) --> [43] >list(ireduce(add, [1, 2], 42)) --> [43, 45] >list(ireduce(add, [])) --> [] >list(ireduce(add, [1])) --> [1] >list(ireduce(add, [1, 2])) --> [1, 3] >I suspect that [42] will be a minority vote. Don't know about the intend, but if it is duplicate of scanl(say on Haskell), it is : list(ireduce(add, [1], 42)) --> [42, 43] list(ireduce(add, [1, 2], 42)) --> [42, 43, 45] From theller at python.net Thu Nov 3 10:18:35 2005 From: theller at python.net (Thomas Heller) Date: Thu, 03 Nov 2005 16:18:35 +0100 Subject: How can I package a python script and modules into a single script? References: <1131030933.425241.142800@o13g2000cwo.googlegroups.com> Message-ID: <3bmd220k.fsf@python.net> "Noah" writes: > I would like to package my main script and all the > modules it imports into a single script that will > run just as the collection would. It should not > need to package standard Python lib modules -- just > my local modules. This is not the same question > that would be answered with py2exe or py2app. I > don't need to package the script into a binary > along with Python. I expect Python to be installed. > I also don't want to use distutils to install the > script. The script will always run on Unix. > > I thought that there might be some way to run a > script package from a tar file. One way would be to > have the package script untar itself into a temp > directory; run the main script; then delete the > temporary package directory when done. That sounds > clunky and prone to leave around trash if someone > does a 'kill -9'. However, this might be an > acceptable compromise. I'm sure that I've seen a > tool around like this, but I can't find it anymore. Wasn't this named 'squeeze'? Thomas From chris.cavalaria at free.fr Wed Nov 30 10:06:38 2005 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 30 Nov 2005 16:06:38 +0100 Subject: Death to tuples! In-Reply-To: References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: <438dbf32$0$16720$636a15ce@news.free.fr> Antoon Pardon a ?crit : > On 2005-11-30, Duncan Booth wrote: > >>Antoon Pardon wrote: >> >>>But lets just consider. Your above code could simply be rewritten >>>as follows. >>> >>> res = list() >>> for i in range(10): >>> res.append(i*i) >>> >> >>I don't understand your point here? You want list() to create a new list >>and [] to return the same (initially empty) list throughout the run of the >>program? > > > No, but I think that each occurence returning the same (initially empty) > list throughout the run of the program would be consistent with how > default arguments are treated. What about that : def f(a): res = [a] return res How can you return the same list that way ? Do you propose to make such construct illegal ? From gregory.petrosyan at gmail.com Tue Nov 15 14:02:45 2005 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 15 Nov 2005 11:02:45 -0800 Subject: Default method arguments In-Reply-To: <1h628u2.j7q74x1i9uhlvN%aleax@mail.comcast.net> References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a0a1b_1@newsgate.x-privat.org> <1132071889.676287.240030@o13g2000cwo.googlegroups.com> <1h628u2.j7q74x1i9uhlvN%aleax@mail.comcast.net> Message-ID: <1132081365.696331.166670@g14g2000cwa.googlegroups.com> Great thanks, Alex! From amfr.org at gmail.com Sun Nov 20 15:00:02 2005 From: amfr.org at gmail.com (amfr) Date: 20 Nov 2005 12:00:02 -0800 Subject: Command line Message-ID: <1132516802.524216.291900@g47g2000cwa.googlegroups.com> Hoe would I call something on the command line from python, e.g. "ls -la"? From twic at urchin.earth.li Fri Nov 18 18:54:29 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 18 Nov 2005 23:54:29 +0000 Subject: running functions In-Reply-To: <437d2a78@nntp0.pdx.net> References: <1132179612.759373.130900@g43g2000cwa.googlegroups.com> <437d2a78@nntp0.pdx.net> Message-ID: On Thu, 17 Nov 2005, Scott David Daniels wrote: > Gorlon the Impossible wrote: > >> I have to agree with you there. Threading is working out great for me >> so far. The multiprocess thing has just baffled me, but then again I'm >> learning. Any tips or suggestions offered are appreciated... > > The reason multiprocess is easier is that you have enforced separation. > Multiple processes / threads / whatever that share reads and writes into > shared memory are rife with irreproducible bugs and untestable code. > Processes must be explicit about their sharing (which is where the bugs > occur), so those parts of the code cane be examined carefully. That's a good point. > If you program threads with shared nothing and communication over Queues > you are, in effect, using processes. If all you share is read-only > memory, similarly, you are doing "easy" stuff and can get away with it. > In all other cases you need to know things like "which operations are > indivisible" and "what happens if I read part of this from before an > update and the other after the update completes, ..... Right, but you have exactly the same problem with separate processes - except that with processes, having that richness of interaction is so hard, that you'll probably never do it in the first place! tom -- science fiction, old TV shows, sports, food, New York City topography, and golden age hiphop From eternalsquire at comcast.net Wed Nov 16 17:00:16 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 16 Nov 2005 14:00:16 -0800 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> Message-ID: <1132178416.518202.138740@f14g2000cwb.googlegroups.com> >The legality of copying, modifying and redistributing works should be >reformed until it matches a 6th grader's intuitions about sharing. A 6th grader also has intuitions regarding the ownership of an idea. "It was MY idea!!!" "No, it's NOT!!!" "Is TOO!!!" The Eternal Squire From martin.witte at gmail.com Wed Nov 2 14:57:31 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 2 Nov 2005 11:57:31 -0800 Subject: Threading In-Reply-To: <1130961217.848546.68450@g14g2000cwa.googlegroups.com> References: <1130959652.003475.26650@o13g2000cwo.googlegroups.com> <1130961217.848546.68450@g14g2000cwa.googlegroups.com> Message-ID: <1130961451.509455.248180@g44g2000cwa.googlegroups.com> Ooops, forgot this link to the recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 From fairwinds at eastlink.ca Sat Nov 26 09:56:26 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Sat, 26 Nov 2005 10:56:26 -0400 Subject: Whitespace test after string.split Message-ID: Hi. I am splitting a string on a non whitespace character. One or more whitespace characters can be returned as items in the list. I do not want the items in the list that are only whitespace (can be one or more characters of whitespace) and plan to use string.strip on those items that are not only whitespace (to remove any whitespace from front or back of items). What kind of efficient test can I use to obtain only list items returned from the split that I am interested in, ignoring any list items that would only be comprised of one or more characters of whitespace (since whitespace can mean one or more spaces, tabs, and other characters) As a second question, I am seeing string split as deprecated in 2.4.2 manual. What is planned in future to split (strings or unicode)? Regards, David From bdelmee at advalvas.REMOVEME.be Wed Nov 30 06:34:46 2005 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Wed, 30 Nov 2005 12:34:46 +0100 Subject: [OT] Oracle 9i client for Linux In-Reply-To: References: <438ced15$0$447$6c56d894@reader0.news.be.easynet.net> Message-ID: <438d8e66$0$441$6c56d894@reader0.news.be.easynet.net> > It is version 10, would it be compatible with 9i servers? Yes. > Indeed I use cx_oracle but on M$ yet. Want to move to Linux. If you need to compile yourself, the instant client headers don't live where a full-blown Oracle install would put them and you may need to slightly alter setup.py. cx_oracle has a support list, see http://sourceforge.net/projects/cx-oracle/ Cheers, Bernard. From mde at micah.elliott.name Tue Nov 1 13:33:59 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Tue, 1 Nov 2005 10:33:59 -0800 Subject: Flat file, Python accessible database? In-Reply-To: References: Message-ID: <20051101183359.GI2575@kitchen.client.attbi.com> On Nov 01, Karlo Lozovina wrote: > I've been Googling around for _small_, flat file (no server > processes), SQL-like database which can be easily access from > Python. Speed and perforamnce are of no issue, most important is > that all data is contained within single file and no server binary > has to run in order to use the dbase. Oh, and I'm using Python under > Cygwin. > > Ofcourse, ease of use and simplicity is most welcomed :). I'm > currently playing around SQLite+PySQLite and BerkeleyDB, but those > two seem like an overkill :(. Not sure about "SQL-like", but the conf/ini file type could be considered a reasonable database format for simple needs, and is easy to parse/write. The ConfigParser is documented here: http://www.python.org/doc/current/lib/module-ConfigParser.html And Fredrik Lundh's examples usage is here: http://effbot.org/librarybook/configparser.htm And the Initialization File format is described here: http://en.wikipedia.org/wiki/INI_file -- _ _ ___ |V|icah |- lliott http://micah.elliott.name mde at micah.elliott.name " " """ From aisaac0 at verizon.net Wed Nov 23 12:55:19 2005 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 23 Nov 2005 17:55:19 GMT Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <1132708265.941224.186550@g44g2000cwa.googlegroups.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:dm263o$b8b$02$1 at news.t-online.com... > Of course nothing can beat a plain old for loop in terms of readability and > -- most likely -- speed. Here are two versions, meant to be comparable. Thanks, Alan Isaac def cumreduce(func, seq, init = None): cr = seq[:] if not(init is None): if seq: cr[0] = func(init,seq[0]) else: cr = [init] for idx in range(1,len(seq)): cr[idx] = func(cr[idx-1],seq[idx]) return cr def ireduce(func, iterable, init=None): if init is None: iterable = iter(iterable) init = iterable.next() yield init elif not iterable: yield init for item in iterable: init = func(init, item) yield init From fredrik at pythonware.com Tue Nov 29 10:32:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Nov 2005 16:32:18 +0100 Subject: TypeError: unsubscriptable object References: <20051129145254.79045.qmail@web30510.mail.mud.yahoo.com> Message-ID: "enas khalil" wrote: > i got this error : > Traceback (most recent call last): > File "F:\MSC first Chapters\28-11\firstprog1.py", line 53, in -toplevel- > for cond in word :cfdist[cond].inc[aa['TAG']] > TypeError: unsubscriptable object it means that either cfdist, cfdist[cond].inc, or aa is not a subscriptable object (that it, some of those don't support the [] operator). my guess is that "inc" is a method, which means that you should use () (call method) instead of [] (index): for cond in word: cfdist[cond].inc(aa['TAG']) > also if you please suggest me a good refrence in how to handle different > types of objects in python as token ,and how i can generate different > token attributes I have no idea what you're talking about here. maybe you should check with an NLTK support forum? From gaudetteje at gmail.com Wed Nov 30 12:18:08 2005 From: gaudetteje at gmail.com (NavyJay) Date: 30 Nov 2005 09:18:08 -0800 Subject: XML processing References: Message-ID: <1133371088.446624.51990@g44g2000cwa.googlegroups.com> I haven't used PyXML extensively, but I have used parts of the Amara XML Toolkit (http://uche.ogbuji.net/uche.ogbuji.net/tech/4suite/amara/) and recommend it for elegance. I can't say, however, which tool is faster. There are many other XML modules that people have written for Python. Do your research and pick the best one for you. On a side note, XML has historically been a poor solution for most of the cases I've seen it used. You should seriously rethink whether you "need to do some XML programming" and consider simpler options. In most simple cases, a primitive text parser with a delimited format is your best bet. You would know best, but this is my 2 cents. From enas_khalil at yahoo.com Sun Nov 20 08:35:19 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Sun, 20 Nov 2005 05:35:19 -0800 (PST) Subject: need help in how to make my script read arabic lang In-Reply-To: Message-ID: <20051120133519.86033.qmail@web30515.mail.mud.yahoo.com> hello , i want to know if yu please how can i use python code in tagging arabic text file my code is as follow : # -*- coding: cp1256 -*- import codecs from nltk.tagger import * from nltk.corpus import brown from nltk.tokenizer import WhitespaceTokenizer from nltk import * from nltk.tokenreader.tagged import TaggedTokenReader # Tokenize ten texts from the Brown Corpus train_tokens = [] text_str = (open('fataha2.txt').read()) #codecs.encode(text_str,'cp1256') reader = TaggedTokenReader(SUBTOKENS='WORDS') text_token = reader.read_token(text_str) print text_token['WORDS'] for l in text_token['WORDS']: train_tokens.append(l) #Initialise and train a unigram tagger mytagger = UnigramTagger(SUBTOKENS='WORDS') for xx in train_tokens: cc = reader.read_token(xx['TEXT']) # print cc.keys() cc['SUBTOKENS']= cc['WORDS'] mytagger.train(cc) #Once a UnigramTagger has been trained, the tag() method can be used to tag new text: text_token = Token(TEXT="????? ??? ?? ????????") WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token) mytagger.tag(text_token) #print 'The first example : Using Unigram Tagger the reseults are : ' print print text_token and i got the following error : Traceback (most recent call last): File "I:/examples/unigramgtag1update1.py", line 13, in ? codecs.encode(text_str,'cp1256') File "C:\Python24\lib\encodings\cp1256.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 0: ordinal not in range(128) please help --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Nov 23 17:19:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 23:19:36 +0100 Subject: Reading binary files References: <1132783214.588828.156280@g49g2000cwa.googlegroups.com> Message-ID: "amfr" wrote > On windows, is there anything special I have to do to read a binary > file correctly? the documentation has the answer: http://docs.python.org/lib/built-in-funcs.html#l2h-25 Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files (else it is ignored). /.../ When opening a binary file, you should append 'b' to the mode value for improved portability. (It's useful even on systems which don't treat binary and text files differently, where it serves as documentation.) in other words, always use f = open(filename, "rb") to open binary files for reading, on all platforms (but it only matters on some platforms). to open for writing, use f = open(filename, "wb") # create new file or f = open(filename, "r+b") # open existing file for read/write From fredrik at pythonware.com Mon Nov 28 10:57:29 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 28 Nov 2005 16:57:29 +0100 Subject: Precision for equality of two floats? References: Message-ID: "Anton81" wrote: > When I do simple calculation with float values, they are rarely exactly > equal even if they should be. What is the threshold http://www.lahey.com/float.htm http://docs.python.org/tut/node16.html > and how can I change it? you cannot. > e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:" use your own equal function, e.g. def equal(a, b): return abs(a - b) < 1e-6 if equal(f1, f2): ... (see the "safe comparision" section of the lahey.com paper for better ways to test for "approximate equality") From deets at nospam.web.de Sun Nov 20 15:50:10 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Nov 2005 21:50:10 +0100 Subject: Command line In-Reply-To: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> References: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> Message-ID: <3uc5rtF102svmU1@uni-berlin.de> amfr wrote: > Hoe would I call something on the command line from python, e.g. "ls > -la"? Use the module subprocess - otherwise maybe popen2 or os. Regards, Diez From dima at net.ntl.com Thu Nov 24 13:43:42 2005 From: dima at net.ntl.com (Dima Barsky) Date: Thu, 24 Nov 2005 18:43:42 +0000 Subject: FTP over TLS References: Message-ID: Carl Waldbieser wrote: > Does anyone know of any good examples for writing client side code > to upload files over a secure FTP connection? I am referring to > FTPS, *not* SFTP, which I found out the hard way are two different > things. Look at the CURL library, the manual says it supports FTPS, although I have not tried it myself: http://curl.haxx.se/libcurl/python/ Hope it helps, Dima. From samrobertsmith at gmail.com Sun Nov 20 19:57:01 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 16:57:01 -0800 Subject: about list Message-ID: <1d987df30511201657g6cccb98bn5ee121474f2d7ef@mail.gmail.com> How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]? Thanks! From steve at REMOVEMEcyber.com.au Mon Nov 14 03:10:04 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Mon, 14 Nov 2005 19:10:04 +1100 Subject: modifying small chunks from long string References: <1131951470.660501.68710@g44g2000cwa.googlegroups.com> <437844F9.20109@REMOVEMEcyber.com.au> Message-ID: <4378465C.40304@REMOVEMEcyber.com.au> Replying to myself... the first sign of madness *wink* Steven D'Aprano wrote: > size = 1024*1024*20 # 20 MB > original = "A" * size > copy = [None] * size > for i in range(size): > copy[i] = original[i].lower() > copy = ''.join(copy) Do you notice the premature optimization? Rather than appending new data to an initially empty list, I thought I would "optimize" my code by pre-allocating all the memory I would need for the list. You can see how well it didn't work: > This takes 530 seconds (8 minutes) The more sensible algorithm, without the unneeded pre-allocation of the copy list, runs 1000 times faster. That's the difference between optimization by wild guessing and optimization by actually writing good code :-) -- Steven. From aum at spam.me.please Tue Nov 8 01:09:53 2005 From: aum at spam.me.please (aum) Date: Tue, 08 Nov 2005 19:09:53 +1300 Subject: R.I.P. Vaults of Parnassus? Message-ID: Hi, The Vaults of Parnassus site: http://www.vex.net/parnassus/ has been down for several days, with no resolution available for the vex.net domain. That site was a treasure-trove of Python resources, with a decent search engine. Does anyone know if it'll be coming back up, or if it's mirrored anywhere? Can anyone recommend any other good warehouses of Python goodies? -- Cheers aum From noway at sorry.com Thu Nov 24 18:31:20 2005 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 24 Nov 2005 23:31:20 GMT Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: >>> Note that this property of __slots__ is an implementation detail. >>> You >>> can't rely on it working in the future. >> I don't "rely" on it. I just want to catch bugs in my code. > > I certainly hope you're not relying on it to catch bugs. You should do > proper testing instead. Not only will that catch pretty much all the > bugs you mention later - thus resolving you of the need to handcuff > clients of your class - it will catch lots of other bugs as well. This sounds a little academic. Writing a real Python program without testing is impossible or close to it, so you are really not telling me anything new. Even *with* testing, there are bugs. I'm sure you well know this. My feeling is that you're trying to get too much out of my words. I'm not trying to handcuff anyone. You seem to concentrate on me trying to avoid people adding attributes to my precious objects. It's not that. If I write a class and want it to be immutable, it is because it has to be so. If I write a queue class and I say that people shouldn't call pop() if it's empty, I mean it. If I enforce it with a RuntimeError, I'm not thinking I'm handcuffing someone. I don't see a ImmutableError to be so different from it. I often design objects that I want to be immutable. I might keep it as a key in dictionaries, or I might have external, non-intrusive caches of some kind relying on the fact that the instance does not change. Of course, it *might* be that testing uncovers the problem. Unittests tend to be pretty specific, so in my experience they happen to miss *new* bugs created or uncovered by the integration of components. Or if they hit it, you still have to go through debug sessions. An ImmutableError would spot the error early. In my view, enforcing immutability is no different from other forms of self-checks. Do you reckon all kind of asserts are useless then? Surely they don't help for anything that a good unittest couldn't uncover. But they help catching bugs such as breakage of invariants immediately as they happen. Immutability can be such an invariant. >>>> If it's not a wart, why would it be a wart for user-defined types >>>> to >>>> have the same behaviour? >>> >>> It's a wart because user-defined classes *don't* have the same >>> behavior. >> Then *my* solution for this would be to give user-defined classes a >> way to behave like builtins, eg. explicitally and fully implement >> immutability. > > Well, if you want to propose a change to the language, you need a good > use case to demonstrate the benefits of such a change. Do you have > such a use case? Catching bugs doesn't qualify, otherwise Python would > be radically different from what it is. One good reason, in my opinion, is that there *are* immutable objects in Python, among builtins. And people can easily build extension objects which are immutable. So being impossible to write a regular object in Python which is immutable is not orthogonal to me. Now let me ask you a question. What is a good use case for "assert" that justifies its introduction in the language? What is a good usecase for module 'unittest' which justifies its introduction in the standard library? Why do you think tuples are immutable and *enforced* to be so? >> Immutability is an important concept in Python programs, and I'm >> impressed it does not have explicit support. > > I'm not convinced that immutability is that important a concept. Yeah, > you have to know about it, but it seems more like an implementation > detail than a crucial concept. Probably it's just a matter of design styles. > I'm not sure it's more important than > things like interned strings and the sharing of small integers. Most > of the discussion of immutables here seems to be caused by newcomers > wanting to copy an idiom from another language which doesn't have > immutable variables. Their real problem is usually with binding, not > immutability. I'm not such a newcomer, but (how funny) Python is *the* language that introduced me to the concept of immutable objects and their importance in design :) -- Giovanni Bajo From mwm at mired.org Sun Nov 13 00:55:53 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 13 Nov 2005 00:55:53 -0500 Subject: Copyright [was Re: Python obfuscation] References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <1131859100.890118.317030@g14g2000cwa.googlegroups.com> Message-ID: <868xvt147q.fsf@bhuda.mired.org> "The Eternal Squire" writes: >>Copyright is a gift granted by the government, not the natural state of >>the world. When kings and emperors and presidents give commercial and >>economic gifts, like monopolies, they rarely are for the benefit of the >>majority. > Last I knew, we had government by, for, and of the people. As far as I know, only one country ever claimed to have that, so your "we" only applies to citizens of that country, and not to everyone who may be reading the letter - and the status of the person you quoted but did not attribute is unclear. Further, recent evidence is that this is no longer true in that country, assuming it ever was. >>and what >>evidence there is suggests strongly that over-strong copyright laws (like >>we have now) are bad for *everyone*, and that weaker copyright (as in the >>early 20th century) would be better. > And here is the crux of the debate. If good, how strong should it be? > Strong enough so that the creator pay his rent and his food and put his > children through college. No so strong that a new creator can't derive > a worthwhile new work from the old. Neither of your two stated goals are being met by the current copyright system. One of them is simply absurd as stated - presumably because your statement is incomplete. Copyright by itself does not pay the rent, put food on the table or put people through college. It's strong enough to be do that *if* the public values what you create enough and *if* you work hard enough at marketing it and *if* you produce enough. Those are some mighty big ifs. On the other hand, we're liable to never see creative work derived from any Disney property newer than the Mouse, with certain narrow exceptions. It seems that the government "by, for and of the people" has reliably extended the lifetime of copyrights - retroactively, even - every time the Mouse is about to slip into the public domain. Maybe "the people" you're talking about above are "the rich corporations with the congresscritters in their pockets." But that's hardly "the majority". >> It churns my stomach to see >>thieves and con artists like the RIAA trying to take the moral high ground >>with talk of "copying is theft". > Copying is theft of opportunity for the creator to be rewarded for his > efforts. The RIAA serves an important role in attempting to introduce > this idea as part of our social norms and courtesies. You apparently think that taking the opportunity for the creator to be rewarded for their efforts is ok if you deride other people who do that very thing. So what's the difference between the RIAA and a pirate who publicly points out that what the RIAA is up to? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Tue Nov 8 22:38:18 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 09 Nov 2005 03:38:18 +0000 Subject: which feature of python do you like most? In-Reply-To: <042dne8P_Ys9y-zenZ2dnUVZ_sadnZ2d@powergate.ca> References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> <042dne8P_Ys9y-zenZ2dnUVZ_sadnZ2d@powergate.ca> Message-ID: Peter Hansen wrote: > zelzel.zsu at gmail.com wrote: > >>I have no idea why people are so facinating with python. > > > Hey, I'm fascinating even without python! > And so modest, too :-) 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 holovaty at gmail.com Wed Nov 16 11:03:53 2005 From: holovaty at gmail.com (Adrian Holovaty) Date: 16 Nov 2005 08:03:53 -0800 Subject: ANN: Django 0.90 Message-ID: <1132157033.635645.86350@g43g2000cwa.googlegroups.com> After a months-long "pre-release" period, we're pleased to announce the first release of Django, the Web framework for perfectionists (with deadlines). Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It lets you write high-quality Web apps very quickly, with very little code. It gives you: * An object-relational mapper, which currently works with PostgreSQL, MySQL and SQLite. (Oracle and MS-SQL support are coming.) This lets you query databases in Python; there's no need to write SQL if you don't want to. * A template system. * A beautiful, production-ready admin interface -- for free. * Full internationalization (i18n) support. * A super-cool community! * An RSS/Atom-producing framework. * Tons of other niceties, such as generic views (which abstract common Web-development patterns), based on several years' worth of solving Real Problems in the Real World. Django has been used on production sites -- lawrence.com, ljworld.com, 6newslawrence.com, kusports.com, visitlawrence.com -- since late 2003. It also powers chicagocrime.org and a host of other sites all over the world. See http://code.djangoproject.com/wiki/DjangoPoweredSites . This release is version 0.90. Our goal is to wrap up remaining changes for 1.0 in the coming weeks/month, and release 1.0 with a guarantee of backwards compatibility. There's not yet a guarantee of backwards compatibility between releases. http://www.djangoproject.com/ http://www.djangoproject.com/download/ Enjoy! Adrian -- Adrian Holovaty holovaty.com | djangoproject.com | chicagocrime.org From eugene at boardkulture.com Sat Nov 19 10:42:21 2005 From: eugene at boardkulture.com (EuGeNe) Date: Sat, 19 Nov 2005 16:42:21 +0100 Subject: Obtaining an member function by name In-Reply-To: References: Message-ID: guy lateur wrote: > Hi all, > > Suppose you have this class: > > class foo: > def bar(): > > Suppose you also have the strings "foo" and "bar". How can you obtain the > function foo.bar()? > > Surely somebody knows.. > > TIA, > g > > Would that do? >>> class foo: @staticmethod def bar(): pass >>> foo.bar >>> From bignose+hates-spam at benfinney.id.au Wed Nov 16 17:54:22 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Nov 2005 09:54:22 +1100 (EST) Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> <1132178792.001827.280820@z14g2000cwz.googlegroups.com> Message-ID: The Eternal Squire wrote: > Ben Finney wrote: > >Ethics such as sharing, and helping one's neighbour? > > Giving away an illegal copy of software it not helping one's > neighbor, it is making that neighbor an accessory to copyright > infringement, a federal offense punishable not in excess of 10 years > of $10K. So the law is the guide to ethical behaviour? Sure you don't have that reversed? -- \ "Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus." -- | _o__) Peter H. Coffin | Ben Finney From enas_khalil at yahoo.com Sun Nov 20 15:52:18 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Sun, 20 Nov 2005 12:52:18 -0800 (PST) Subject: need a tutorial in tokens ,different types In-Reply-To: Message-ID: <20051120205218.61945.qmail@web30507.mail.mud.yahoo.com> hello all could any one suggest me tutorials in different tokenizations and clear describtion of how can i use token type and assign diff attributes to tokens ,also good tutorials in diff data types in python thanks every body enas --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From morphex at gmail.com Wed Nov 9 20:56:42 2005 From: morphex at gmail.com (morphex) Date: 9 Nov 2005 17:56:42 -0800 Subject: Sending email in utf-8? References: <1131381565.320532.229310@g49g2000cwa.googlegroups.com> <1131388898.175850.301140@o13g2000cwo.googlegroups.com> Message-ID: <1131587802.290119.14670@g43g2000cwa.googlegroups.com> By turning everything into unicode objects (unicode(string)) and then running body.encode('utf-8') and using quoted printable, it works. Thanks for all the help, it's really appreciated! From fredrik at pythonware.com Sun Nov 20 11:36:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 17:36:05 +0100 Subject: email separation References: <20051120160913.13612.qmail@web35911.mail.mud.yahoo.com> Message-ID: "john boy" wrote: > Does anyone know if I can somehow separate all mails coming > from the python forum from all of my other mail, so I can open > it from another folder or something like that under the same > address...I have a yahoo account... look under "filters" on this page: http://help.yahoo.com/help/us/mail/manage/index.html From apardon at forel.vub.ac.be Mon Nov 28 04:25:51 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2005 09:25:51 GMT Subject: Making immutable instances References: <0I6dncrRuNnuxBjeRVn-ig@comcast.com> Message-ID: Op 2005-11-26, Steven D'Aprano schreef : > On Thu, 24 Nov 2005 12:55:07 +0000, Antoon Pardon wrote: > >> Suppose I have the following code. >> >> from module import __take_care__ >> >> __private_detail__ = ... >> >> I now have two variable that are flaged the same way, but they are not. > > No, you have two names written using a poor naming convention. Well if it is a poor naming convention, why react to me, and not to Mike who was defending this poor naming convention? > __name__ should be used only for Python's special methods. > >> __take_care__ is a private variable from an other module which I should >> use with extreme care not to break the other package. > > Python doesn't do any special treatment of __name or __name__ from > modules. The only information hiding techniques Python enforces are that > module._name (single leading underscore) is not imported by "from module > import *", and class.__name (double leading underscore) is mangled to > class._Class__name. We were not talkin about special treatment by python. We were talking about conventions to communicate purpose to other readers of the software. >> It are other modules that should take special care if they >> should choose to import this variable. > > I'm not sure what the difference is. If there is a difference, why are you > using the same naming convention for different sorts of names ("private > module variable" and "private module data"). If there is no difference, I > don't understand the point of your example. Well it seems you didn't seem to understand the point of my answer. Maybe you should first reread the article I responded too. -- Antoon Pardon From MrJean1 at gmail.com Sun Nov 27 16:26:36 2005 From: MrJean1 at gmail.com (MrJean1) Date: 27 Nov 2005 13:26:36 -0800 Subject: Estimating memory use? In-Reply-To: References: Message-ID: <1133126796.600993.145210@f14g2000cwb.googlegroups.com> There is a function mx_sizeof() in the mx.Tools module from eGenix which may be helpful. More at /Jean Brouwers PS) This is an approximation for memory usage which is useful in certain, simple cases. Each built-in type has an attribute __basicsize__ which is the size in bytes needed to represent the basic type. For example str.__basicsize__ returns 24 and int.__basictype__ returns 12. However, __basicsize__ does not include the space needed to store the object value. For a string, the length of the string has to be added (times the character width). For example, the size of string "abcd" would at least approximately str.__basicsize__ + len("abcd") bytes, assuming single byte characters. In addition, memory alignment should be taken into account by rounding the size up to the next multiple of 8 (or maybe 16, depending on platform, etc.). An approximation for the amount of memory used by a string S (of single byte characters) aligned to A bytes would be (str.__basicsize__ + len(S) + A - 1) & A Things are more complicated for types like list, tuple and dict and instances of a class. From donn at u.washington.edu Mon Nov 28 13:21:25 2005 From: donn at u.washington.edu (Donn Cave) Date: Mon, 28 Nov 2005 10:21:25 -0800 Subject: exception KeyboardInterrupt and os.system command References: <200511271513.48021.bulliver@badcomputer.org> <3uv06bF13d0blU1@uni-berlin.de> <1133168674.088374.142790@z14g2000cwz.googlegroups.com> Message-ID: In article <1133168674.088374.142790 at z14g2000cwz.googlegroups.com>, "malv" wrote: > That's also kind of what I expected. > However, I quickly tried: > import os > while 1: > y = os.system("sleep 1") > z = (y >> 8) & 0xFF > print z > > I never get anything in return but 0, hitting c-C or not. > I have uset the above code to get exit code returns in the past though. > Would there be anything special with sleep? That algorithm will give you the same thing as os.WEXITSTATUS(), on most platforms, though not necessarily all so it's better to use the function. On platforms where it works, exit status is of course stored in 2nd byte from the low end, and signal status is stored separately, in the low byte. So naturally, your right shift discards the signal status and you're left with 0. On the other hand, if you use os.spawnv, signal status will be returned as a negative integer, instead of a positive integer exit status. spawnv() is safer than system() if the command is constructed from data, and it also doesn't block SIGINT in the caller like system does, so it would work for the problem posed in the original post. But it might be just as well to watch the process status for any non-zero value, and then call the graceful exit procedure. Donn Cave, donn at u.washington.edu From rrr at ronadam.com Sun Nov 13 17:03:13 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 13 Nov 2005 22:03:13 GMT Subject: help make it faster please In-Reply-To: References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com><1131648018.390959.80610@f14g2000cwb.googlegroups.com><1131649407.776813.57740@o13g2000cwo.googlegroups.com> <1131651417.994185.121630@g47g2000cwa.googlegroups.com> <5ALdf.1159$bx3.968@tornado.tampabay.rr.com> Message-ID: Fredrik Lundh wrote: > Ron Adam wrote: > > >>The \w does make a small difference, but not as much as I expected. > > > that's probably because your benchmark has a lot of dubious overhead: I think it does what the OP described, but that may not be what he really needs. Although the test to find best of n, instead was finding worse of n. Which explains why I was getting a larger variance than I thought I should have been getting. >>word_finder = re.compile('[\w@]+', re.I) > > > no need to force case-insensitive search here; \w looks for both lower- > and uppercase characters. But the dictionary keys need to be either upper or lower otherwise you count 'The' separately from 'the'. >> for match in word_finder.finditer(string.lower()): > > > since you're using a case-insensitive RE, that lower() call is not necessary. > > >> word = match.group(0) > > > and findall() is of course faster than finditer() + m.group(). Cool, I don't use re that often so I just used what was posted to test against. > >> t = time.clock() >> for line in lines.splitlines(): >> countDict = foo(line) >> tt = time.clock()-t > > > and if you want performance, why are you creating a new dictionary for > each line in the sample? Because that's what the OP apparently wanted. A line by line word count. I originally did it to get an the over all count and then change it so it matched the re version that was posted. > here's a more optimized RE word finder: > > word_finder_2 = re.compile('[\w@]+').findall > > def count_words_2(string, word_finder=word_finder_2): > # avoid global lookups > countDict = {} > for word in word_finder(string): > countDict[word] = countDict.get(word,0) + 1 > return countDict > > with your original test on a slow machine, I get > > count_words: 0.29868684 (best of 3) > count_words_2: 0.17244873 (best of 3) > > if I call the function once, on the entire sample string, I get > > count_words: 0.23096036 (best of 3) > count_words_2: 0.11690620 (best of 3) > > Wow, a lot bigger difference than on my machine. An athlon 64 3000+ on winxp. I'm not sure how much difference that would make? This is what I get after adding the above version to it, with the lower(). There's not quite as big a difference as you get, but the find all version is still faster than both the others. Cheers, Ron Character count: 100000 Word count: 16477 Average word size: 6.06906597075 word_counter: 0.06245989 (best of 3) count_words: 0.07309812 (best of 3) count_words_2: 0.04981024 (best of 3) And as count all words... Character count: 100000 Word count: 16477 Average word size: 6.06906597075 word_counter: 0.05325006 (best of 3) count_words: 0.05910528 (best of 3) count_words_2: 0.03748158 (best of 3) They all improve, but the re find all version is clearly better. ##################### import string import re import time import random # Create a really ugly n length string to test with. # The word length are n = 100000 random.seed(1) lines = ''.join([ random.choice(string.ascii_letters * 2 + '_@$&*()#/<>' + ' \n' * 6) for x in range(n) ]) print 'Character count:', n print 'Word count:', len(lines.split()) print 'Average word size:', float(n)/len(lines.split()) letters = string.lowercase + string.digits + '_@' def word_iter(text, letters=letters): wd = '' for c in text + ' ': if c in letters: wd += c elif wd != '': yield wd wd = '' def word_counter(text): countDict={} for wd in word_iter(text.lower()): if wd in countDict: countDict[wd] += 1 else: countDict[wd] = 1 return countDict word_finder = re.compile('[\w@]+', re.I).finditer def count_words(string, word_finder=word_finder): # avoid global lookups countDict = {} for match in word_finder(string.lower()): word = match.group(0) countDict[word] = countDict.get(word,0) + 1 return countDict word_finder_2 = re.compile('[\w@]+').findall def count_words_2(string, word_finder=word_finder_2): # avoid global lookups countDict = {} for word in word_finder(string.lower()): countDict[word] = countDict.get(word,0) + 1 return countDict foos = [word_counter, count_words, count_words_2] r1 = r2 = None for foo in foos: best_time = 1000000 # too large to be useful on purpose for n in range(3): t = time.clock() #for line in lines.splitlines(): countDict = foo(lines) tt = time.clock()-t best_time = min(tt, best_time) r1 = r2 r2 = countDict if r1 != None: # change to 1 if assert fails to find problem if 0: for k in r1.keys(): if r1[k] != r2[k]: print k,r1[k],r2[k] assert r1 == r2 print '%s: %.8f (best of %d)' \ % (foo.__name__, best_time, n+1) From david.rasmussen at gmx.net Tue Nov 1 14:36:07 2005 From: david.rasmussen at gmx.net (David Rasmussen) Date: Tue, 01 Nov 2005 20:36:07 +0100 Subject: Scanning a file In-Reply-To: <43663b19.1454241668@news.oz.net> References: <1130497567.764104.125110@g44g2000cwa.googlegroups.com> <7xek65nal0.fsf@ruckus.brouhaha.com> <1130505731.850947.68690@o13g2000cwo.googlegroups.com> <4363fdd4$0$2107$edfadb0f@dtext02.news.tele.dk> <43663b19.1454241668@news.oz.net> Message-ID: <4367c3a5$0$2100$edfadb0f@dtext02.news.tele.dk> Bengt Richter wrote: > > Good point, but perhaps the bit pattern the OP is looking for is guaranteed > (e.g. by some kind of HDLC-like bit or byte stuffing or escaping) not to occur > except as frame marker (which might make sense re the problem of re-synching > to frames in a glitched video stream). > Exactly. > The OP probably knows. I imagine this thread would have gone differently if the > title had been "How to count frames in an MPEG2 file?" and the OP had supplied > the info about what marks a frame and whether it is guaranteed not to occur > in the data ;-) > Sure, but I wanted to ask the general question :) I am new to Python and I want to learn about the language. /David From nospam2 at 2nospam.com Sat Nov 19 18:24:58 2005 From: nospam2 at 2nospam.com (Tony) Date: Sat, 19 Nov 2005 17:24:58 -0600 Subject: Is Python weak on the web side? Message-ID: If I'd like to learn Python for web-development, what are the options available? Thanks. tony From aleax at mail.comcast.net Mon Nov 28 22:08:42 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 28 Nov 2005 19:08:42 -0800 Subject: Instantiating classes which are derived from built-in types. References: Message-ID: <1h6r3kz.1w1dj8fyl4ey7N%aleax@mail.comcast.net> Achim Dahlhoff wrote: > Hi. > > I'm trying to find out the diffrence between normal classes and classes > derived from built-in types. > (Which is causing me trouble trying to instantiate a class using C API > calls) > > >>> class A: > ... pass > ... > >>> class B(dict): > ... pass > ... > >>> type(A) > > >>> type(B) > > >>> A is oldstyle -- a wart existing for backwards compatibility. Newstyle classes (highly recommended for all new code) may inherit from object (or any other newstyle class, or builtin type supporting inheritance) or may be set on a per-module basis by setting __metaclass__=type at module level at the start of the module. > Anyone know how an object could be instantiated using a handle to B? Just use the recommended abstract interface, e.g. PyObject_CallFunction(B, NULL) if you want to pass no arguments - this works for A, for B, and for any other callable including e.g. a factory function (its very generality makes it very desirable...). Alex From mwm at mired.org Sat Nov 5 02:22:59 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 02:22:59 -0500 Subject: re sub help References: <1131173343.954029.211530@o13g2000cwo.googlegroups.com> Message-ID: <86br0z7e3w.fsf@bhuda.mired.org> s99999999s2003 at yahoo.com writes: > hi > > i have a string : > a = > "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" > > inside the string, there are "\n". I don't want to substitute the '\n' > in between > the [startdelim] and [enddelim] to ''. I only want to get rid of the > '\n' everywhere else. Well, I'm not an expert on re's - I've only been using them for three decades - but I'm not sure this can be done with a single re, as the pattern you're interested in depends on context, and re's don't handle that well. On the other hand, this is fairly straightforward with simple string operations: >>> a = "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" >>> sd = '[startdelim]' >>> ed = '[enddelim]' >>> s, r = a.split(sd, 1) >>> m, e = r.split(ed, 1) >>> a = s + sd + m.replace('\n', '') + ed + e >>> a 'this\nis\na\nsentence[startdelim]thisisanother[enddelim]this\nis\n' >>> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From darrenleeweber at gmail.com Sun Nov 6 17:43:09 2005 From: darrenleeweber at gmail.com (Darren L. Weber) Date: 6 Nov 2005 14:43:09 -0800 Subject: Installing ATLAS and LAPACK Message-ID: <1131316989.175136.14480@g47g2000cwa.googlegroups.com> The following is a first attempt to almost create a shell script for installation of ATLAS and LAPACK. It does not work right now and it is specific to a particular platform. It is posted here to archive it and throw into the public domain, maybe others will find it useful. It is at least a documentation of some relevant notes on the procedure. Corrections and updates would be really appreciated. Alternatives to automate this process also welcome, but not rpm (unless it can be demonstrated that an rpm installation achieves an equivalent optimized blas to a full compilation). Also, advice about integrating this with compilation of python and numeric python libraries much appreciated too, particularly the definition of some commonly accepted paths for the library installation, so that all python compilation can link the libraries without having to modify their configure scripts. ####################################################### For background about creating and using libraries with linux, see http://www.gnu.org/software/libtool/libtool.html http://www.dwheeler.com/program-library http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Program-Library-HOWTO.html "In theory, code in static ELF libraries that is linked into an executable should run slightly faster (by 1-5%) than a shared library or a dynamically loaded library, but in practice this rarely seems to be the case due to other confounding factors." Locations for installation (from Program-Library-HOWTO): 3.1.2. Filesystem Placement Shared libraries must be placed somewhere in the filesystem. Most open source software tends to follow the GNU standards; for more information see the info file documentation at info:standards#Directory_Variables. The GNU standards recommend installing by default all libraries in /usr/local/lib when distributing source code (and all commands should go into /usr/local/bin). They also define the convention for overriding these defaults and for invoking the installation routines. The Filesystem Hierarchy Standard (FHS) discusses what should go where in a distribution (see http://www.pathname.com/fhs). According to the FHS, most libraries should be installed in /usr/lib, but libraries required for startup should be in /lib and libraries that are not part of the system should be in /usr/local/lib. There isn't really a conflict between these two documents; the GNU standards recommend the default for developers of source code, while the FHS recommends the default for distributors (who selectively override the source code defaults, usually via the system's package management system). In practice this works nicely: the ``latest'' (possibly buggy!) source code that you download automatically installs itself in the ``local'' directory (/usr/local), and once that code has matured the package managers can trivially override the default to place the code in the standard place for distributions. Note that if your library calls programs that can only be called via libraries, you should place those programs in /usr/local/libexec (which becomes /usr/libexec in a distribution). One complication is that Red Hat-derived systems don't include /usr/local/lib by default in their search for libraries; see the discussion below about /etc/ld.so.conf. Other standard library locations include /usr/X11R6/lib for X-windows. Note that /lib/security is used for PAM modules, but those are usually loaded as DL libraries (also discussed below). ... 3.2. How Libraries are Used ... The list of directories to be searched is stored in the file /etc/ld.so.conf. Many Red Hat-derived distributions don't normally include /usr/local/lib in the file /etc/ld.so.conf. I consider this a bug, and adding /usr/local/lib to /etc/ld.so.conf is a common ``fix'' required to run many programs on Red Hat-derived systems. ####################################################### # A. ATLAS INSTALLATION 1. download and extract ATLAS source, eg cd /usr/local/src/ tar zxvf atlas3.6.0.tar.gz cd ATLAS #2. follow the INSTALL.txt instructions to build it and test ATLAS ./configure make #3. if successful, copy atlas files into common system locations, eg mkdir -p /usr/local/lib/atlas cp lib/Linux_P4SSE2/* /usr/local/lib/atlas/ chmod +x /usr/local/lib/atlas/lib* mkdir -p /usr/local/include/atlas cp include/Linux_P4SSE2/* /usr/local/include/atlas/ ####################################################### # B. LAPACK INSTALLATION # #1. download and extract LAPACK source cd /usr/local/src/ tar zxvf lapack.tgz cd LAPACK #2. make LAPACK with all defaults cp INSTALL/make.inc.$PLATFORM make.inc make #(On my fedora core 3 system, the timing failed) #3. if successful, install the default lapack mkdir -p /usr/local/lib/lapack cp lapack_LINUX.a /usr/local/lib/lapack/liblapack.a cp blas_LINUX.a /usr/local/lib/lapack/libf77blas.a ####################################################### # C. compile LAPACK for ATLAS # #1. prepare LAPACK for recompilation make clean cp Makefile Makefile.backup #3. remove all blas* entries from the Makefile all: and lib: entries echo "" echo " remove all blas* entries from the Makefile all: and lib: entries" echo "" cat Makefile | sed s/blaslib// | sed s/blas_testing// | sed s/blas_timing// > tmp.txt mv -f tmp.txt Makefile #4. edit make.inc, this is the tricky part! # #WRT, the BLASLIB entry of make.inc: # #BLASLIB here is just for testing purpose. We are not #creating a combined LAPACK/BLAS library. They are kept #separate. BLASLIB is the BLAS library with which you #want to test LAPACK. # #When you type 'make', the installation of LAPACK begins. #It consists of constucting the LAPACK library. # #LAPACK is Fortran code so you need the Fortran BLAS interface to ATLAS: #-L/usr/local/src/ATLAS/lib/Linux_P4SSE2 -lf77blas -latlas #(ie, there is no requirement for the libcblas.a) # #To test LAPACK with the ATLAS BLAS, set: # #BLASLIB = -L/usr/local/src/ATLAS/lib/Linux_P4SSE2/ -lf77blas -latlas # #or (given standardized installation location suggested above) # #BLASLIB = -L/usr/local/lib/atlas/ -lf77blas -latlas # #When testing LAPACK with ATLAS-BLAS: #!!!!make sure there is no -fno-f2c options!!!! #in the option of compilation of LAPACK (see in make.inc). # #When done, cp INSTALL/make.inc.LINUX make.inc oldlib=`cat make.inc | grep BLASLIB | sed s#/#.#g` newlib="BLASLIB = -L/usr/local/lib/atlas/ -lf77blas -latlas" cat make.inc | sed s/$oldlib/$newlib/ cp make.inc make.inc.atlas #5. recompile LAPACK (see the Makefile for options) make install make lib ####################################################### # D. INTEGRATE LAPACK with ATLAS INSTALLATION # #1. Combine the lapack_LINUX.a from the last lapack #build with the previous optimized ATLAS #liblapack.a, according to this web page: # #http://math-atlas.sourceforge.net/errata.html#completelp # #ATLAS provides optimized versions for 10 LAPACK driver routines: #[S,D,C,Z]GESV [S,D,C,Z]GETRF [S,D,C,Z]GETRS [S,D,C,Z]GETRI [S,D,C,Z]TRTRI #[S,D,C,Z]POSV [S,D,C,Z]POTRF [S,D,C,Z]POTRS [S,D,C,Z]POTRI [S,D,C,Z]LAUUM #You have no reason not to use them. # #So, cd /usr/local/src/ATLAS/lib/Linux_P4SSE2/ mkdir tmp cd tmp ar x /usr/local/src/ATLAS/lib/Linux_P4SSE2/liblapack.a cp /usr/local/src/LAPACK/lapack_LINUX.a libcombinedlapack.a ar r libcombinedlapack.a *.o #2. install the combined lapack library, eg: cp libcombinedlapack.a /usr/local/lib/atlas/ cp libcombinedlapack.a .. cd .. rm -rf tmp #3. Update the system? # #ln -s /usr/local/lib/atlas/libcombinedlapack.a /lib/liblapack.a # #If, for some reason, you build a shared library, run #ldconfig to update symbolic links and the cache in #/etc/ld.so.cache ################################################### # Using the library #A last remark: remember that LAPACK needs libf77blas.a and #LAPACK from ATLAS needs libcblas.a; so now the new liblapack.a #will need both. When linking programs, this looks like: # #-lcombinedlapack -lcblas -lf77blas -latlas # # #Acknowledgement: Some very helpful comments above were #provided by Julie Langou at cs utk edu From mahs at telcopartners.com Tue Nov 15 12:34:43 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 15 Nov 2005 09:34:43 -0800 Subject: Need advice on subclassing code In-Reply-To: <437a0c58$1_1@newspeer2.tds.net> References: <437a0c58$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Rusty Shackleford wrote: >> ... >> C_1_1 and C_1_2 share a common C ancestor, and in practice may be >> identical, but theoretically, could have the same function name with two >> different implementations underneath. >> >> ... > > How are you instantiating the correct class? You should be able to provide a default behaviour. For example if the classes are all defined in module C you could have a factory like this: > > import C > def makeC(x, y): > subtype = 'C_%d_%d' % (x, y) > cls = getattr(C, subtype, C.C) > return cls(x, y) > > Then in module C just define the subtypes you need to specialize; all other values of x and y will get the base class C.C. > > Kent Or, if you actually want different classes for each set of parameters (say for debugging or introspection), you could compose the default ones on the fly: import C def makeC(x, y): subtype = 'C_%d_%d' % (x, y) cls = getattr(C, subtype, None) if not cls: # No specialized class found, so compose a default # This requires C.C to be a new-style class cls = type(subtype, (C.C,), {"__autogenerated__": True}) return cls(x, y) Michael From cito at online.de Thu Nov 24 12:42:45 2005 From: cito at online.de (Christoph Zwerschke) Date: Thu, 24 Nov 2005 18:42:45 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <4385b7b6.632202659@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <1132735254.039468.106660@g44g2000cwa.googlegroups.com> <4385b7b6.632202659@news.oz.net> Message-ID: Bengt Richter schrieb: >>d.setvalues((13, 14)) ==> d = OrderedDict((1, 13), (2, 14)) > The implication above is that OrderedDict takes an *args argument, > but really it takes a single argument that is a sequence of k,v pairs, > (and maybe some keyword options). Right. Interpret it as a short notation only, I did not want to change the interface. I think it's a common mistake to forget the brackets because you think one pair should be enough. At least I often forget it. > You could make keys, values, and items custom descriptors which would define __call__ > for the old key() etc accesses, well as __getitem__ and __setitem__. Then you could write > > d.items[0], d.items[-1] = d.items[-1], d.items[0] > > to swap the order of the first and last items in the thing (I hesitate to say dict ;-) > You could also operate on slices. Nice. You could also get the i-th value with d.values[i]. But is this considered good style or would it be considered "dirty" to have a callable member that also supports indexing and slicing? (I don't know, just asking?) Plus, it opens a can of worms by increasing the complexity tremendously. Let's see whether this can be handled. > BTW, before I showed an example where d[2:3] returned > a new dict instance rather than d.items()[:]. I think the items list > is better, since they naturally add, sort, reverse, etc as lists, > and you can write OrderedDict(d[2:3]+d[1:2]) if you want a new dict. Not sure about that. I would rather expect that if you slice an object, you get an object of the same type. And you can also add, sort, reverse, etc the ordered dict if you want. > A slice assignment to d[i:j] is really sugar for something, but we have to decide exactly > what in case of duplicate keys in the incoming items, either with each other ... You mean slice assignments to d.items[i:j]. If you make the slice assignment to d[i:j] then at least you cannot have conflicts in the incoming items. The first question is: Should a slice assignment be treated as deletion with subsequential addition (changing the order) or as a replacement (i.e. try to not change the order)? I agree that the second would be the expected semantics, but as you mentioned more difficult to implement. > One way to define it would be > d.items[i:j] = itemseq > > to be implemented as sugar for > newitems = d.items[:i] + list(itemseq) + d.items[j:] > d.clear() > d.update(newitems) Which should be the same as d = OrderedDict(d.items[:i] + list(itemseq) + d.items[j:]) Sounds reasonable. > So > d.reverse() > could be spelled > d.items[:] = d.items[::-1] Slice assignment for keys and values would also allow to set a new key order with d.keys[:] = newkeyseq So no need to define a setkeys() method or let keys() take arguments. If we want to allow this kind of things at all. > If you are using slices, you can safely use them directly in the __getitem__ of th dict interface, > as I did in the "Que mas?" post. So we don't have to write d.items[i:j] and could write d[i:j]. > The thing is, d[i:j] will tempt to skip ".items" in d.items[i] and write d[i], which has the dict > key meaning, not the item list index. It is faster not have a descriptor between though. I still think d[i:j] should return an ordered dict, not an item list. > I think maybe allowing write to keys or values is pretty iffy. There are too many weird > re-associations of keys and values possible, and which you could do my other means if you > really really wanted to. But I do think full index and slice read access would be fine. There are different opinions. Fuzzyman would probably say "Don't trust yourself?" I myself am undecided. Perhaps you could expect that somebody knows what he does if he makes a slice assignment to d.keys. In any way, such an assignment should not "break" the directory (with "broken" I mean that the internal keys sequence does not match the keys of the internal dictionary). If anything does not match, it should raise a KeyException. If it is implemented that way, I think we can allow it. > I think also that d1==d2 should effectively be implemented as d1[:] == d2[:] -- i.e, compare > the item lists to implement comparisons. Wouldn't it be more performant to compare for d1.internal_dict==d2.internal_dict and d1.internal_sequence==d2.internal_sequence? You don't keep track of the item lists, they need to be built on every occasion. -- Christoph From cfajohnson at gmail.com Sat Nov 19 01:04:51 2005 From: cfajohnson at gmail.com (Chris F.A. Johnson) Date: Sat, 19 Nov 2005 01:04:51 -0500 Subject: os.popen('alias') References: <1132345866.163167.174360@f14g2000cwb.googlegroups.com> Message-ID: <3tr253-sfd.ln1@rogers.com> On 2005-11-19, Chris F.A. Johnson wrote: > On 2005-11-18, Belebele wrote: >>>From an interactive python shell, I execute the following: >> >> import os >> for line in os.popen('alias').readlines(): >> print line >> >> >> No aliases are printed. >> >> I started python from an bash environment that had many aliases >> defined. I expected to see the list of aliases from within the >> interactive python shell. > > Since bash does not export aliases, they cannot be seen by a child > process. > >> What could I do to see those aliases defined in the shell from where >> I started python? > > Store them in a file before calling python, and read that file. Or redefine them as functions and use: import os for line in os.popen('typeset -f').readlines(): print line -- Chris F.A. Johnson, author | Shell Scripting Recipes: | My code in this post, if any, A Problem-Solution Approach | is released under the 2005, Apress | GNU General Public Licence From peter at engcorp.com Wed Nov 23 22:28:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Nov 2005 22:28:45 -0500 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> References: <1132802380.246858.151330@g44g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Peter Hansen wrote: >>I believe it's currently guaranteed that the order of >>the items in dict.keys() and dict.values() will match (i.e. the index of >>any key in its list will be the same as the index of the corresponding >>value in its list). > > Interesting, but why it guaranteed this as functionality wise they are > two different things and since dict is unordered, there is no need for > such guarantee, would it be just implementation consequence ? From the docs (http://docs.python.org/lib/typesmapping.html): """ Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". The same relationship holds for the iterkeys() and itervalues() methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same value for pairs. Another way to create the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]". """ Does that explain it adequately? -Peter From roccomoretti at hotpop.com Mon Nov 7 13:23:15 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 07 Nov 2005 12:23:15 -0600 Subject: [OT] Map of email origins to Python list In-Reply-To: References: Message-ID: Paul McGuire wrote: > "Claire McLister" wrote in message > news:mailman.221.1131384118.18701.python-list at python.org... > We've been working with Google Maps, and have created a web service to > map origins of emails to a group. As a trial, we've developed a map of > emails to this group at: > > http://www.zeesource.net/maps/map.do?group=668 > > This represents emails sent to the group since October 27. > > Would like to hear what you think of it. > ------------------------------ > > > Another sleepless camera pointed at the fishbowl that is my online life. > It's also a testament to the limited value of physically locating people by internet addresses - If you zoom in on the San Fransico bay area, and click on the southern most bubble (south of San Jose), you'll see the entry for the Mountain View postal code (94043) - a massive list which contains mostly gmail.com accounts, but also contains accounts with .de .ca .uk .pl .it .tw and .za domains. I doubt all of the people in that list live in sunny California, let alone in Mountain View proper. From steve at holdenweb.com Tue Nov 1 10:19:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Nov 2005 15:19:42 +0000 Subject: Pickling and unpickling inherited attributes In-Reply-To: <1130851315.487444.205760@g47g2000cwa.googlegroups.com> References: <1130713951.953157.270130@g14g2000cwa.googlegroups.com> <1130851315.487444.205760@g47g2000cwa.googlegroups.com> Message-ID: <4367878E.9010401@holdenweb.com> Alex wrote: > Thanks to both Alex Martelli and Steve Holden.. We need __slots__ for > other reasons, too long to explain, but basically to prevent assignment > of extra attributes. > > I ended up changing child classes this way: > > def __getstate__(self): > return(Parent.__getstate__(self), self.C) > def __setstate__(self, data): > Parent.__setstate__(self, data[0]) > self.C=data[1:] > > This seems to work fine. > OK, but do be aware that slots was intended solely as a memory-conservation measure where large numbers of objects are being created. You are therefore subverting its true intent by using it to limit the assignment of extra attributes (and there has been much recent discussion on this list, though not in this thread, about what to do instead. 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 googlinggoogler at hotmail.com Sun Nov 6 07:01:49 2005 From: googlinggoogler at hotmail.com (googlinggoogler at hotmail.com) Date: 6 Nov 2005 04:01:49 -0800 Subject: Pylab and pyserial plot in real time Message-ID: <1131278509.380060.281410@g44g2000cwa.googlegroups.com> Hiya, I've got a PIC microcontroller reading me humidity data via rs232, this is in ASCII format. I can view this data easily using hyperterminal or pyserial and convert it to its value (relative humidty with ord(input)) But what im trying to do is plot the data in real time, ideally with pylab - as it looks simple to use and simple is the way i want to go! My code is below, it doesnt show a graph, I was wondering whether someone could suggest whats wrong? thank you in advance David ######################################################################## import serial from pylab import * ser = serial.Serial(0) t = arange(0.0, 1.0+0.01, 0.01) xlabel('time') ylabel('RH %') title(' RH sensor data sampled at 1 sec intervals ') #grid(true) x = 0 while 1: s = ser.read() b = ord(s) h = [] h.append(b) x = x + 1 plot(t,h) ser.close ######################################################################## From haraldarminmassa at gmail.com Wed Nov 30 11:34:47 2005 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 30 Nov 2005 08:34:47 -0800 Subject: python speed In-Reply-To: <438db382$0$67257$157c6196@dreader2.cybercity.dk> References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133358884.407477.219560@g47g2000cwa.googlegroups.com> <438db382$0$67257$157c6196@dreader2.cybercity.dk> Message-ID: <1133368487.648595.50950@z14g2000cwz.googlegroups.com> >Faster than assembly? LOL... :) why not? Of course, a simple script like "copy 200 bytes from left to right" can be handoptimized in assembler and run at optimum speed. Maybe there is even a special processor command to do that. I learned that there was one generation of CPUs which had effectively a command to copy X bytes from left to right; but a specific version of that CPU did this command slower then a loop in certain situations. Some newer generations of that CPU and even some competitors CPU had that command implented correctly, and it was indeed faster than the loop. Now: is it rather likely that for a single programm a programmer is able to get it right for all CPUs? It even gets more complicated. The human mind is able to consider a certain amount of things at once, sth. like on-chip-cache or short-term-memory. Now with an ever growing complexity of processors, with cache lines, partyparallelexecution, branchprediction, out of order execution, multilevelcaching, hypermetathreading ... it may be that the usual availaible human brain is no longer capable of really knowing what happens. My guess is that the average code speed of a Rigopy could indeed be higher than the average code speed of the average assembler programmer. Harald From nick.smallbone at gmail.com Mon Nov 14 07:11:39 2005 From: nick.smallbone at gmail.com (Nick Smallbone) Date: 14 Nov 2005 04:11:39 -0800 Subject: PySizer 0.1 In-Reply-To: <3tqp2pFts5u3U1@individual.net> References: <1131922657.017880.218920@z14g2000cwz.googlegroups.com> <3tqp2pFts5u3U1@individual.net> Message-ID: <1131970298.991311.33670@g14g2000cwa.googlegroups.com> Claudio Grondi wrote: > A small hint about the Web-site: > At least to me, the links to the documentation as e.g. > > http://pysizer.8325.org/doc/auto/home/nick/sizer-trunk/doc/auto/scanner.html > are broken (no big thing, because the distro has it anyway). > Oops. That should be fixed now. From fccoelho at gmail.com Mon Nov 28 10:33:06 2005 From: fccoelho at gmail.com (Flavio) Date: 28 Nov 2005 07:33:06 -0800 Subject: importing a method In-Reply-To: References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> Message-ID: <1133191986.034689.59090@g14g2000cwa.googlegroups.com> This "new" module sounds pretty cool, too bad its deprecated... I would not want to add a dependancy to a deprecated module in my code. But maybe I'll check the code for instancemethod within it and see what it does. Fl?vio From hancock at anansispaceworks.com Sun Nov 27 01:05:28 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 27 Nov 2005 00:05:28 -0600 Subject: Syntax In-Reply-To: References: <1133065081.696769.32570@z14g2000cwz.googlegroups.com> Message-ID: <20051127000528.7b86d1f5@samwise.anansi> On Sat, 26 Nov 2005 20:54:49 -0800 Robert Kern wrote: > calad.sigilon at gmail.com wrote: > > So, two options: > > > > from os import * > > import os > > One of these two ways you're not supposed to use for > > security reasons, but I'm spacing on which one. > > I don't think there are any *security* reasons, but > stylistically, "import os" is greatly preferred. When > someone else reads your code, they will immediately know > where getcwd() comes from. It's not a question of "security" in the usual sense, but the first syntax imports a lot of stuff into the current namespace, increasing the risk of unintentionally clobbering local names. So it's certainly "riskier" in the sense of "likely to cause bugs". -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From mwm at mired.org Sat Nov 26 04:46:49 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 04:46:49 -0500 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> <86fypkim4x.fsf@bhuda.mired.org> <7xhd9zerfg.fsf@ruckus.brouhaha.com> Message-ID: <86oe47g2ra.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> Those two statements say the same thing. Part of the Python philosphy, >> from "import this", is that there should only be one obvious way to do >> it. By enabling that part of Python's philosphy, you're automatically >> limiting python to not allow other - specifically non-pythonic - ways >> to do the same thing. > Sometimes there are zero obvious ways to do it, or an obvious way that > doesn't work, so if you want to do it at all, you have to find a > contorted way. At that point it's normal to ask why there isn't an > obvious way that works. All too often, the answer is "that would be > un-Pythonic". Examples? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From grflanagan at yahoo.co.uk Thu Nov 3 07:36:52 2005 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 3 Nov 2005 04:36:52 -0800 Subject: Python for .NET and IronPython In-Reply-To: References: Message-ID: <1131021412.409880.42790@g44g2000cwa.googlegroups.com> John Salerno wrote: > Hi all. I'm currently learning C#, and I'm also interested in learning > Python In a similar position to yourself - learning both languages - I can definitely recommend Python ( though C# 's curly brackets might annoy you more than they did before!!) > so it seems like a decent > idea to want to integrate the two FWIW, what I've been doing lately is calling Python scripts from Windows.Forms apps, capturing their 'StdOut'. There's an article on http://www.thecodeproject.com which explains how you can do this asynchronously, but the following (C#) code is what I'm using ( imagine a Windows Form with a TextBox to enter the script name, another to enter any arguments for the script, and 'Run', 'Cancel' and 'Browse' CommandButtons). (assumes the script requires no user interaction) private void BrowseForScript_Click(object sender, System.EventArgs e) { if ( this.openFileDialog.ShowDialog() == DialogResult.OK ) { this.txtIO.Clear(); this.txtIO.Focus(); this.txtIO.AppendText( openFileDialog.FileName); } } private void Run_Click(object sender, System.EventArgs e) { System.Diagnostics.ProcessStartInfo startInfo; System.Diagnostics.Process process; string directory; string pyArgs; string script; script = this.txtIO.Text.Trim(); if ( script == null || script.Length == 0 ) { return; } try { directory = Path.GetDirectoryName( script ); script = Path.GetFileName( script ); } catch (ArgumentException) { MessageBox.Show("The script file path contains invalid characters.", "Invalid Script Path", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ( script.Length == 0 ) { MessageBox.Show("No script file has been specified.", "Invalid Script Path", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ( directory == null || directory.Length == 0 ) { directory = DEFAULT_SCRIPT_DIRECTORY; } pyArgs = this.txtArgs.Text.Trim(); startInfo = new ProcessStartInfo("python"); startInfo.WorkingDirectory = directory; startInfo.Arguments = script + " " + pyArgs; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; process = new Process(); process.StartInfo = startInfo; process.Start(); string s; while ((s = process.StandardOutput.ReadLine()) != null) { this.__application.Write( s + "\n" ); } while ((s = process.StandardError.ReadLine()) != null) { this.__application.Write( s + "\n" ); } } Gerard From twic at urchin.earth.li Tue Nov 22 20:35:04 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 23 Nov 2005 01:35:04 +0000 Subject: user-defined operators: a very modest proposal In-Reply-To: References: Message-ID: On Tue, 22 Nov 2005 jepler at unpythonic.net wrote: > Each unicode character in the class 'Sm' (Symbol, > Math) whose value is greater than 127 may be used as a user-defined operator. EXCELLENT idea, Jeff! > Also, to accomodate operators such as u'\N{DOUBLE INTEGRAL}', which are not > simple unary or binary operators, the character u'\N{NO BREAK SPACE}' will be > used to separate arguments. When necessary, parentheses will be added to > remove ambiguity. This leads naturally to expressions like > \N{DOUBLE INTEGRAL} (y * x**2) \N{NO BREAK SPACE} dx \N{NO BREAK SPACE} dy > (corresponding to the call (y*x**2).__u222c__(dx, dy)) which are clearly easy > to love, except for the small issue that many inferior editors will not clearly > display the \N{NO BREAK SPACE} characters. Could we use '\u2202' instead of 'd'? Or, to be more correct, is there a d-which-is-not-a-d somewhere in the mathematical character sets? It would be very useful to be able to distinguish d'x', as it were, from 'dx'. > * Do we immediately implement the combination of operators with nonspacing > marks, or defer it? As long as you don't use normalisation form D, i'm happy. > * Should some of the unicode mathematical symbols be reserved for literals? > It would be greatly preferable to write \u2205 instead of the other proposed > empty-set literal notation, {-}. Perhaps nullary operators could be defined, > so that writing \u2205 alone is the same as __u2205__() i.e., calling the > nullary function, whether it is defined at the local, lexical, module, or > built-in scope. Sounds like a good idea. \u211D and relatives would also be a candidate for this treatment. And for those of you out there who are laughing at this, i'd point out that Perl IS ACTUALLY DOING THIS. tom -- I DO IT WRONG!!! From apardon at forel.vub.ac.be Fri Nov 4 03:08:42 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 08:08:42 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <7xpsphlxri.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-11-03, Steven D'Aprano schreef : > On Thu, 03 Nov 2005 04:30:09 -0800, Paul Rubin wrote: > >> Steve Holden writes: >>> > class A: >>> > a = 1 >>> > b = A() >>> > b.a += 2 >>> > print b.a >>> > print A.a >>> > Which results in >>> > 3 >>> > 1 >>> > >>> I don't suppose you'd care to enlighten us on what you'd regard as the >>> superior outcome? >> >> class A: >> a = [] >> b = A() >> b.append(3) >> print b.a >> print a.a >> >> Compare and contrast. > > > I take it then that you believe that ints like 1 should be mutable like > lists? Because that is what the suggested behaviour implies. No it isn't. One other way, to implement the += and likewise operators would be something like the following. Assume a getnsattr, which would work like getattr, but would also return the namespace where the name was found. The implementation of b.a += 2 could then be something like: ns, t = getnsattr(b, 'a') t = t + 2 setattr(ns, 'a') I'm not arguing that this is how it should be implemented. Just showing the implication doesn't follow. -- Antoon Pardon From pythonnew at gmail.com Thu Nov 17 20:22:47 2005 From: pythonnew at gmail.com (Ben Bush) Date: Thu, 17 Nov 2005 17:22:47 -0800 Subject: How to draw a dash line in the Tkinter? Message-ID: <8c11e4350511171722r2edbf6bgc40c98fcfb1e57bc@mail.gmail.com> How to draw a dash line in the Tkinter? -------------- next part -------------- An HTML attachment was scrubbed... URL: From pythonnew at gmail.com Tue Nov 15 04:39:47 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 15 Nov 2005 01:39:47 -0800 Subject: compare list In-Reply-To: <4379A629.6060207@cc.umanitoba.ca> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <8c11e4350511142324j69b921cbta00549fcf9755aa2@mail.gmail.com> <4379A629.6060207@cc.umanitoba.ca> Message-ID: <8c11e4350511150139m185d74c2l5c6dd5a3014d52c@mail.gmail.com> On 11/15/05, Brian van den Broek wrote: > > Ben Bush said unto the world upon 2005-11-15 01:24: > > > > > > > Unfortunately, the indents got screwed up along the way. But the part > > > >>of my code you asked about was: > >> > >>for item in list1: > >> if item in list2: > >> if item + 1 in list1 and item + 1 in list2: > >> return True > >> > >>In some detail: > > > > >>Does that clarify it? > >> > >>Finally, your response to Alex would have been much more useful if > >>you'd quoted the error rather than just asserting that you got an > >>error :-) > >> > >>Best, > >> > >>Brian vdB > > Hi Ben, > > first, while there are those on the list/n.g. who differ, the > majoritarian view is that top posting isn't a good thing. At minimum, > if someone bothered to correct it, it would be nice if in a further > follow-up you didn't top-post again :-) > > Second, you might find the tutor list really helpful. It is where I > learned most of what I know, and I still read it more than c.l.p. It > is very newbie friendly. > > As for your question: > > >> Hi Brian, > > > > regarding "if item + 1 in list1 and item + 1 in list2:", > > my understanding is this will check whether the following item in > each list > > is the same. How does the code permit the situation that the order > does not > > matter? > > For example, for lisA and lisB, the comparison is true and the two > lists > > have 5 and 6 but different order. > > lisA=[1,2,3,4,5,6,9] > > lisB=[1,6,5] > > Many Thanks! > > > There are two distinct issues that might be the source of your > confusion. I will be explicit about both; pardon if only one applied. > > >>> num_list = [1, 42, 451] > >>> for item in num_list: print item, type(item) > > 1 > 42 > 451 > >>> > > Iterating over a list as I did makes item refer to each list member in > turn. So, item + 1 doesn't refer to the next item (except by accident > as it were when two items are sequential ints). Rather, it refers to > int that results from adding 1 to the int that is item. > > You might be thinking of list index notation instead: > > >>> index = 1 > >>> num_list[index], num_list[index + 1] > (42, 451) > >>> > > (General tip: putting a print or two in my original code would have > cleared that up very quickly.) > > So, that cleared up, are you wondering why item + 1 suffices, instead > of both item + 1 and item - 1? > > If so, consider that it the list1 has both n and n - 1 in it and we > iterate over list1 checking each case, eventually item will refer to n > - 1. In that case, item + 1 = n and we are covered after all. I did as > I did in my original code thinking it was probably quicker to have > only one test and pay the cost that there might be a quicker exit from > the iteration were I to test both item + 1 and item - 1. f it > mattered, I'd test for speed. Of course, if speed mattered and I could > ever remember to use sets :-) I'd follow Alex and Duncan's suggestions > instead! > > If that doesn't clear it up, give yourself a few short lists and run > test cases having inserted print statements to see what is going on. > To stop it all from whizzing by too fast, put in > > raw_input("Hit enter and I'll keep working") > > somewhere in the loops to slow things down. > > HTH, > > Brian vdB > > Brian, Really appreciate your help!!! Ben -- Thanks! Ben Bush -------------- next part -------------- An HTML attachment was scrubbed... URL: From pierre.barbier at cirad.fr Thu Nov 10 02:37:19 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 10 Nov 2005 08:37:19 +0100 Subject: What do you use as symbols for Python ? Message-ID: <4372f88a$0$31833$636a15ce@news.free.fr> When you need some symbols in your program, what do you use in Python ? For example, an object get a state. This state is more readable if expressed as a symbols, for example "opened", "closed", "error". Typically, in C or C++, I would use an enum for that: enum OBJECT_STATE { opened, closed, error } In CAML or Haskell I would use the union types: type ObjectState = Opened | Closed | Error In Ruby I would use the symbols : object.state = :opened object.state = :closed object.state = :error ... but I don't know what to use in Python ! Thanks, Pierre From erniedude at gmail.com Wed Nov 2 10:54:10 2005 From: erniedude at gmail.com (Ernesto) Date: 2 Nov 2005 07:54:10 -0800 Subject: * TypeError - Need help passings args In-Reply-To: References: <1130944044.311979.145660@g49g2000cwa.googlegroups.com> Message-ID: <1130946850.373696.72990@f14g2000cwb.googlegroups.com> Thanks, that ran without errors. The only problem now is that it launches devcon.exe without actually passing the parameters to the program. It's as if I just typed "devcon" at a Windows command prompt and pressed enter. I can't figure out why it doesn't accept my parameter. From noway at sorry.com Tue Nov 8 06:04:30 2005 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 08 Nov 2005 11:04:30 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442683.986618.17890@g14g2000cwa.googlegroups.com> Message-ID: <2D%bf.51545$Pe2.965736@twister2.libero.it> pinkfloydhomer at gmail.com wrote: > I just want an alias. What you want is impossible. But there are many workarounds. > I just want to be able to make a reference to any old thing in Python. > A list, an integer variable, a function etc. so that I, in complicated > cases, can make a shorthand. If "myRef" could somehow "point at" > something long an complicated like a[42]["pos"][-4], that might be > useful. One simple workaround: def createAlias(L, idx1, idx2, idx3): def setval(n): L[idx1][idx2][idx3] = n return setval k = createAlias(a, 42, "pos", -4) [...] n = computeValue(...) k(n) # store it! You will also find out that your case is actually very unlikely in well-designed code. You don't usually work with stuff with three level of nesting like a[][][], since it gets totally confusing and unmaintanable. You will end up always with objects with better semantic, and methods to modify them. So in the end you will always have a reference to the moral equivalent of a[42]["pos"], and that would be a well defined object with a method setThis() which will modify the moral equivalent of [-4]. -- Giovanni Bajo From twic at urchin.earth.li Tue Nov 22 20:55:00 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 23 Nov 2005 01:55:00 +0000 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 22 Nov 2005, Christoph Zwerschke wrote: > Fuzzyman schrieb: > >> Of course ours is ordered *and* orderable ! You can explicitly alter >> the sequence attribute to change the ordering. > > What I actually wanted to say is that there may be a confusion between a > "sorted dictionary" (one where the keys are automatically sorted) and an > "ordered dictionary" (where the keys are not automatically ordered, but > have a certain order that is preserved). Those who suggested that the > "sorted" function would be helpful probably thought of a "sorted > dictionary" rather than an "ordered dictionary." Exactly. Python could also do with a sorted dict, like binary tree or something, but that's another story. tom -- When I see a man on a bicycle I have hope for the human race. -- H. G. Wells From cochrane at esscc.uq.edu.au Wed Nov 2 23:23:53 2005 From: cochrane at esscc.uq.edu.au (Paul Cochrane) Date: Thu, 03 Nov 2005 14:23:53 +1000 Subject: Running autogenerated code in another python instance References: <43685941.1593033671@news.oz.net> Message-ID: On Wed, 02 Nov 2005 06:33:28 +0000, Bengt Richter wrote: > On Wed, 2 Nov 2005 06:08:22 +0000 (UTC), Paul Cochrane wrote: > >>Hi all, >> >>I've got an application that I'm writing that autogenerates python code >>which I then execute with exec(). I know that this is not the best way to >>run things, and I'm not 100% sure as to what I really should do. I've had a >>look through Programming Python and the Python Cookbook, which have given me >>ideas, but nothing has gelled yet, so I thought I'd put the question to the >>community. But first, let me be a little more detailed in what I want to >>do: >> Bengt, Thanks for your reply! > It's a little hard to tell without knowing more about your > user input (command language?) syntax that is translated to > or feeds the process that "autogenerates python code". Ok, I'll try and clarify things as much as I can. > E.g., is it a limited python subset that you are accepting as input, > or a command language that you might implement using the cmd module, or ? It's basically just a command language I guess. Perhaps it's best to explain using an example. Here's the pyvisi code that generates a very simple line plot using the vtk renderer module: """ Example of plotting lines with pyvisi """ # set up some data to plot from Numeric import * x = arange(10, typecode=Float) y = x**2 # example code for how a user would write a script in pyvisi from pyvisi import * # base level visualisation stuff # import the objects to render the scene using the specific renderer #from pyvisi.renderers.gnuplot import * # gnuplot from pyvisi.renderers.vtk import * # vtk #from pyvisi.renderers.plplot import * # plplot # define the scene object # a Scene is a container for all of the kinds of things you want to put # into your plot for instance, images, meshes, arrow/vector/quiver plots, # contour plots, spheres etc. scene = Scene() # create a LinePlot object plot = LinePlot(scene) # add some helpful info to the plot plot.title = 'Example 2D line plot' plot.xlabel = 'x' plot.ylabel = 'x^2' plot.linestyle = 'lines' # assign some data to the plot plot.setData(x, y) # render the scene to screen scene.render(pause=True, interactive=True) # save the scene out to file ## png plot.setData(x, y) # have to do this now because we've already # render()ed the scene, will be removed in the # future scene.save(fname="simpleLinePlot.png", format=PngImage()) This code then gets translated by the pyvisi module into the vtk-python code: import vtk from Numeric import * # LinePlot.__init__() _plot = vtk.vtkXYPlotActor() _renderer = vtk.vtkRenderer() _renderWindow = vtk.vtkRenderWindow() _renderWindow.AddRenderer(_renderer) _renderWindow.SetSize(640,480) _renderer.SetBackground(1,1,1) # Renderer._initRendererModule # LinePlot.setData() _x = array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]) _xData = vtk.vtkDataArray.CreateDataArray(vtk.VTK_FLOAT) _xData.SetNumberOfTuples(len(_x)) _y0 = array([0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0]) _y0Data = vtk.vtkDataArray.CreateDataArray(vtk.VTK_FLOAT) _y0Data.SetNumberOfTuples(len(_y0)) for i in range(len(_x)): _xData.SetTuple1(i,_x[i]) for i in range(len(_x)): _y0Data.SetTuple1(i,_y0[i]) _fieldData0 = vtk.vtkFieldData() _fieldData0.AllocateArrays(2) _fieldData0.AddArray(_xData) _fieldData0.AddArray(_y0Data) _dataObject0 = vtk.vtkDataObject() _dataObject0.SetFieldData(_fieldData0) _plot.AddDataObjectInput(_dataObject0) _plot.SetXValuesToValue() _plot.SetDataObjectXComponent(0,0) _plot.SetDataObjectYComponent(0,1) _plot.GetXAxisActor2D().GetProperty().SetColor(0, 0, 0) _plot.GetYAxisActor2D().GetProperty().SetColor(0, 0, 0) _renderer.SetBackground(1.0, 1.0, 1.0) _lut = vtk.vtkLookupTable() _lut.Build() _colours = [] _colours.append(_lut.GetColor(0)) _plot.SetPlotColor(0, _colours[0][0], _colours[0][1], _colours[0][2]) _plot.SetPosition(0.1, 0.1) _plot.SetWidth(0.8) _plot.SetHeight(0.8) # Scene.render() _lut = vtk.vtkLookupTable() _refLut = vtk.vtkLookupTable() _lut.Build() _refLut.Build() for _i in range(256): _lut.SetTableValue(_i, _refLut.GetTableValue(255-_i)) _iRenderer = vtk.vtkRenderWindowInteractor() _iRenderer.SetRenderWindow(_renderWindow) # LinePlot.render() _renderer.AddActor2D(_plot) _plot.SetTitle('Example 2D line plot') _plot.SetXTitle('x') _plot.SetYTitle('x^2') _renderWindow.Render() _iRenderer.Start() Which is pretty ugly for the user to have to get to grips with, so I'm trying to simplify the interface to the back end. I'm writing other backends so that one only needs to change one line of code to then use gnuplot or plplot as the renderer to generate the plot. Of course some renderers can do things others can't, but that's another issue... > There are lots of easy things you could do without generating and exec-ing > python code per se. I'd love to know of other options. I like the idea of generating the code one would have to write for a particular renderer so that if the user wanted to, they could use the autogenerated code to form the basis of a specific visualisation script they could then hack themselves. I also like it because I can see how the pyvisi code maps directly to the back end. > How complex is a user session state? Not 100% sure. My intention is that this is just a simple matter of translating the commands specified at the high level into the lower level stuff in the background. It can handle plotting several different graphs in a loop as the data used to generate the graph changes, and it can handle interactive display of the graphics in vtk (a vtk feature really, via OpenGL), but nothing too tricky there. exec() is handy for running commands generated on the fly, however, it doesn't keep the state of the interpreter and so any variables generated on a previous call are lost. Also, exec ignores globals etc (at least AFAIK). What would be great would be to run the generated commands within the same scope and state, then I wouldn't need to worry about this separate thread/process idea. I just don't know how to do that. > What modifies it? > What actions are possible? History? Undo? There's no history or undo, just processing of the script. > Is the data a static passive > resource to view, or partly generated or made accessible by prior actions > in a session? The data can be generated by prior actions in a given python script, but basically pyvisi is set up to grab the data it's passed, and then work out how best to render it. So in some sense the data is static and passive, however can change at some later date, but one has to recall the setData() method and then the render() method of the scene object to process any changes that have occured in the data. > Single user or collaborative? Definitely single user. > Shared access to everything or > only to static data? Etc., etc. Preferably only shared access to static data, but I do some variable name mangling to try and keep autogenerated variables separate to anything the user has created themselves. > Some examples of user input and corresponding generated python might help, > with some idea of the kind of visualization aspects being controlled ;-) With my initial post I didn't want to put in examples as it was already quite long and I didn't want to put people off replying. btw: I really appreciate your feedback; I usually work best bouncing ideas off people to find a clear way to do something. One of the main ideas of the module is to distill the common visualisation tasks down to a simple set of commands, and then let the interface work out how to actually implement that. One wants to be able to put titles, and labels and axes on things, one wants to plot 3D surfaces of data, arrows of vector fields, ellipses of tensor data, isosurfaces of 3D scalar data, and be able to display this to the screen and save to file. Other visualisation aspects to be controlled are such things as camera angles, number of contours in a plot, different kinds of colourmaps, etc. Just to try and be of some help, here's another example of plotting some data and its output. This time it's plotting of a random vector field with arrows in three dimensions. First the pyvisi code: """ Example of plotting a 3D vector field with pyvisi """ # set up some data to plot from Numeric import * dim = 10 # initialise the positions of the vectors x = zeros((dim,dim), typecode=Float) y = zeros((dim,dim), typecode=Float) z = zeros((dim,dim), typecode=Float) # initialise the vector displacements # (I may need to rethink how this works in the interface) dx = zeros((dim,dim), typecode=Float) dy = zeros((dim,dim), typecode=Float) dz = zeros((dim,dim), typecode=Float) # set the positions randomly, and set the displacements to some smaller # random number but of mean zero instead of distributed between 0 and 1 import random random.seed() for i in range(dim): for j in range(dim): x[i,j] = random.random() y[i,j] = random.random() z[i,j] = random.random() dx[i,j] = (random.random()-0.5)/5.0 dy[i,j] = (random.random()-0.5)/5.0 dz[i,j] = (random.random()-0.5)/5.0 # example code for how a user would write a script in pyvisi from pyvisi import * # base level visualisation stuff # import the objects to render the scene using the specific renderer #from pyvisi.renderers.gnuplot import * # gnuplot from pyvisi.renderers.vtk import * # vtk #from pyvisi.renderers.povray import * # povray # define the scene object # a Scene is a container for all of the kinds of things you want to put # into your plot for instance, images, meshes, arrow/vector/quiver # plots, # contour plots, spheres etc. scene = Scene() # create a ArrowPlot3D object plot = ArrowPlot3D(scene) # add some helpful info to the plot plot.title = 'Example 3D arrow/quiver/vector field plot' plot.xlabel = 'x' plot.ylabel = 'y' plot.zlabel = 'z' # assign some data to the plot plot.setData(x, y, z, dx, dy, dz) # render the scene to screen scene.render(pause=True, interactive=True) # save the scene out to file plot.setData(x, y, z, dx, dy, dz) # have to do this because we've already # render()ed the scene. This requirement # will be removed in the future scene.save(fname="arrowPlot3D.png", format=PngImage()) And now the generated vtk-python code: import vtk from Numeric import * _renderer = vtk.vtkRenderer() _renderWindow = vtk.vtkRenderWindow() _renderWindow.AddRenderer(_renderer) _renderWindow.SetSize(640,480) _renderer.SetBackground(1,1,1) # Renderer._initRendererModule # ArrowPlot3D.__init__() # ArrowPlot3D.setData() _x = array([0.877228328994, 0.412795474983, 0.163560730946, 0.89780023349, 0.129244456665, 0.40180234598, 0.542135110974, 0.46894547296, _y = array([0.750790237727, 0.355648864325, 0.659517997105, 0.0381646378866, _z = array([0.26125343592, 0.941964065844, 0.510850248162, 0.131409524918, _dx = array([0.0474228215121, -0.0940162717243, -0.0926294230912, _dy = array([0.0853229942053, 0.0358464500795, -0.00461198953457, _dz = array([-0.0559212949124, 0.0827739088553, 0.0849306644324, _points = vtk.vtkPoints() _points.SetNumberOfPoints(100) _points.InsertPoint(0, 0.877228, 0.750790, 0.261253) _vectors = vtk.vtkFloatArray() _vectors.SetNumberOfComponents(3) _vectors.SetNumberOfTuples(100) _vectors.SetName("vectors") _vectors.InsertTuple3(0, 0.047423, 0.085323, -0.055921) _grid = vtk.vtkUnstructuredGrid() _grid.SetPoints(_points) _grid.GetPointData().AddArray(_vectors) _grid.GetPointData().SetActiveVectors("vectors") # Scene.render() _lut = vtk.vtkLookupTable() _refLut = vtk.vtkLookupTable() _lut.Build() _refLut.Build() for _i in range(256): _lut.SetTableValue(_i, _refLut.GetTableValue(255-_i)) _iRenderer = vtk.vtkRenderWindowInteractor() _iRenderer.SetRenderWindow(_renderWindow) # ArrowPlot3D.render() _arrow = vtk.vtkArrowSource() _maxNorm = _grid.GetPointData().GetVectors().GetMaxNorm() _glyph = vtk.vtkGlyph3D() _glyph.ScalingOn() _glyph.SetScaleModeToScaleByVector() _glyph.SetColorModeToColorByVector() _glyph.SetScaleFactor(0.1/_maxNorm) _glyph.SetInput(_grid) _glyph.SetSource(_arrow.GetOutput()) _glyph.ClampingOff() _stripper = vtk.vtkStripper() _stripper.SetInput(_glyph.GetOutput()) _lut = vtk.vtkLookupTable() _lut.Build() _refLut = vtk.vtkLookupTable() _refLut.Build() for i in range(256): _lut.SetTableValue(i, _refLut.GetTableValue(255-i)) _mapper = vtk.vtkPolyDataMapper() _mapper.SetInput(_stripper.GetOutput()) _mapper.SetScalarRange(0, _maxNorm) _actor = vtk.vtkActor() _actor.SetMapper(_mapper) _renderer.AddActor(_actor) _font_size = 14 _textProp = vtk.vtkTextProperty() _textProp.SetFontSize(_font_size) _textProp.SetFontFamilyToArial() _textProp.BoldOff() _textProp.ItalicOff() _textProp.ShadowOff() _textProp.SetColor(0,0,0) _titleMapper = vtk.vtkTextMapper() _titleMapper.SetInput("Example 3D arrow/quiver/vector field plot") _titleProp = _titleMapper.GetTextProperty() _titleProp.ShallowCopy(_textProp) _titleProp.SetJustificationToCentered() _titleProp.SetVerticalJustificationToTop() _titleProp.SetFontSize(18) _titleActor = vtk.vtkTextActor() _titleActor.SetMapper(_titleMapper) _titleActor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay() _titleActor.GetPositionCoordinate().SetValue(0.5, 0.95) _renderer.AddActor(_titleActor) _axes = vtk.vtkCubeAxesActor2D() _axes.SetCamera(_renderer.GetActiveCamera()) _axes.SetFlyModeToOuterEdges() _axes.SetBounds(min(_x)-_maxNorm, max(_x)+_maxNorm, min(_y)-_maxNorm, max(_y)+_maxNorm, min(_z)-_maxNorm, max(_z)+_maxNorm) _axes.SetXLabel("x") _axes.SetYLabel("y") _axes.SetZLabel("z") _axesProp = _axes.GetProperty() _axesProp.SetColor(0,0,0) _axesTitleProp = _axes.GetAxisTitleTextProperty() _axesTitleProp.ShallowCopy(_textProp) _axesLabelProp = _axes.GetAxisLabelTextProperty() _axesLabelProp.ShallowCopy(_textProp) _axesLabelProp.SetFontSize(8) _renderer.AddActor(_axes) _renderer.ResetCamera() _renderer.SetBackground(1,1,1) _renderWindow.Render() _iRenderer.Start() As you can see from the snipping, there's good reason for me to want to share data objects around... I know it's ugly, but it got it working quickly (I'm a scientist, not a proper software developer...) Hopefully you can also see that the pyvisi script is a _lot_ simpler than what is required to generate the visualisation. Ok. I think that's enough for one post. Again, thanks heaps for your reply, I do appreciate it, and hopefully now you can understand my question a bit more clearly. I look forward to hearing from you soon. Regards, Paul -- Paul Cochrane Earth Systems Science Computational Centre University of Queensland Brisbane Queensland 4072 Australia E: cochrane at esscc dot uq dot edu dot au From martin.witte at gmail.com Wed Nov 9 14:09:43 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 9 Nov 2005 11:09:43 -0800 Subject: Make an exe file as a Windows Service In-Reply-To: <1131553008.253205.76110@g14g2000cwa.googlegroups.com> References: <1131553008.253205.76110@g14g2000cwa.googlegroups.com> Message-ID: <1131563383.450936.215470@g44g2000cwa.googlegroups.com> py2exe has an option to create a MS Windows service (see http://www.py2exe.org) from a Python script From calfdog at yahoo.com Thu Nov 3 13:20:41 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 3 Nov 2005 10:20:41 -0800 Subject: Web automation (was: Pressing a Webpage Button) In-Reply-To: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> Message-ID: <1131042041.155434.254810@g44g2000cwa.googlegroups.com> Hello, It's fairly easy to do see code below: ########################################################################## from win32com.client import DispatchEx import time # instaniate a new IE object ie = DispatchEx('InternetExplorer.Application') # Naviagte to the site ie.Navigate("www.google.com") # You have to wait for the site to load. Best use a method that check for readystate ="complete" and ie.Busy while ie.Busy: time.sleep(0.1) doc = self._ie.Document while doc.readyState != 'complete': time.sleep(0.1) ie.Document.all["q"].value ="Python rocks" ie.Document.all["btnG"].click() I have a wrapper that does all this for you. It is geared for people in QA. You can download if here URL : http://pamie.sourceforge.net To use it is simple" The wait to laod the doc is already in the code ########################################### from cPAMIE import PAMIE ie=PAMIE() ie.Navigate(www.google.com) # Set the text - arguments - value to set, textbox name, formname ie.SetTextBox('Python","q","f") ie.ClickButton("btnG,"f") ie.ClickLink('Python Programming Language') Hope this helps Rob qwweeeit at yahoo.it wrote: > Hi all, > Elliot Temple on the 1 June wrote: > > How do I make Python press a button on a webpage? I looked at > > urllib, but I only see how to open a URL with that. I searched > > google but no luck. > > > For example, google has a button how would i make a script to press that button? > > I have a similar target: web automation, which > needs not only to press web buttons but also > fill up input fields (like in your case the > search field of Google). > On the suggestion of gmi... at gmail.com, I tried > twill (http://www.idyll.org/~t/www-tools/twill.html). > > I think it can be the solution: > I already applied it for reading data from an asp file > (http://groups.google.it/group/comp.lang.python/browse_frm/thread/23b50b2c5f2ef377/2e0a593e08d28baf?q=qwweeeit&rnum=2#2e0a593e08d28baf) > I try to solve your problem using the interactive mode > (but twill can also be called as a module). > > Set twill in interactive mode: twill-sh > - load Google webpage: > go www.google.it (I'm Italian!) > - show the page with the command 'show' > - Get the page forms: > showforms > > ## __Name______ __Type___ __ID________ __Value__________________ > hl hidden (None) it > ie hidden (None) ISO-8859-1 > q text (None) > meta radio all [''] of ['', 'lr=lang_it', > 'cr=count ... > 1 btnG submit (None) Cerca con Google > 2 btnI submit (None) Mi sento fortunato > current page: http://www.google.it > > The input field is q (Type:text), while there are two buttons > (Type: submit) and a radio button meta (Type: radio). > > - fill values: > fv 0 q twill > (being "twill" the search string") > - press the search button: > fv 1 btnG "Cerca con Google" > submit > twill answers with the query to Google: > http://www.google.it/search?hl=it&ie=ISO-8859-1&q=twill&btnG=Cerca+con+Google&meta= > - save the search result on a file: > save_html /home/qwweeeit/searching_twill.html > > Here they are the 1st 10 hits of the search! > Don't ask me to continue! Perhaps asking to the author of twill > (C. Titus Brown)... > > With such a method you can bypass the Google's restrictions, because > you are using the browser (only building automatically the query). > > And this answers to the right observation of Grant Edwards: > > Ah, never mind. That doesn't work. Google somehow detects > > you're not sending the query from a browser and bonks you. > > Bye. From y.glodt at sitasoftware.lu Wed Nov 9 08:32:07 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 09 Nov 2005 14:32:07 +0100 Subject: append to non-existing list In-Reply-To: <17265.63091.388847.972049@montanaro.dyndns.org> References: <4371EFBC.1030502@sitasoftware.lu> <17265.63091.388847.972049@montanaro.dyndns.org> Message-ID: <4371FA57.40206@sitasoftware.lu> skip at pobox.com wrote: > Yves> My question is: Is there no way to append to a non existing list? > > My question in return is: How is Python supposed to know that pkcolumns is > supposed to be a list instead of some other type of object that happens to > define an append() method? I am fairly new to python (and I like it more and more), but I can not answer this question... As I said, where I come from it is possible, and how they do it is explained a little here: http://lu.php.net/manual/en/language.types.type-juggling.php As I want to learn, I will work with python the pythonic way, but sometimes I just fall back to what I know from php... :-) Thanks for your answer and the example code, Yves p.s. thanks for the "import this" hint > For example, my code might contain this class > definition before the suspect pkcolumns.append() call: > > class MaxLengthList: > def __init__(self, maxsize=0): > self.data = [] > self.maxsize = maxsize > > def append(self, item): > if self.maxsize and len(self.data) == self.maxsize: > del self.data[0] > self.data.append(item) > > def __getattr__(self, attr): > return getattr(self.data, attr) > > I think it would be perfectly reasonable for Python to choose to instantiate > my MaxLengthList instead of a plain old list. > > Yves> I am lazy for declaring it first, IMHO it bloats the code, and > Yves> (don't know if it's good to say that here) where I come from (php) > Yves> I was used to not-needing it... > > I don't know php, but would also have to wonder how it knows to create a > list instead of an integer (for example). > > Finally, from the Zen of Python (try "import this" at an interpreter > prompt): > > In the face of ambiguity, refuse the temptation to guess. > > Skip > > . > From gene.tani at gmail.com Tue Nov 29 10:41:33 2005 From: gene.tani at gmail.com (gene tani) Date: 29 Nov 2005 07:41:33 -0800 Subject: Precision for equality of two floats? In-Reply-To: References: Message-ID: <1133278893.518431.150090@g49g2000cwa.googlegroups.com> Anton81 wrote: > Hi! > > When I do simple calculation with float values, they are rarely exactly > equal even if they should be. What is the threshold and how can I change > it? > > e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:" > > Anton googled for "floating point" "comparison tolerance" http://www.boost.org/libs/test/doc/components/test_tools/floating_point_comparison.html From alexs at advfn.com Fri Nov 4 05:54:27 2005 From: alexs at advfn.com (Alex Stapleton) Date: Fri, 4 Nov 2005 10:54:27 +0000 Subject: Most efficient way of storing 1024*1024 bits In-Reply-To: <1131099979.328947.45740@o13g2000cwo.googlegroups.com> References: <1130973885.746466.208470@g44g2000cwa.googlegroups.com> <1131099979.328947.45740@o13g2000cwo.googlegroups.com> Message-ID: <7F2249CD-86CB-425C-AA16-514BC80665A2@advfn.com> On 4 Nov 2005, at 10:26, Ben Sizer wrote: > Tom Anderson wrote: > >> On Wed, 2 Nov 2005, Dan Bishop wrote: >> >> >>> Tor Erik S?nvisen wrote: >>> >>> >>>> I need a time and space efficient way of storing up to 6 million >>>> bits. >>>> >>> >>> The most space-efficient way of storing bits is to use the bitwise >>> operators on an array of bytes: >>> >> >> Actually, no, it's to xor all the bits together and store them in >> a single >> boolean. >> > > I'd use 'or' rather than 'xor'. The or operator is more likely to > yield > a '1' at the end of it, and a 1 is narrower than a 0, obviously making > it more efficient to store. Typical gas guzzling, SUV driving american logic. A would obviously use more POWER and hence INCREASE GLOBAL WARMING leading to the ultimate DEATH of EVERYBODY you know and LOVE! From pythonnew at gmail.com Tue Nov 15 06:45:03 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 15 Nov 2005 03:45:03 -0800 Subject: compare list In-Reply-To: <8c7f10c60511150328sfe52e8q@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <1d987df30511142330t39b137fdpdc9eee56e73d6e1f@mail.gmail.com> <4379AA95.80806@cc.umanitoba.ca> <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> <8c7f10c60511150227v297140e1n@mail.gmail.com> <1d987df30511150258j7848d3d5o61905f5ac935a6b0@mail.gmail.com> <8c7f10c60511150305p29c7ab48u@mail.gmail.com> <8c11e4350511150316l3f35253dkd42f98842e55119a@mail.gmail.com> <8c7f10c60511150328sfe52e8q@mail.gmail.com> Message-ID: <8c11e4350511150345k2cfbd0fex85e8686213de428@mail.gmail.com> On 11/15/05, Simon Brunning wrote: > > On 15/11/05, Ben Bush wrote: > > an error reported: > > Traceback (most recent call last): > > File > > > "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > > line 310, in RunScript > > exec codeObject in __main__.__dict__ > > File "C:\temp\try.py", line 8, in ? > > from sets import Set as set > > ImportError: cannot import name Set > > >>> > > Works for me. You don't have a sets module of your own, do you? Try > this, and report back what you see: > > import sets > print sets.__file__ > print dir(sets) > > -- > Cheers, > Simon B, > simon at brunningonline.net, > http://www.brunningonline.net/simon/blog/ > I found I named the following python file as sets.py, which brought the problem (is that right?). i changed it to other name and it works. But the logic output is wrong. from sets import Set as set lisA=[1,2,5,9] lisB=[9,5,0,2] lisC=[9,5,0,1] def two(sequence1, sequence2): set1, set2 = set(sequence1), set(sequence2) return len(set1.intersection(set2)) == 2 print two(lisA,lisB) False(should be true!) -- Thanks! Ben Bush -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.daniels at acm.org Mon Nov 21 08:09:16 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 21 Nov 2005 05:09:16 -0800 Subject: Underscores in Python numbers In-Reply-To: <4381016f$0$4205$626a14ce@news.free.fr> References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132460920.666321.264290@f14g2000cwb.googlegroups.com> <4381016f$0$4205$626a14ce@news.free.fr> Message-ID: <4381c575$1@nntp0.pdx.net> Bruno Desthuilliers wrote: > So even if it's far from a common use case for *most* Python users, it > may be a common use case for *some* Python users. > > Also, someone mentionned the use of Python as a configuration langage - > which is probably a much more common use case. > > So FWIW, I'd be +1 on adding it *if and only if*: > - it's trivial to implement [1] > - it doesn't break older code > > and +1 on the space as group delimiter BTW. > > [1]: I never wrote a language by myself, but I've played a bit with > parsers and lexers, and I _guess_ (which implies I may be wrong !-) it > wouldn't require much work to add support for a "literal numeric > grouping" syntax in Python. Since I've been trying to speed up the digit-scan code, I can say that any ignorable will slow the loop (counting digits gives you an integral logarithm to the base, and you can tell if you can convert quickly). However, Unicode must have ignore ables apparently, so (at least in the Unicode case) they may have to be dealt with. Also, a parser hack won't do (for speed), you have to get the entire number and translate it at one go. The space smacks of expecting a parser change, where you might expect: pi = (3.1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 5923078164 0628620899 8628034825 3421170679 8214808651 3282306647 0938446095 5058223172 5359408128 ) to work (allowing any whitespace and line breaks and ...). Also, it would be a trifle frustrating to translate: distance = (1 000 000 000 000 000 000 000 000 000 000.) Which looks like an integer for a long time. I'd say if we go for anything, we should follow the Ada lead of allowing underscore, only allow single underscores (so 1__000 is an error). I am happier with those applications that want this using their own function, however: pi = FloatConv('3.1415926535 8979323846 2643383279 5028841971 ' '6939937510 5820974944 5923078164 0628620899 ' '8628034825 3421170679 8214808651 3282306647 ' '0938446095 5058223172 5359408128') Since the use case is long constants, can we generally agree they should be named and set out as globals in the module? And in such a case, the cost of calling something like FloatConv (or whatever) becomes negligible. As to interactive use, I just don't see that having things like IntConv, FloatConv around strings is a real hardship -- for me the hardship is almost always trying to verify the digits are typed in correctly, not the extra function call. -- -Scott David Daniels scott.daniels at acm.org From chris.mccoy at spirentcom.com Thu Nov 3 00:33:40 2005 From: chris.mccoy at spirentcom.com (Chris McCoy) Date: Thu, 3 Nov 2005 00:33:40 -0500 Subject: Nested List Question References: <1130995475_2055@spool6-east.superfeed.net> <1h5f4t2.1yv785h120xalfN%aleax@mail.comcast.net> Message-ID: <1130996191_2067@spool6-east.superfeed.net> Thank you! I've been banging my head against the wall! Chris M. "Alex Martelli" wrote in message news:1h5f4t2.1yv785h120xalfN%aleax at mail.comcast.net... > Newsfeeds wrote: > >> Hello All, >> >> Could anyone tell me why this code produces the output it does? > ... >> gridSystemId = [[None]*columns]*rows > > You've made gridSystemID a list of `rows` references to the SAME "inner" > list, so the behavior you observe is the only possible one. > > If you want copies instead, ASK for copies...: > > gridSystemId = [ [None]*columns for x in xrange(rows) ] > > > Alex > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-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 bokr at oz.net Tue Nov 29 11:52:41 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 29 Nov 2005 16:52:41 GMT Subject: General question about Python design goals References: Message-ID: <438c6bdd.226677104@news.oz.net> On 29 Nov 2005 08:27:43 GMT, Antoon Pardon wrote: >On 2005-11-28, Duncan Booth wrote: >> Antoon Pardon wrote: >> >>> >>> No I gave an example, you would implement differently. But even >>> if you think my example is bad, that would make it a bad argument >>> for tuples having list methods. That is not the same as being >>> a good argument against tuples having list methods. >> >> Tuples don't have list methods, therefore any code which seems to require a >> tuple with list methods should make you stop and consider whether your >> design is wrong. > >IMO that is a non-sequitur, because that makes what is good or bad >design dependand on the language used. > >If I have a design that seems to require tuples with a count method, >then wether that is a good or bad design doesn't depend on >whether or not python allows that or not. > No, but if your requirement is to count __eq__ - matching items in a tuple, maybe your sense of orthogonality ought to abstract out the sequence aspect in some other way than seeing it as a seeming method requirement for tuple. A tuple.count method has implications about attribute access to a special object, tuple, which then you have to deal with for every new object you introduce, unless you want to inherit it from object, but that means object becomes a mega swiss army knife in short order. So IMO the thing is not to ask for a specific solution like "why not a count method for tuples?" You'll just get answers to that literal question, with some elaborations. Instead, if you put it in the form of what your general requirement really is (I'm guessing ;-) which I assume is to be able to apply list count method _functionality_ to anything which quacks like a list, including tuples etc. In short, anything iterable. Now the problem is to bring program and data together with some spelling in python. data.method() is certainly one spelling, but so is method(data). You gain something either way. The first allows you to associate the method and data without executing the method, i.e., data.method is a bound method object that has the data-method association built in, and it can be passed around. method(data) does the call right away and uses a diferent name space search path to find method, and is not necessarily associated with type(data). To ask for common methods for all objects that exhibit some similar aspect is to entangle their types in some way or to duplicate stuff. Sometimes it's fine to derive from a common base etc., but why not a built-in count function that does something like (untested) def count(obj, match_item, eq=operator.eq): return sum(1 for item in iter(obj) if eq(item, match_item)) which would give a little flexibility about eq comparison as well as wide applicability to any sequence? index too (untested) def index(obj, match_item, eq=operator.eq): try: return (i for i, item in enumerate(obj) if eq(item, match_item)).next() except StopIteration: raise ValueError('index(seq, item): item not in seq') why doesn't list have a find like str? ;-) def find(obj, match_item, eq=operator.eq): try: return (i for i, item in enumerate(obj) if eq(item, match_item)).next() except StopIteration: return -1 One could create an alternate spelling for obj.count(thing) using the count function above. You can spell it now as count.__get__(obj, type(obj))(thing) if you want to duplicate the effect of having the count function retrieved from type(obj) as if it were a method defined there. Or you can spell it count(obj) which doesn't seem too bad ;-) But now the problem is cluttering the __builtins__ space. So maybe it would be better to write from sequence_goodies import count ... count(obj) Do you really want a count method for tuple? Or is that maybe not as clean is it seemed? All the issues aren't usually immediatly apparent, so IMO the more we focus on abstract functionality desired, the more likely we will get helpful solution ideas for a menu of choices, and avoid prematurely discussing whether we should have pumpkin pie with or without whipped cream, when finally we might all like strawberries and cream better, if someone had thought of it. Regards, Bengt Richter From bonono at gmail.com Thu Nov 10 06:25:52 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 03:25:52 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131595096.310029.98740@g43g2000cwa.googlegroups.com> <1131596283.073069.165700@g43g2000cwa.googlegroups.com> <1131620733.240589.296510@g14g2000cwa.googlegroups.com> Message-ID: <1131621952.208466.323880@z14g2000cwz.googlegroups.com> I use "list" in the name in "english"/general sense(say a list in haskell is lazily evaluated), it could be a list or it could be a lazily evaluated iterable. The original post is really just about "when" or may be "until" syntax that makes it a bit shorter to read and hopefuly easier to understand. Leif K-Brooks wrote: > Wrapping a function in a generator expression doesn't magically make it > lazily evaluated. The whole list has to be generated and returned; > using a generator expression instead of a list comprehension just means > that it doesn't need to be copied in memory. From guy.lateur at b-b.be Thu Nov 24 12:46:43 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 24 Nov 2005 17:46:43 GMT Subject: Locking a file under Windows References: Message-ID: <70nhf.56299$EG6.3187806@phobos.telenet-ops.be> Correction: it's probably best to use the Flock class by John Nielsen. Much cleaner and working great. Info can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/Windows_NT_Files_.2d.2d_Locking.html Best regards, g "Guy Lateur" schreef in bericht news:qKlhf.56244$Hp7.3644537 at phobos.telenet-ops.be... > > I guess it'd be better if I use the second suggestion, i.e. temporarily > renaming the file for writing, and renaming it back to unlock it. > > Cheers, > g > > > From rurpy at yahoo.com Tue Nov 22 18:21:07 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 22 Nov 2005 15:21:07 -0800 Subject: about sort and dictionary References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> Message-ID: <1132701667.183254.166910@g47g2000cwa.googlegroups.com> "Steven D'Aprano" wrote in message news:pan.2005.11.22.21.42.58.763662 at REMOVETHIScyber.com.au... > On Tue, 22 Nov 2005 08:53:07 -0800, rurpy wrote: > > > I am not a complete newb at python, but I am still pretty new. > > I too thought immediately that the output should be 3,2,1, 1,2,3. > > What you are saying is that a.reverse() should *both* change a in place > *and* return a reference to the same list. Yes. I don't see a problem with this. > > I used reverse() and sort() a couple time and of course read > > the docs before I did. I noted they do the change inplace, and > > don't find rememering that to be a terrible burden. Actually, I > > get rather annoyed by the comment that they return None "as > > a reminder" that the change is inplace. How arrogant! While > > I'm sure the designers had kindly intentions. my memory, though > > bad, is not that bad, and I object to being forced to write code > > that is more clunky than need be, because the designers thought > > they needed to help me with my memory. > > Built-in methods with side-effects (sort, reverse, update, clear, etc.) > return None because every function must return something, not because it > is a reminder. Python is not Pascal, and there are no procedures. Quoting directly from the Library Reference: "To remind you that they operate by side effect, they don't return the sorted or reversed list." > There are four possibilities for a construction like list.sort(): > > (1) sort the list in place and return a reference to the same list; > (2) sort the list in place and return a copy of the same list; > (3) sort the list in place and return None; > (4) don't sort in place and return a sorted list. > > No solution is always right, no solution is always wrong, but the most > flexible is a combination of (3) and (4). Python now has that with sort() > and sorted(). Prior to the addition of sorted() to the language, (3) was > considered the best solution because of a simple Python principle: never > duplicate objects unless explicitly told to. #2 makes no sense. I see the primary difference as inplace or copy sort, and the return value as a secondary issue: (1) Leave orignal list alone and sort a copy. Obviously this has to return a reference to that copy. (2) Sort list in place and... (2a) Don't return anything (i.e. return None) (2b) Return a reference to the list. (2b) is clearly the most flexible (of the inplace options) because it subsumes option (2a) -- if is you don't want to use the returned refernce for stylistic reasons, then don't. I think this is just another (admittedly minor) case of Python's designers using Python to enforce some idea of programming style purity. From peno at mailme.org Sat Nov 5 10:47:50 2005 From: peno at mailme.org (Peter Notebaert) Date: Sat, 05 Nov 2005 15:47:50 GMT Subject: lists <-> tuple References: <1130973892.137886.170410@f14g2000cwb.googlegroups.com> Message-ID: "Jim" wrote in message news:1130973892.137886.170410 at f14g2000cwb.googlegroups.com... >> Tuples or lists for matrix-like functionality? > > Use lists. Tuples are meant for small immutable sets of things that go > together. Lists are more like arrays, and you can assign to one > existing element if you want. > > One exception, is a short vector is often a tuple like (x, y, z) and > you might want to multiply that vector by your matrix. You can convert > a tuple to a list with list(aTuple) or back with tuple(aList.) > > Even better, take a look at numarray (or numpy or scipy or scipy_core.) > They all have really nice matrix code and there are C APIs that let > you manipulate them. Chances are they do everything you're intending > to implement. > > Immutability example: > tup = ("a", "b", "c") > tup[1] = "g" > Traceback (most recent call last): > File "", line 1, in ? > TypeError: object does not support item assignment > lst = ["a", "b", "c"] > lst[1] = "g" > lst > ['a', 'g', 'c'] > > > -Jim > Thanks! From Michael.J.Fromberger at Clothing.Dartmouth.EDU Fri Nov 4 00:29:17 2005 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Fri, 04 Nov 2005 00:29:17 -0500 Subject: Burrows-Wheeler (BWT) Algorithm in Python References: <1130919309.381711.305450@f14g2000cwb.googlegroups.com> <1131048758.719582.204090@g43g2000cwa.googlegroups.com> Message-ID: In article <1131048758.719582.204090 at g43g2000cwa.googlegroups.com>, bearophileHUGS at lycos.com wrote: > Michael J. Fromberger: > > I can send you a Python implementation I wrote, if you like; but if > > you're interested in better understanding how the transform works, > > I would recommend you try writing your own implementation. > > I'd like to see it, if you want you can put it somewhere or send it > directly. You can grab a copy here: http://www.cs.dartmouth.edu/~sting/sw/bwt.py Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From kylotan at gmail.com Wed Nov 23 04:29:41 2005 From: kylotan at gmail.com (Ben Sizer) Date: 23 Nov 2005 01:29:41 -0800 Subject: a new design pattern for Python Library? In-Reply-To: <1132709883.708313.279720@g44g2000cwa.googlegroups.com> References: <1132709883.708313.279720@g44g2000cwa.googlegroups.com> Message-ID: <1132738181.664201.272500@g44g2000cwa.googlegroups.com> The Eternal Squire wrote: > I tend to use this design pattern a lot in order to aid in > compartmentalizing interchangeable features in a central class that > depend on the central class's data. I'm afraid I've read this paragraph and the code 3 times and I still have no idea what you're trying to convey. Perhaps it's just because your example is too abstract to me. It does look like it obscures the role of the classes involved however, which doesn't seem like a good thing to me. What do you consider a 'friendship dependency'? Is this just the Strategy pattern? -- Ben Sizer From ajikoe at gmail.com Mon Nov 21 05:22:16 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 21 Nov 2005 02:22:16 -0800 Subject: unittest can not use function name 'test' ? Message-ID: <1132568536.218071.81160@z14g2000cwz.googlegroups.com> Hello I found something strange in my unittest : This code is ok (will report error ): class MyTest1(unittest.TestCase): def runTest(self): self.assertEqual(2,3) pass if __name__ == '__main__': unittest.main() But if I add a function with the first name is 'test' it fails to recognize the error: class MyTest1(unittest.TestCase): def test1(self): pass def runTest(self): self.assertEqual(2,3) pass if __name__ == '__main__': unittest.main() Please help pujo From aleax at mail.comcast.net Fri Nov 4 10:50:52 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 4 Nov 2005 07:50:52 -0800 Subject: Learning multiple languages (question for general discussion) References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> Message-ID: <1h5hs5y.19u42x51mo5hupN%aleax@mail.comcast.net> Magnus Lycka wrote: > Alex Martelli wrote: > > Yes, but I haven't found knowing (and using) Python dampens my > > enthusiasms for learning new languages. > > But you're more enthusiatic than most of us Alex. I wish > I could say the same, but I must admit that I only did > halfhearted attempts at learning new languages after Python. > I've looked a bit at most of the ones you mentioned, but > there was nothing that gave me the drive to really follow > it through. I've somehow become content in this regard. I can't imagine NOT getting enthusiastic and stimulated by reading Van Roy and Hariri's book -- it IS quite as good and readable as SICP. Ruby's also blessed with good books (and the excellent Rails, too). > This doesn't mean that I'm not evolving. I regularly program > in three languages (Python, C++ and SQL) and I must learn > new things the whole time to keep interested, whether it's > in the current problem domain, in architectural matters, in > regards to libraries or development tools or whatever. Now I agree, languages are not the only thing worth learning -- they just tend to be more fun (although big frameworks compete with them for this distinction;-). Knuth's latest work is always stimulating, too, even though the new RISC MIX isn't particularly so;-). > it's Twisted for instance. Still, finding Python was a lot > like finding a permanent home (which doesn't exclude various > excursions, or prevent another move or two in this life.) Yes, good analogy, I think -- just the right mix of elegance and practicality one would look for in one's home!-) Alex From mwilliams at mgreg.com Sun Nov 13 19:41:49 2005 From: mwilliams at mgreg.com (Michael Williams) Date: Sun, 13 Nov 2005 19:41:49 -0500 Subject: Trouble with "freeze.py" importing 3rd Party Modules In-Reply-To: References: Message-ID: Can anyone explain why "freeze.py" will make binaries with the std modules fine, however, when using 3rd party modules (Pexpect in particular) it requires the target system to actually have it installed? Thanks in advance, Mike From kent37 at tds.net Sat Nov 5 09:11:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 05 Nov 2005 09:11:07 -0500 Subject: How can I do this in Python? In-Reply-To: <1131178398.195075.111300@z14g2000cwz.googlegroups.com> References: <1131118052.827738.235590@f14g2000cwb.googlegroups.com> <1131122051.701419.108200@g43g2000cwa.googlegroups.com> <1131140647.140956.12850@z14g2000cwz.googlegroups.com> <1131178398.195075.111300@z14g2000cwz.googlegroups.com> Message-ID: <436cbb27$1_2@newspeer2.tds.net> Lad wrote: > Can you please explain in more details (1) choice? If you are using CGI you might be interested in the VoidSpace logintools which seems to handle much of this process. See http://www.voidspace.org.uk/python/logintools.html#no-login-no-access Kent From y.glodt at sitasoftware.lu Wed Nov 16 05:55:38 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 16 Nov 2005 11:55:38 +0100 Subject: [Twisted-Python] ssh tunnel Message-ID: <437B102A.30602@sitasoftware.lu> (I asked about this several times in the twisted list but never got an answer, maybe here I'll more happy...) Hi, I'm new to conch and I wonder if somebody could point me to an example of how to create an ssh tunnel with conch to forward a connection (e.g. database or vnc) through that tunnel (if that's possible at all...) Thanks in advance and best regards, Yves From NOmanlio_perilloSPAM at libero.it Thu Nov 24 04:11:36 2005 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Thu, 24 Nov 2005 09:11:36 GMT Subject: strange behaviour when writing a large amount of data on stdout References: Message-ID: On Thu, 24 Nov 2005 05:22:18 GMT, Dennis Lee Bieber wrote: >On Wed, 23 Nov 2005 16:51:15 GMT, Manlio Perillo > declaimed the following in >comp.lang.python: > >> So, it's seem to be a specific problem of Windows XP(?). >> > Pardon? I think the prior respondent said it /did/ work on WinXP. > > Sure works on my WinXP Pro; 3.4GHz, 2GB RAM -- Even setting > I have added a question mark... However: did you have installed SP1 or SP2? Regards Manlio Perillo From fredrik at pythonware.com Tue Nov 1 12:30:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 1 Nov 2005 18:30:52 +0100 Subject: hello, I want to change n bytes of a binary file References: <311b5ce10511010648y33063589se0dbd5281b29af4e@mail.gmail.com> <311b5ce10511010712r7c1d1b1fia3bc4787fe6e0775@mail.gmail.com> Message-ID: "could ildg" wrote: > > so how can I do the binary stuff? > > 8-bit strings contain bytes. > > > I want a encrypt function like below: > > def encrypt(filename,n): > > f = open(filename,"rb+") > > > a=f.read(n) > > b = encrypt(a) ^^^^^^^^Thank you~~,but where is the encrypt defined? oh, I though you asked how to update the first n bytes of a binary file. if you want to XOR the bytes, you can do something like: import array b = array.array("B", a) for i in range(len(b)): b[i] = b[i] ^ 255 b = b.tostring() or b = "".join([chr(ord(c) ^ 255) for c in a]) or some variation thereof. From rpdooling at gmail.com Mon Nov 21 20:10:39 2005 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Nov 2005 17:10:39 -0800 Subject: mxODBC sql MSAccess Message-ID: <1132621839.128441.49430@f14g2000cwb.googlegroups.com> Hello, I'm new to python and trying to get records from an MSAccess database using mxODBC. It works, but the output is not formatted the way I want it. Here's the script: import mx.ODBC.Windows as odbc driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access Databases/Quotations2005' conn = odbc.DriverConnect(driv) c = conn.cursor() c.execute ("SELECT Author, Topic1, Topic2, Quote FROM QuotesToTxt WHERE Author LIKE 'Mencken%'") rows = c.fetchall() for r in rows: print r And here's what I get: ('Mencken, H.L.', 'Americans', 'Democracy', 'Democracy is the theory that the common people know what they want, and deserve to get it good and hard.') ('Mencken, H.L.', 'Conscience', 'Mother-In-Law', 'Conscience is a mother-in-law whose visit never ends. The inner voice which warns us that someone may be looking.') Where are the parenthese and single quotes coming from? SQL or mxODBC? And how can I get just simple tab-delimited records with a standard carriage return separating the records? Thanks so much for any help. bs From geskerrett at hotmail.com Mon Nov 14 09:02:02 2005 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 14 Nov 2005 06:02:02 -0800 Subject: Inserting Records into SQL Server - is there a faster interface than ADO In-Reply-To: References: <1131724751.606322.162110@g44g2000cwa.googlegroups.com> Message-ID: <1131976921.982178.210260@g43g2000cwa.googlegroups.com> The utility is designed to run in the background and maintain/update a parallel copy of a production system database. We are using the stored procedure to do a If Exist, update, else Insert processing for each record. The originating database is a series of keyed ISAM files. So we need to read each record, perform some simple data conversions and then update the SQL database. We are using Python to read the originating database and perform the record conversion and then posting the results back to SQL Server. We designed our utility to run a night so that the SQL server is up to date the next day and ready for reporting. Thanks for your tips on BCP. I will investigate further as it looks like it might be useful for the initial loading of the data and perhaps some changes to the our utility program to minimize the amount of data that needs to be read/processed. Geoff. From apardon at forel.vub.ac.be Thu Nov 3 09:30:40 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Nov 2005 14:30:40 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131026455.722847.153180@g14g2000cwa.googlegroups.com> Message-ID: Op 2005-11-03, venk schreef : > hey, > did u read my reply fully? i too feel that this matter of raising > unbound local error in one case and not raising it in the other must be > analysed... Yes, it seems I didn't respond to your satisfaction, but since you don't provide details I can't clarify. > quoting from the documentation > "If a name binding operation occurs anywhere within a code block, all > uses of the name within the block are treated as references to the > current block. This can lead to errors when a name is used within a > block before it is bound. This rule is subtle. Python lacks > declarations and allows name binding operations to occur anywhere > within a code block. The local variables of a code block can be > determined by scanning the entire text of the block for name binding > operations." Well I wonder. Would the following code be considered a name binding operation: b.a = 5 -- Antoon Pardon From zach at in.tu-clausthal.de Fri Nov 18 09:41:29 2005 From: zach at in.tu-clausthal.de (Gabriel Zachmann) Date: Fri, 18 Nov 2005 15:41:29 +0100 Subject: combine doxygen and doc-strings? Message-ID: Is there a way to combine doxygen comments, like this one ## Documentation for a function. # @var a - variable # More details. def func( a ): pass with the doc strings, like this one def func( a ): """ Documentation for a function. More details. """ pass ? Obviously, one would like to write the documentaion only once. Best regards, Gabriel. -- /-----------------------------------------------------------------------\ | Any intelligent fool can make things bigger, more complex, | | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \-----------------------------------------------------------------------/ From fredrik at pythonware.com Wed Nov 16 11:39:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 17:39:57 +0100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com><1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: Rick Wotnaz wrote. > ... which leads me to belive that 'msg' is not type(str). It can be > coerced (str(msg).find works as expected). But what exactly is msg? > It appears to be of , and does not test equal to a > string. it's an instance of the exception type, of course. ::: if you do raise SomeError, value Python will actually do raise SomeError(value) (that is, create a SomeError exception and pass the value as its first argument). you can use either form in your code (I prefer the latter myself). ::: as for catching the exceptions, if you do try: ... except SomeError, v: ... Python will treat this as try: ... except: # some exception occurred typ = sys.exc_type exc = sys.exc_value if issubclass(typ, SomeError): v = exc ... else: raise # propagate! (where typ and exc are internal variables) From prolibertine at gmail.com Sun Nov 13 07:14:31 2005 From: prolibertine at gmail.com (=?GB2312?B?1dS54g==?=) Date: Sun, 13 Nov 2005 20:14:31 +0800 Subject: about python ide Message-ID: <1ece08820511130414t1a0e9a32k@mail.gmail.com> i am use python2.4.2 on my gentoo linux system i want to find some ide of python but i am using gtk2.8,wxPython has some bug on it.i cant emerge it correctly. i want some ide use pygtk or other lib of python gui except wxpython(wxWidgets) thx -- /********************************************************** * Love in Gentoo-Linux C and Python * Look at my blog * http://poorc.wordpress.com **********************************************************/ From jepler at unpythonic.net Mon Nov 14 15:33:02 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 14 Nov 2005 14:33:02 -0600 Subject: how do i use "tkinter.createfilehandler" with a regular c program? In-Reply-To: References: Message-ID: <20051114203301.GB25848@unpythonic.net> Compared to your program, I * Made sure that the slave program actually flushed its stdout buffers * didn't call read(), which will by default continue reading until it reaches EOF, not merely read the available data #!/usr/bin/env python import sys, time, Tkinter, itertools, _tkinter, os if '-slave' in sys.argv: for i in itertools.count(): time.sleep(1) print "This is a line of output:", i sys.stdout.flush() raise SystemExit root = Tkinter.Tk() root.wm_withdraw() fh = os.popen('%s -slave' % sys.argv[0]) def reader(*args): line = fh.readline() if not line: print "EOF from slave" raise SystemExit print "from slave: %r" % line _tkinter.createfilehandler(fh, Tkinter.READABLE, reader) root.mainloop() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rhettinger at gmail.com Wed Nov 23 13:42:48 2005 From: rhettinger at gmail.com (rhettinger at gmail.com) Date: 23 Nov 2005 10:42:48 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) References: <1132764821.340622.321850@g47g2000cwa.googlegroups.com> Message-ID: <1132771368.416050.182760@o13g2000cwo.googlegroups.com> > > FWIW, the itertools documentation style was intended more as a learning > > device than as a specification. I combined regular documentation, > > approximately equivalent generator code, examples, and recipes. > > Hopefully, reading the module docs creates an understanding of what the > > tools do, how to use them, how to combine them, and how to roll your > > own to extend the toolset. [Fredrik Lundh] > maybe it's time to change "equivalent to" to "similar to", to avoid > messing things up for people who reads the mostly informal library > reference as if it were an ISO specification. Will do. This is doubly a good idea because there are small differences in argument processing. For example, count() makes an immediate check for a numerical argument but the generator version won't recognize the fault until the count(x).next() is called. From mwm at mired.org Wed Nov 30 16:20:52 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 16:20:52 -0500 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> <86fypkim4x.fsf@bhuda.mired.org> <861x10v4ks.fsf@bhuda.mired.org> <86psoj2w0c.fsf@bhuda.mired.org> Message-ID: <864q5tomrv.fsf@bhuda.mired.org> Antoon Pardon writes: > On 2005-11-29, Mike Meyer wrote: >> Antoon Pardon writes: >>>> You see, you can make languages more powerful by *removing* things >>>> from it. >>> You cast this in way to general terms. The logic conclusion >>> from this statements is that the most powerfull language >>> is the empty language. >> The only way you reach that conclusion is if you read the statement as >> saying that removing things *always* makes a langauge more >> powerful. That's not what I said, > I would say it is the common interpretation for such a sentence. You'd be wrong. "Can" denotes a possibility, not a certainty. If I'd say "You *will* make languages more powerful by removing features", then you'd be right. But that isn't what I said. >>>> Wrong. There are some thing which there should *not* be a way to do. >>>> For instance, there should not be a way to produce a segmentation >>>> fault - which means certain features common to other languages will >>>> never be added. >>> Then C-extentions shouldn't be allowed. >> C-extensions aren't part of Python. > As far as I understand, if you implement a class with a C-extension, > then that class is understood to be part of Python. So if you > think there should be no way to produce a segmentation fault in > python you shouldn't allow such classes. You understand wrong. >>>> We don't talk much about how you produce buffer >>>> overfows in Python, but people have asked for that as well. Adding >>>> ways to write hard-to-read code is frowned upon. And so on. >>> Do you mean people have asked for the possibility that a buffer >>> overflow would overwrite other variables? >> Buffer overflows don't have to overwrite variables. They just asked >> how you create buffer overflows in Python. > I do wonder what they mean with a buffer overflow. Would the following > classify: > buf = range(10) > buf[10] = 10 Well, you'd have to ask them. Personsally, I wouldn't count that, because no data outside the scope of buf got written to. >>>> I won't speak for others, but I wouldn't reject it out of hand. You >>>> haven't provided enough information. Accepting it just because it adds >>>> a way to do something is wrong. First, you have to ask whether or not >>>> that something is something we want in Python at all. Then you >>>> consider whether how the way proposed fits with the language: is it >>>> ugly? >>> That is a highly subjective question, answering it says more about >>> the person then about the proposal. >> True. But whether or not a language is good is a highly subjective >> question. Since the goal - keeping python good to the people who >> already consider it good - is subjective, it's only natural that part >> of the evaluation process be sujectie. >>>> Is it prone to abuse? >>> I don't see why this is always brought up, given the number of >>> features that can be abused in python. >> Just because Python isn't perfect is no reason to make it worse. > Why is it worse. You seem to think that if one has a toolbox, which > lacks a hammer, that the fact that the hammer can be abused makes > your toolbox less usefull if you add a hammer to it. Look again. I never said it would make Python less useful, I said it would make it worse. Those aren't the same thing. It's possible to make a language both more useful and worse at the same time. For instance, Python would clearly be more useful if it could interpret perl 6 scripts. Personally, I think adding the features required to do that would make the language (much, much) worse. Oddly enough, I think adding the features to Perl so it could interpret Python scripts would make it better as well as more useful :-). > We have a toolbox, full of equipment that can be abused, yet > that something else can be abused too, seems to be a mayor > stumbling block for adding it. "Major" is your word, not mine. I just listed it as something to consider. It may be there's an obscure corner case that's really abusive, but chances are no one would ever stumble over it. That's not a major problem. On the other hand, if there's an obvious and attractive use that's abusive, that's a reason for looking for another way to add that functionality. >>>> In summary, the design philosophy is that it's better to do without >>>> some facility than to add it in a way that doesn't fit with the >>>> language, and the process reflects that. >>> I don't mind that a proposal is worked on and that counter-proposals >>> can be made. But some people just seem to counter any new proposal, >>> while other are more interrested in searching for ways to make >>> the new proposal fit the language. Now sometimes a proposal can't >>> be fitted and gets rejected, so be it. But maybe more could be >>> fitted in the langauge if more people were willing to look for >>> ways to fit something, instead of rejecting it simply because >>> the current proposal doesn't fit properly yet. >> The only way this would be good is if "more features" were inherently >> better. That's simply not true. So the change in behavior you're >> looking for isn't clearly good. > No, this is good while there are still possible features that could make > python a better language In that case, they're doing exactly what you want: they're making sure that possible features make python a better language. You seem to think they should stop doing this. I disagree. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From prochazka at u-turnmediagroup.com Wed Nov 16 06:48:36 2005 From: prochazka at u-turnmediagroup.com (=?ISO-8859-2?Q?Jan_Proch=E1zka?=) Date: Wed, 16 Nov 2005 12:48:36 +0100 Subject: special method in module Message-ID: <437B1C94.3060200@u-turnmediagroup.com> Hello, can have modules special methods? althouht i think that no, i tried following example and i don't, why it don't works: ---------------------------- file m2.py (imported module) class Module: def __getitem__(self,index): return index module=Module() __getitem__=module.__getitem__ --------------------------- file m1.py (main program): import m2 print m2.__getitem__(17) # prints 17 print m2[17] # raises error ------------------------------ thanks Honza Prochazka From *firstname*nlsnews at georgea*lastname*.com Tue Nov 29 15:50:19 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Tue, 29 Nov 2005 20:50:19 GMT Subject: unicode speed References: Message-ID: <*firstname*nlsnews-0C315E.15502629112005@news.verizon.net> In article , David Siroky wrote: > Hi! > > I need to enlighten myself in Python unicode speed and implementation. > > My platform is AMD Athlon at 1300 (x86-32), Debian, Python 2.4. > > First a simple example (and time results): > > x = "a"*50000000 > real 0m0.195s > user 0m0.144s > sys 0m0.046s > > x = u"a"*50000000 > real 0m2.477s > user 0m2.119s > sys 0m0.225s > > So my first question is why creation of a unicode string lasts more then 10x > longer than non-unicode string? Your first example uses about 50 MB. Your second uses about 200 MB, (or 100 MB if your Python is compiled oddly). Check the size of Unicode chars by: >>> import sys >>> hex(sys.maxunicode) If it says '0x10ffff' each unichar uses 4 bytes; if it says '0xffff', each unichar uses 2 bytes. > Another situation: speed problem with long strings > > I have a simple function for removing diacritics from a string: > > #!/usr/bin/python2.4 > # -*- coding: UTF-8 -*- > > import unicodedata > > def no_diacritics(line): > if type(line) != unicode: > line = unicode(line, 'utf-8') > > line = unicodedata.normalize('NFKD', line) > > output = '' > for c in line: > if not unicodedata.combining(c): > output += c > return output > > Now the calling sequence (and time results): > > for i in xrange(1): > x = u"a"*50000 > y = no_diacritics(x) > > real 0m17.021s > user 0m11.139s > sys 0m5.116s > > for i in xrange(5): > x = u"a"*10000 > y = no_diacritics(x) > > real 0m0.548s > user 0m0.502s > sys 0m0.004s > > In both cases the total amount of data is equal but when I use shorter strings > it is much faster. Maybe it has nothing to do with Python unicode but I would > like to know the reason. It has to do with how strings (either kind) are implemented. Strings are "immutable", so string concatination is done by making a new string that has the concatenated value, ans assigning it to the left-hand-side. Often, it is faster (but more memory intensive) to append to a list and then at the end do a u''.join(mylist). See GvR's essay on optimization at . Alternatively, you could use array.array from the Python Library (it's easy) to get something "just as good as" mutable strings. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From nyamatongwe+thunder at gmail.com Tue Nov 29 05:14:26 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 29 Nov 2005 10:14:26 GMT Subject: unicode speed In-Reply-To: References: Message-ID: <6SVif.6506$ea6.3923@news-server.bigpond.net.au> David Siroky: > output = '' I suspect you really want "output = u''" here. > for c in line: > if not unicodedata.combining(c): > output += c This is creating as many as 50000 new string objects of increasing size. To build large strings, some common faster techniques are to either create a list of characters and then use join on the list or use a cStringIO to accumulate the characters. This is about 10 times faster for me: def no_diacritics(line): if type(line) != unicode: line = unicode(line, 'utf-8') line = unicodedata.normalize('NFKD', line) output = [] for c in line: if not unicodedata.combining(c): output.append(c) return u''.join(output) Neil From gh at ghaering.de Wed Nov 23 08:59:40 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 23 Nov 2005 14:59:40 +0100 Subject: syntax errors while building pypgsql In-Reply-To: <3uj7hcF10k63tU1@individual.net> References: <3uj7hcF10k63tU1@individual.net> Message-ID: <438475CC.3090405@ghaering.de> Tin Gherdanarra wrote: > Hallo, > > I'm trying to install pypgsql. However, I get syntax errors > while compiling the C sources. The following excerpt > from pgconnection.h looks a little funny to me: > > typedef struct { > PyObject_HEAD /* Here is the syntax error, and rightly so */ > [...] > I don't know what PyObject_HEAD or PGconn is, > but if they are types, a syntax error is justified here: [...] I don't think that's the real error. Are there any error messages *before* that? Like the compiler can't find "Python.h" or something? That would be an indication that you do not have the python-devel package installed. Btw. the Debian package of pyPgSQL is called python-pgsql, so an apt-get install python-pgsql should do. -- Gerhard From bokr at oz.net Fri Nov 11 21:07:08 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 12 Nov 2005 02:07:08 GMT Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131627394.890394.200070@g44g2000cwa.googlegroups.com> <4373bcbc.150778327@news.oz.net> <1131675601.931303.177890@g14g2000cwa.googlegroups.com> Message-ID: <43754890.252110405@news.oz.net> On 10 Nov 2005 18:20:01 -0800, "bonono at gmail.com" wrote: > >Bengt Richter wrote: >> If you want to terminate a generator expression after the first sequence of elements >> satisfying a condition, and you don't want to use takewhile, I don't know of a gotcha >> to prevent you from just raising StopIteration, using an expression that will do that, e.g., >> >> >>> list (x for x in xrange(20) if x<5 or iter([]).next()) >> [0, 1, 2, 3, 4] >> >> Or a bit more readably: >> >>> def stop(): raise StopIteration >> ... >> >>> list (x for x in xrange(20) if x<5 or stop()) >> [0, 1, 2, 3, 4] >> >> IOW, your "when condition(x)" (IIUIC) can be spelled "if condition(x) or stop()" >If it is a single loop, takewhile/dropwhile is perfectly fine but as I >mentioned in another post, it is nested and the condition needs >surrounding scope so seperate function and StopIteration doesn't work >as it breaks out of the whole thing expression. How do you mean? How did you write the expression? E.g., there are two stop() calls in this one, but they are in different scopes: >>> list ((i,list(xseq)) for i, xseq in enumerate((x for x in xrange(20) if x<5 or stop()) for j in xrange(20) if j<4 or stop() )) [(0, [0, 1, 2, 3, 4]), (1, [0, 1, 2, 3, 4]), (2, [0, 1, 2, 3, 4]), (3, [0, 1, 2, 3, 4])] Or, (perhaps) more prettily written (same syntax, just spread differently): >>> list( ... (i,list(xseq)) for i, xseq in enumerate( ... (x for x in xrange(20) if x<5 or stop()) ... for j in xrange(20) if j<4 or stop() ... ) ... ) [(0, [0, 1, 2, 3, 4]), (1, [0, 1, 2, 3, 4]), (2, [0, 1, 2, 3, 4]), (3, [0, 1, 2, 3, 4])] >>> I would think takewile would do the same. Might as well see: >>> from itertools import takewhile >>> list( ... (i,list(twiter)) for i, twiter in enumerate( ... takewhile(lambda x:x<5, xrange(20)) ... for j in takewhile(lambda x:x<4, xrange(20)) ... ) ... ) [(0, [0, 1, 2, 3, 4]), (1, [0, 1, 2, 3, 4]), (2, [0, 1, 2, 3, 4]), (3, [0, 1, 2, 3, 4])] Seems ok. > >takewhile/dropwhile still works in this case(because of the lambda >which sees the surrounding scope). > Could you show your code with the traceback of its failure? I've lost context ;-) Regards, Bengt Richter From JHoover at fbi.gov Sun Nov 20 22:15:59 2005 From: JHoover at fbi.gov (Gordon Airporte) Date: Sun, 20 Nov 2005 22:15:59 -0500 Subject: Type-checking unpickled objects In-Reply-To: References: Message-ID: isinstance! Now why didn't I know about that? Thanks you. I guess I'll need a throwaway instance of the class to run type() on to get a usable type object for comparison, but I'll work something out. As to the security considerations...this is a small enough program with a limited enough release that I'm not going to sweat it, although I will keep this in mind. From broek at cc.umanitoba.ca Tue Nov 15 04:11:05 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 15 Nov 2005 03:11:05 -0600 Subject: compare list In-Reply-To: <8c11e4350511142324j69b921cbta00549fcf9755aa2@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <8c11e4350511142324j69b921cbta00549fcf9755aa2@mail.gmail.com> Message-ID: <4379A629.6060207@cc.umanitoba.ca> Ben Bush said unto the world upon 2005-11-15 01:24: > > Unfortunately, the indents got screwed up along the way. But the part > >>of my code you asked about was: >> >>for item in list1: >> if item in list2: >> if item + 1 in list1 and item + 1 in list2: >> return True >> >>In some detail: >>Does that clarify it? >> >>Finally, your response to Alex would have been much more useful if >>you'd quoted the error rather than just asserting that you got an >>error :-) >> >>Best, >> >>Brian vdB Hi Ben, first, while there are those on the list/n.g. who differ, the majoritarian view is that top posting isn't a good thing. At minimum, if someone bothered to correct it, it would be nice if in a further follow-up you didn't top-post again :-) Second, you might find the tutor list really helpful. It is where I learned most of what I know, and I still read it more than c.l.p. It is very newbie friendly. As for your question: >> Hi Brian, > > regarding "if item + 1 in list1 and item + 1 in list2:", > my understanding is this will check whether the following item in each list > is the same. How does the code permit the situation that the order does not > matter? > For example, for lisA and lisB, the comparison is true and the two lists > have 5 and 6 but different order. > lisA=[1,2,3,4,5,6,9] > lisB=[1,6,5] > Many Thanks! There are two distinct issues that might be the source of your confusion. I will be explicit about both; pardon if only one applied. >>> num_list = [1, 42, 451] >>> for item in num_list: print item, type(item) 1 42 451 >>> Iterating over a list as I did makes item refer to each list member in turn. So, item + 1 doesn't refer to the next item (except by accident as it were when two items are sequential ints). Rather, it refers to int that results from adding 1 to the int that is item. You might be thinking of list index notation instead: >>> index = 1 >>> num_list[index], num_list[index + 1] (42, 451) >>> (General tip: putting a print or two in my original code would have cleared that up very quickly.) So, that cleared up, are you wondering why item + 1 suffices, instead of both item + 1 and item - 1? If so, consider that it the list1 has both n and n - 1 in it and we iterate over list1 checking each case, eventually item will refer to n - 1. In that case, item + 1 = n and we are covered after all. I did as I did in my original code thinking it was probably quicker to have only one test and pay the cost that there might be a quicker exit from the iteration were I to test both item + 1 and item - 1. f it mattered, I'd test for speed. Of course, if speed mattered and I could ever remember to use sets :-) I'd follow Alex and Duncan's suggestions instead! If that doesn't clear it up, give yourself a few short lists and run test cases having inserted print statements to see what is going on. To stop it all from whizzing by too fast, put in raw_input("Hit enter and I'll keep working") somewhere in the loops to slow things down. HTH, Brian vdB From brian at rkspeed-rugby.dk Mon Nov 28 09:45:57 2005 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: 28 Nov 2005 15:45:57 +0100 Subject: How to get started in GUI Programming? References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> <1133186792.984959.261550@g43g2000cwa.googlegroups.com> Message-ID: peter.mosley at talk21.com writes: > Others recommended wxPython, PyQt and various derivatives. The trouble > is there's too much choice! Agreed, I tried to find /the answer/ some time ago, and I got to the same conclusion. In addition it is even more difficult to find the advantages and disadvantages of the different toolkits. My main reasons for choosing wxpython (but never really try to do something useful with it) was the native look-and-feel on different platforms and the many different examples, and the demo application pysketch. Unfortunately, even wxpython supports two or three ways of doing drawings on a canvas, and not that many examples were available for this. In addition pyqt should be great, I read. So i have been waiting for trolltech to release qt4 and just saw that they have. pyqt is not updated yet. > One development is that my local public library has, to my surprise, > managed to locate a copy of 'Python and Tkinter Programming' by J. > Grayson. I've not read it yet, and an initial flick through > doesn't look too promising but maybe I am mistaken.. I had the same experience with it. I got more from http://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From grflanagan at yahoo.co.uk Sat Nov 5 07:15:36 2005 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 5 Nov 2005 04:15:36 -0800 Subject: Python doc problem example: gzip module (reprise) In-Reply-To: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> Message-ID: <1131192936.228280.150530@g44g2000cwa.googlegroups.com> Xah Lee wrote: > Python Doc Problem Example: gzip > > Xah Lee, 20050831 > > Today i need to use Python to compress/decompress gzip files. Since > i've read the official Python tutorial 8 months ago, have spent 30 > minutes with Python 3 times a week since, have 14 years of computing > experience, 8 years in mathematical computing and 4 years in unix admin > and perl, i have quickly found the official doc: > http://python.org/doc/2.4.1/lib/module-gzip.html > > I'd imagine it being a function something like: > > fileContent = GzipFile(filePath, comprress/decompress) > > However, scanning the doc after 20 seconds there's no single example > showing how it is used. > > Instead, the doc starts with some arcane info about compatibility with > some other compression module and other software. Then it talks in a > very haphazard way with confused writing about the main function > GzipFile. No perspectives whatsoever about using it to solve a problem > nor a concrete description of how to use it. Instead, jargons of Class, > Constructor, Object etc are thrown together with presumption of > reader's expertise of IO programing in Python and gzip compression > arcana. > > After no understanding, and being not a Python expert, i wanted to read > about file objects but there's no link. > > After locating the file object's doc page: > http://python.org/doc/2.4.1/lib/bltin-file-objects.html, but itself is > written and organized in a very unhelpful way. > > Here's the detail of the problems of its documentation. It starts with: > > ?The data compression provided by the zlib module is compatible > with that used by the GNU compression program gzip. Accordingly, the > gzip module provides the GzipFile class to read and write gzip-format > files, automatically compressing or decompressing the data so it looks > like an ordinary file object. Note that additional file formats which > can be decompressed by the gzip and gunzip programs, such as those > produced by compress and pack, are not supported by this module.? > > This intro paragraph is about 3 things: (1) the purpose of this gzip > module. (2) its relation with zlib module. (3) A gratuitous arcana > about gzip program's support of ?compress and pack? software being > not supported by Python's gzip module. Necessarily mentioned because > how the writing in this paragraph is phrased. The writing itself is a > jumble. > > Of the people using the gzip module, vast majority really just need to > decompress a gzip file. They don't need to know (2) and (3) in a > preamble. The worst aspect here is the jumbled writing. > > ?class GzipFile( [filename[, mode[, compresslevel[, fileobj]]]]) > Constructor for the GzipFile class, which simulates most of the methods > of a file object, with the exception of the readinto() and truncate() > methods. At least one of fileobj and filename must be given a > non-trivial value. The new class instance is based on fileobj, which > can be a regular file, a StringIO object, or any other object which > simulates a file. It defaults to None, in which case filename is opened > to provide a file object.? > > This paragraph assumes that readers are thoroughly familiar with > Python's File Objects and its methods. The writing is haphazard and > extremely confusive. Instead of explicitness and clarity, it tries to > convey its meanings by side effects. > > ? The words ?simulate? are usd twice inanely. The sentence > ?...Gzipfile class, which simulates...? is better said by > ?Gzipfile is modeled after Python's File Objects class.? > > ? The intention to state that it has all Python's File Object methods > except two of them, is ambiguous phrased. It is as if to say all > methods exists, except that two of them works differently. > > ? The used of the word ?non-trivial value? is inane. What does a > non-trivial value mean here? Does ?non-trivial value? have specific > meaning in Python? Or, is it meant with generic English interpretation? > If the latter, then what does it mean to say: ?At least one of > fileobj and filename must be given a non-trivial value?? Does it > simply mean one of these parameters must be given? > > ? The rest of the paragraph is just incomprehensible. > > ?When fileobj is not None, the filename argument is only used to > be included in the gzip file header, which may includes the original > filename of the uncompressed file. It defaults to the filename of > fileobj, if discernible; otherwise, it defaults to the empty string, > and in this case the original filename is not included in the header.? > > ?discernible?? This writing is very confused, and it assumes the > reader is familiar with the technical specification of Gzip. > > ?The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or > 'wb', depending on whether the file will be read or written. The > default is the mode of fileobj if discernible; otherwise, the default > is 'rb'. If not given, the 'b' flag will be added to the mode to ensure > the file is opened in binary mode for cross-platform portability.? > > ?discernible?? Again, familiarity with the working of Python's file > object is implicitly assumed. For people who do not have expertise with > working with files using Python, it necessatates the reading of > Python's file objects documentation. > > ?The compresslevel argument is an integer from 1 to 9 controlling > the level of compression; 1 is fastest and produces the least > compression, and 9 is slowest and produces the most compression. The > default is 9.? > > ?Calling a GzipFile object's close() method does not close > fileobj, since you might wish to append more material after the > compressed data. This also allows you to pass a StringIO object opened > for writing as fileobj, and retrieve the resulting memory buffer using > the StringIO object's getvalue() method.? > > huh? append more material? pass a StringIO? and memory buffer? > > Here, expertise in programing with IO is assumed of the reader. > Meanwhile, the writing is not clear about how exactly what it is trying > to say about the close() method. > Suggestions > -------------------------- > A quality documentation should be clear, succinct, precise. And, the > least it assumes reader's expertise to obtain these qualities, the > better it is. > > Vast majority of programers using this module really just want to > compress or decompress a file. They do not need to know any more > details about the technicalities of this module nor about the Gzip > compression specification. Here's what Python documentation writers > should do to improve it: > > ? Rewrite the intro paragraph. Example: ?This module provides a > simple interface to compress and decompress files using the GNU > compression format gzip. For detailed working with gzip format, use the > zlib module.?. The ?zlib module? phrase should be linked to its > documentation. > > ? Near the top of the documentation, add a example of usage. A > example is worth a thousand words: > > # decompressing a file > import gzip > fileObj = gzip.GzipFile("/Users/joe/war_and_peace.txt.gz", 'rb'); > fileContent = fileObj.read() > fileObj.close() > > # compressing a file > import gzip > fileObj = gzip.GzipFile("/Users/mary/hamlet.txt.gz", 'wb'); > fileObj.write(fileContent) > fileObj.close() > > ? Add at the beginning of the documentation a explicit statement, > that GzipFile() is modeled after Python's File Objects, and provide a > link to it. > > ? Rephrase the writing so as to not assume that the reader is > thoroughly familiar with Python's IO. For example, when speaking of the > modes 'r', 'rb', ... add a brief statement on what they mean. This way, > readers may not have to take a extra step to read the page on File > Objects. > > ? Remove arcane technical details about gzip compression to the > bottom as footnotes. > > ? General advice on the writing: The goal of writing on this module > is to document its behavior, and effectively indicate how to use it. > Keep this in mind when writing the documentation. Make it clear on what > you are trying to say for each itemized paragraph. Make it precise, but > without over doing it. Assume your readers are familiar with Python > language or gzip compression. For example, what are classes and objects > in Python, and what compressions are, compression levels, file name > suffix convention. However, do not assume that the readers are expert > of Python IO, or gzip specification or compression technology and > software in the industry. If exact technical details or warnings are > necessary, move them to footnotes. > --------------- > > Xah > xah at xahlee.org > ? http://xahlee.org/ """ You want to create the world before which you can kneel: this is your ultimate hope and intoxication. Also sprach Zarathustra. """ --Friedrich Nietzsche, Thus Spoke Zarathustra, 1885 Gerard From tuvas21 at gmail.com Wed Nov 30 12:38:44 2005 From: tuvas21 at gmail.com (Tuvas) Date: 30 Nov 2005 09:38:44 -0800 Subject: Quene Message-ID: <1133372324.562281.128910@g47g2000cwa.googlegroups.com> I am trying to write a function that holds a variable-length quene. The quene has 2 bits of information. At some point, I would like to remove bits of this quene, when they are completed. Is there a way to do this with something as follows? quene=[] quene.append((4,2)) quene.append((3,6)) if(4 in quene): #Shows false, what's the correct syntax to show true? remove 4 from quene #(Not python code, not sure how to do this...) So, how can I make this work? Thanks! From fredrik at pythonware.com Fri Nov 11 08:10:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 14:10:02 +0100 Subject: how to start a process and get it's pid? References: <43745C93.70907@sitasoftware.lu> <1131713940.819881.6320@g43g2000cwa.googlegroups.com> Message-ID: Daniel Crespo wrote: >> >>> os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") >> 1944 > > I don't get the correct PID. > > When I do os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") > I get 168 (for example), while in the tasklist appears notepad.exe with > the 2476 PID. > > Why? not sure, but the return value looks like a PID, so maybe you're seeing the PID for the cmd.exe instance used to run the program. or something. try this instead: >>> import subprocess >>> p = subprocess.Popen("c:/windows/notepad.exe") >>> p.pid 1948 From swaroopch at gmail.com Sat Nov 5 02:42:18 2005 From: swaroopch at gmail.com (Swaroop C H) Date: 4 Nov 2005 23:42:18 -0800 Subject: Parrot Project for Python In-Reply-To: <436c3f4e$0$41142$14726298@news.sunsite.dk> References: <436c3f4e$0$41142$14726298@news.sunsite.dk> Message-ID: <1131176538.877620.246940@g44g2000cwa.googlegroups.com> See http://pirate.tangentcode.com/ - Swaroop From deets at nospam.web.de Sun Nov 27 12:00:55 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Nov 2005 18:00:55 +0100 Subject: passing artibrary strings into a database In-Reply-To: <1133109304.575556.284190@g47g2000cwa.googlegroups.com> References: <1133109304.575556.284190@g47g2000cwa.googlegroups.com> Message-ID: <3uu728F13cahqU1@uni-berlin.de> schwehr at gmail.com wrote: > Hi All, > > I was wondering if there is a helper library out there that will nicely > encode artibrary text so that I can put in into a TEXT field in a > database and then retrieve it without getting into trouble with ',",new > lines or other such things that would foul the sql insert call and or > be a security hazard? This feels like a newbee type question, but I > haven't found anything with a quick search. Use paramtetrized cursor.execute(..) That is instead of doing c.execute("insert into foo values ('%s')" % mytext) do c.execute("insert into foo values (?)", mytext) Attention, the actual style of a parameter is dependand on your database, e.g. oracle uses a differnet one: c.execute("insert into foo values (:mytext)", dict(mytext=mytext)) The actual style to use is given in the docs, or can be queried with connection.paramstyle I recommend reading the DB-API 2.0 specs. Diez From http Mon Nov 28 18:53:17 2005 From: http (Paul Rubin) Date: 28 Nov 2005 15:53:17 -0800 Subject: General question about Python design goals References: Message-ID: <7x64qcwcr6.fsf@ruckus.brouhaha.com> Peter Hansen writes: > Christoph Zwerschke wrote: > > Ok, these are nice aphorisms with some truth. But I had to think of > > the German excuse "Wer Ordnung h?lt ist nur zu Faul zum Suchen - ein > > Genie ?berblickt das Chaos." ("Those who try to keep things tidy are > > just too lazy to search for searching - a genius surveys the chaos"). > > Is that really the translation? "too lazy to search for searching"? > What does that mean? It should just say "too lazy to search" or maybe "too lazy to be a searcher". From antonyliu2002 at yahoo.com Wed Nov 30 20:35:01 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Wed, 30 Nov 2005 17:35:01 -0800 (PST) Subject: One module cannot be found by the interpreter Message-ID: <20051201013501.7818.qmail@web35810.mail.mud.yahoo.com> I downloaded and built the python/c++ maxent package ( http://homepages.inf.ed.ac.uk/s0450736/maxent_toolkit.html ). I don't know what happened, the interpreter cannot find the cmaxent module, whereas cmaxent.py is right under the current directory. >>> from maxent import * cmaxent module not found, fall back to python implementation. >>> Could you please kindly advise? Thanks a lot. __________________________________ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ From fredrik at pythonware.com Thu Nov 17 09:00:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Nov 2005 15:00:15 +0100 Subject: searching for files on Windows with Python References: <20051117133525.21047.qmail@server285.com> Message-ID: Shane wrote: > I've been giving Google a good workout with no luck. I would like to be > able to search a Windows filesystem for filenames, returning a list off absolute > paths to the found files, something like: maybe some variation of http://article.gmane.org/gmane.comp.python.general/422691 is what you need ? From dave at dbmdata.com Sun Nov 6 09:25:15 2005 From: dave at dbmdata.com (David Mitchell) Date: Sun, 06 Nov 2005 09:25:15 -0500 Subject: Can't instantiate class Message-ID: <436E124B.7000003@dbmdata.com> Hello, Here is a very basic question, but it is frustrating me to no end nonetheless. I have one file called addLink.py. In a method in this file I am trying to instantiate a class and call a method from that class. Here is the code: def getCategories(): # instantiate the DataUtil class db = DataUtil() # and call the getConnection() method connection = db.getConnection() ... At the top of this file I am importing the DataUtil module (named DataUtil.py) with this line: import DataUtil The DataUtil.py file resides in the same directory as the above file and looks like this: import MySQLdb class DataUtil: def __init__(self): print "init" def getConnection(self): return MySQLdb.connect(host="host", user="user", passwd="pass", db="test") When I execute the getCategories() method above I get the following error: File "C:\Apache2\htdocs\Intranet\addLink.py", line 42, in getCategories db = DataUtil() TypeError: 'module' object is not callable Any idea what I'm doing wrong? Thanks, Dave From case.nelson at gmail.com Wed Nov 23 12:37:45 2005 From: case.nelson at gmail.com (snoe) Date: 23 Nov 2005 09:37:45 -0800 Subject: asyncore question In-Reply-To: References: Message-ID: <1132767465.459463.308030@f14g2000cwb.googlegroups.com> Not 100% sure why print d gives None but if you need to print something that represents the instance, use repr >>> d.__str__ >>> str(d) 'None' >>> repr(d) '' >>> print repr(d) Why isn't __str__ in dir? >>> dir(d) ['__doc__', '__getattr__', '__init__', '__module__', '__repr__', '_map', 'accept ', 'accepting', 'add_channel', 'addr', 'bind', 'close', 'closing', 'connect', 'c onnected', 'create_socket', 'debug', 'del_channel', 'handle_accept', 'handle_clo se', 'handle_connect', 'handle_error', 'handle_expt', 'handle_expt_event', 'hand le_read', 'handle_read_event', 'handle_write', 'handle_write_event', 'listen', ' log', 'log_info', 'readable', 'recv', 'send', 'set_reuse_addr', 'set_socket', 's ocket', 'writable'] From dont at spam.me Tue Nov 29 20:49:35 2005 From: dont at spam.me (Bugs) Date: Tue, 29 Nov 2005 17:49:35 -0800 Subject: wxGrid and Focus Event In-Reply-To: References: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> <438CACF1.1020909@ulmcnett.com> <1133294056.952406.108890@g44g2000cwa.googlegroups.com> <1133298277.358823.184670@f14g2000cwb.googlegroups.com> Message-ID: So Paul, are you saying there's a bug with the wxGrid control and if so, do you know if there's been a bug-report submitted to the wxWidgets and/or wxPython folks? Or is this just the way the wxGrid control works? Thanks! Paul McNett wrote: > Not so fast. I've found out that I had to do the following ugly > workaround to ensure it works in all cases: > From y.glodt at sitasoftware.lu Fri Nov 11 10:58:43 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Fri, 11 Nov 2005 16:58:43 +0100 Subject: how to start a process and get it's pid? In-Reply-To: <437461E6.1020607@ghaering.de> References: <43745C93.70907@sitasoftware.lu> <437461E6.1020607@ghaering.de> Message-ID: <4374BFB3.2090701@sitasoftware.lu> Gerhard H?ring wrote: > Yves Glodt wrote: >> Hello, >> >> another question rose for me today... >> >> Is there a way to start an external process, in it's own context (not as >> the exec-() functions do), and get it's pid...? [...] > > Check out the subprocess module if you're using Python 2.4. > > Otherwise, you can always use os.spawn*, for example: > > >>> os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") > 1944 Thanks, in Linux it seems to work. > HTH, > > -- Gerhard > From bonono at gmail.com Fri Nov 18 18:22:12 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 18 Nov 2005 15:22:12 -0800 Subject: Adding through recursion In-Reply-To: References: <1132320167.127338.92460@g47g2000cwa.googlegroups.com> Message-ID: <1132356132.806977.149990@g44g2000cwa.googlegroups.com> Ben Finney wrote: > martin.clausen at gmail.com wrote: > > def add(x, y): > > if x == 0: > > print y > > return y > > else: > > x -= 1 > > y += 1 > > add(x, y) > > To add to the other good advice in this thread: > > This is just one of many reasons why I advocate always having a > *single* return statement, at the *end* of the function. I usually > start out writing my function setting a default return value, and the > return statement immediately below. > > In your case, the default return value is None, so let's make that > explicit. > > def recursive_add(x, y): > result = None > return result > > Then, the rest of the function's responsibility is about changing that > default value if necessary. > > def recursive_add(x, y): > result = None > if x == 0: > print y > result = y > else: > x -= 1 > y += 1 > recursive_add(x, y) > return result > > With this structure, it becomes quickly obvious what's gone wrong: one > of the branches is not changing the default return value. > > def recursive_add(x, y): > if x == 0: > print y > result = y > else: > x -= 1 > y += 1 > result = recursive_add(x, y) > return result > > I find this much less error-prone than hiding return statements in > branches throughout the function; if the only return statement is at > the very end of the function, it becomes much easier to read. I don't see this as clearer than multiple return. But then it I believe it is really preference or style, rather than obvious advantage/disadvantage. Interestingly, this kind of error is easy to spot by the compiler in C. From samrobertsmith at gmail.com Sat Nov 12 03:30:06 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 00:30:06 -0800 Subject: about widget construction kit In-Reply-To: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com> References: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com> Message-ID: <1d987df30511120030r15cf33e3me8ce2aac1512e8b1@mail.gmail.com> very hard for me to understand the difference between try...except and try...finally From cito at online.de Sun Nov 27 20:12:19 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 28 Nov 2005 02:12:19 +0100 Subject: General question about Python design goals Message-ID: Sometimes I find myself stumbling over Python issues which have to do with what I perceive as a lack of orthogonality. For instance, I just wanted to use the index() method on a tuple which does not work. It only works on lists and strings, for no obvious reason. Why not on all sequence types? Or, another example, the index() method has start and end parameters for lists and strings. The count() method also has start and end parameters for strings. But it has no such parameters for lists. Why? However when I ask such things I noticed I get answers like: "Is there a use case?" "You can do it some other way so it is not worth bothering." Let me ask back: Do I really need to bother and justify it with a use case in a case where the language can be easily made more consistent or orthogonal without breaking anything? What about design goals such as: - orthogonality - coherence, consistency - principle of least astonishment ("Python fits my brain") - simplicity ("kiss" principle) - aesthetics, symmetry Actually, which priority have the above design goals for Python? Are other design goals considered more important? If I compare them with the "Zen of Python", I find some of the above: consistency -> Special cases aren't special enough to break the rules simplicity -> Simple is better than complex aesthetics -> Beautiful is better than ugly Actually, concerning the last two, you already need to understand the Zen of Python to decide if something is "simple" or even "beautiful", so they are not really suitable to *define* the Zen of Python. For me, a programming language is beautiful if it is orthogonal and coherent. But for others, this may be different. Somehow, I'm missing a direct allusion to the following in the Zen of Python: - orthogonality - principle of least astonishment Maybe I am I lacking the satori of a real Python Zen master? -- Christoph From pythonnew at gmail.com Tue Nov 22 12:25:11 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 22 Nov 2005 09:25:11 -0800 Subject: drawline Message-ID: <8c11e4350511220925q2c55971m553ed80952e7d89@mail.gmail.com> I had the following code and when I clicked the left mouse button one time. I got green line and the second click got a purple line and the green disappeared. I was confused by two questions: First, Clicknum increases when every time I click the button. Is it possible to reset Clicknum to 0? Second, how to do something like: I click the left button the first time, the green line appear then disappear, the purple line appear(just as the code has done but become a loop; if a second-time click is implied, the loop stops. from Tkinter import * ClickNum = 0 def drawline(event): global ClickNum if ClickNum == 0: canvas.create_line(100, 0, 100, 200, arrow=FIRST,fill="green",tag="a") elif ClickNum == 1: canvas.delete("a") canvas.create_line(100, 50, 60, 300, arrow=FIRST,fill="purple") ClickNum += 1 tk = Tk() canvas = Canvas(tk, bg="white", bd=0, highlightthickness=0) canvas.pack(fill=BOTH, expand=YES) canvas.create_line(100, 200, 350, 200, arrow=LAST,fill='red') canvas.bind("<1>", drawline) tk.mainloop() From amk at amk.ca Tue Nov 1 14:43:20 2005 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 01 Nov 2005 13:43:20 -0600 Subject: python.org offline References: <1130862100.694549.276860@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 1 Nov 2005 18:18:06 +0100, Sybren Stuvel wrote: > Yes, I can read. My question is: does anyone know why this happens so > often lately? I suspect this is teething problems related to the move to a new server. I've bumped up the number of Apache processes, so we'll see if that alleviates the problem. --amk From rurpy at yahoo.com Thu Nov 24 14:55:30 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 24 Nov 2005 11:55:30 -0800 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132775825.182959.314090@g43g2000cwa.googlegroups.com> Message-ID: <1132862130.734675.239590@g49g2000cwa.googlegroups.com> Fredrik Lundh wrote: > rurpy at yahoo.com wrote: > > > I don't find your code any more readable than the OP's > > equivalent code: > > the OP's question was > > How you do this in a practic way without > the use of one-line code ? I know. But you compared the readability of code with one-liners and long variable names with the readability of code with no one-liners and short variable names. I thought that most of the readability improvement was due to the long-to-short name change. So I posted what I hoped was code equivalent to what you quoted, but using your short names and a one-liner "then-if-else" (on 3 lines :-) It satisfied me that the readability improvement was due to the short varible names. > > The OPs code make one pass through the dict, your's makes > > two. I do not know what effect (if any) that has in the case of > > a very large dict. > > the OPs code contains five reads and three writes, my and > steven's versions contain four reads and three writes. the > yet-to-be-released ternary operator would remove one read > from the OPs code, which makes both alternatives equivalent. > > dictionary accesses don't involve passes over the dictionary. I was actually thinking of the effects of hardware memory cache... > there's a comment on readability and code understanding waiting > to be made here, but I'll leave that for another day. From bonono at gmail.com Sun Nov 20 08:41:39 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 05:41:39 -0800 Subject: about lambda In-Reply-To: References: Message-ID: <1132494099.642274.220720@g14g2000cwa.googlegroups.com> Shi Mu wrote: > what does the following code mean? It is said to be used in the > calculation of the overlaid area size between two polygons. > map(lambda x:b.setdefault(x,[]),a) The equivalent of : def oh_my_yet_another_function_name_why_not_use_lambda(x): b.setdefault(x,[]) map(oh_my_yet_another_function_name_why_not_use_lambda, a) Or for x in a: b.setdefault(x,[]) From eternalsquire at comcast.net Tue Nov 22 20:38:03 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 22 Nov 2005 17:38:03 -0800 Subject: a new design pattern for Python Library? Message-ID: <1132709883.708313.279720@g44g2000cwa.googlegroups.com> Hi, I tend to use this design pattern a lot in order to aid in compartmentalizing interchangeable features in a central class that depend on the central class's data. I know that explicit class friendship designs syntactic sugar, but I am thinking this should be a standard design pattern to make friendship dependencies a little more self documenting. Opinions? The Eternal Squire class Friend (object): def __init__ (self, friend): object.__init__ (self) self.friend = friend Example use: class Bar (Friend): TITLE = None DEFAULT = 1 def __init__ (self, top): Friend.__init__ (self, top) self.data = self.default * self.default def __str__ (self): print "%s mode %d default = %d" % (self.__class__.__name__, self.friend.mode, self.data) class ABar (Bar): DEFAULT = 2 class Foo: BAR = ABar def __init__ (self): self.bar = self.BAR (self) self.mode = 1 def __str__ (self): return str (self.bar) From rogerb at rogerbinns.com Mon Nov 7 00:23:03 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 6 Nov 2005 21:23:03 -0800 Subject: PyFLTK - an underrated gem for GUI projects References: Message-ID: "aum" wrote in message news:pan.2005.11.07.00.23.39.597631 at spam.me.please... > To me, wxPython is like a 12-cylinder Hummer, with fuzzy dice hanging > from the mirror, fridge and microwave in the back, and DVD consoles on > every seat, towing a campervan - absolute power and luxury, giving 8mpg > if you're lucky. A word of support for wxPython: - It comes with a nice demo app that shows every single supported widget and editable code for playing with them so you can tweak to try new things. - It supports printing, drag and drop and various similar niceties on each platform. - Mac is a first class citizen (support isn't perfect but it is better than "good enough"). The FLTK docs mention Mac a few times but usually just Unix and Windows. - It fully supports Unicode. (It looks like the under development FLTK 2.0 uses UTF-8 in some places but doesn't look like this release is imminent.) - There is a half decent HTML widget. (The FLTK one is only a quarter decent :-) - You get the native look and feel on each platform and native widgets are used wherever possible. (I can't tell what FLTK does). - Various other corner things are covered as needed by more complex apps such as audio, ActiveX on Windows, stock icons, online help, calendar controls, directory and file selectors, a grid/table etc etc As is usually the case, each developer only uses 10% of the functionality of the toolkit available, but it is a different 10% for each! My 10% includes printing and drag and drop which are missing from most of the toolkits you listed. I also insist on native widgets wherever possible. It is possible to make the wxPython smaller by having more DLLs each with fewer widgets in it. That way you will only suck in the ones you use. I do like that FLTK has the documentation style as PHP where users can add comments to each page. Roger From gherron at digipen.edu Thu Nov 10 12:27:14 2005 From: gherron at digipen.edu (Gary Herron) Date: Thu, 10 Nov 2005 09:27:14 -0800 Subject: What do you use as symbols for Python ? In-Reply-To: References: <4372f88a$0$31833$636a15ce@news.free.fr> Message-ID: <437382F2.1080008@digipen.edu> Erik Max Francis wrote: >Pierre Barbier de Reuille wrote: > > > >>When you need some symbols in your program, what do you use in Python ? >> >>For example, an object get a state. This state is more readable if >>expressed as a symbols, for example "opened", "closed", "error". >>Typically, in C or C++, I would use an enum for that: >>enum OBJECT_STATE >>{ >> opened, closed, error >>} >> >> > > OPENED, CLOSED, ERROR = range(3) > > object.state = OPENED > > Another similar approach that keeps those values together in a single namespace is this (my favorite): class State: OPENED, CLOSED, ERROR = range(3) Then you can refer to the values as State.OPENED State.CLOSED State.ERROR The extra clarity (and slight wordiness) of the dotted notation seems, somehow, quite Pythonic to me. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From steve at holdenweb.com Fri Nov 4 00:15:22 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Nov 2005 05:15:22 +0000 Subject: Getting Python Accepted in my Organisation In-Reply-To: References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> Message-ID: Magnus Lycka wrote: > Stuart Turner wrote: > >>Hi Everyone, >> >>I'm working hard trying to get Python 'accepted' in the organisation I work >>for. I'm making some good in-roads. One chap sent me the text below on >>his views of Python. I wondered if anyone from the group could give me >>some advice on how to respond / if they had been in a similar position. [...] > Life would be easy if tools were only chosen on technincal, economical > and practical merits... > Altogether now" "If I ruled the world ..." > To put things into perspective, it's important to get beyond the very > broad categories of programming languages. It's pointless to judge > Python on the merits of Perl or AWK, just because a certain label is > sometimes applied to all three. That would be like saying that Java > is more or less like COBOL. (OO COBOL?) > Quite. People have said exactly that, you know ;-) http://www.artima.com/weblogs/viewpost.jsp?thread=42242 [...] 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 rurpy at yahoo.com Tue Nov 22 21:24:04 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 22 Nov 2005 18:24:04 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: <1132712643.968300.151010@g49g2000cwa.googlegroups.com> rhettinger at gmail.com wrote: > > > ii. The other problem is easier to explain by example. > > > Let it=iter([1,2,3,4]). > > > What is the result of zip(*[it]*2)? > > > The current answer is: [(1,2),(3,4)], > > > but it is impossible to determine this from the docs, > > > which would allow [(1,3),(2,4)] instead (or indeed > > > other possibilities). > > > """ > > > IMO left->right is useful enough to warrant making it defined > > > behaviour > > > > And in fact, it is defined behavior for itertools.izip() [1]. > > > > I don't see why it's such a big deal to make it defined behavior for > > zip() too. > > IIRC, this was discussednd rejected in an SF bug report. It should not > be a defined behavior for severals reasons: > > * It is not communicative to anyone reading the code that zip(it, it) > is creating a sequence of the form (it0, it1), (it2, it3), . . . IOW, > it conflicts with Python's style of plain-speaking. Seems pretty plain to me, and I am far from a Python expert. > * It is too clever by far -- much more of a trick than a technique. I see tons of tricks posted every day. There is a time and place for them. > * It is bug-prone -- zip(x,x) behaves differently when x is a sequence > and when x is an iterator (because of restartability). Don't leave > landmines for your code maintainers. Err thanks for the advice, but they are *my* code maintainers and I am the best judge of what constitutes a landmine. > * The design spirit of zip() and related functions is from the world of > functional programming where a key virtue is avoidance of side-effects. > Writing zip(it, it) is exploiting a side-effect of the implementation > and its interaction with iterator inputs. The real spirit of zip() is > having multiple sequences translated to grouped sequences out -- the > order of application (and order of retrieving inputs) should be > irrelevant. I'm not sure what to say when people start talking about "spirit" when making technical decisions. > * Currently, a full understanding of zip() can be had by remembering > that it maps zip(a, b) to (a0, b0), (a1, b1), . . . . That is simple > to learn and easily remembered. In contrast, it introduces unnecessary > complexity to tighten the definition to also include the order of > application to cover the special case of zip being used for windowing. > IOW, making this a defined behavior results in making the language > harder to learn and remember. I don't see how defining zip()'s behavior more precisely, interfers at all with this understanding. > Overall, I think anyone using zip(it,it) is living in a state of sin, > drawn to the tempations of one-liners and premature optimization. They > are forsaking obvious code in favor of screwy special cases. The > behavior has been left undefined for a reason. I really don't understand this point of view. It is exactly what I was just complaining about in a different thread. Every one your reasons (except the last, which is very weak anyway) is based on how you think someone may use zip if you define fully what it does. Why do you feel compelled to tell me how I should or shouldn't write my code?! It is this attitude of "we know what is best for you, child" that really pisses me off about Python sometimes. Please make language decisions based on technical considerations and not how you want me to use the language. Believe it or not, I can make those decisions on my own. From steve at REMOVEMEcyber.com.au Thu Nov 24 03:22:21 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 24 Nov 2005 19:22:21 +1100 Subject: wxPython Licence vs GPL References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> Message-ID: <4385783D.8050201@REMOVEMEcyber.com.au> Steve Holden wrote: > The thrust of my original remarks was to try to persuade the OP that the > original comment about changing the code was ingenuous. If you take some > code under license as a starting point then even if no line of code > remains unchanged at the end of the process your code is arguably a > derivative work of the original. "Derivative work" is not a well-formed concept. Many copyright lawyers have made many fortunes arguing whether or not this work or that work is a derivative work of some other. -- Steven. From robert.kern at gmail.com Sat Nov 12 06:28:53 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 12 Nov 2005 03:28:53 -0800 Subject: about array,arange In-Reply-To: <1d987df30511120252w3b07b187l71db482bffe35a11@mail.gmail.com> References: <1d987df30511120252w3b07b187l71db482bffe35a11@mail.gmail.com> Message-ID: Shi Mu wrote: > i got confused by the use of array and arange. > arange get array and range get list, why we need the two different types? When you're asking questions about a third-party module, it's a good idea to mention the module. In this case you're asking about scipy_core (hopefully) or else numarray or Numeric. The answer to your question is that sometimes we need to get largish arrays (not lists) of consecutive numbers quickly. array(range(N)) is wasteful of memory and time because it has to create a list of Python ints that are simply going to be thrown away once we're done converting to the needed array. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From uval at rz.uni-karlsruhe.de Mon Nov 21 06:51:01 2005 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Daniel_Sch=FCle?=) Date: Mon, 21 Nov 2005 12:51:01 +0100 Subject: duplicate items in a list In-Reply-To: References: Message-ID: Shi Mu wrote: > I used the following method to remove duplicate items in a list and > got confused by the error. > > >>>>a > > [[1, 2], [1, 2], [2, 3]] > >>>>noDups=[ u for u in a if u not in locals()['_[1]'] ] > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iterable argument required >>> a [[1, 2], [1, 2], [2, 3]] >>> c=[] >>> for x in a: ... if x not in c: c.append(x) ... >>> c [[1, 2], [2, 3]] or (Python 2.4) >>> a [[1, 2], [1, 2], [2, 3]] >>> set([frozenset(u) for u in a]) set([frozenset([1, 2]), frozenset([2, 3])]) hth Daniel From pwatson at redlinepy.com Wed Nov 23 18:45:41 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 23 Nov 2005 17:45:41 -0600 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <4384ec18$0$25871$9b622d9e@news.freenet.de> References: <3uk6siF11mqgvU1@individual.net> <4384ec18$0$25871$9b622d9e@news.freenet.de> Message-ID: <4384FF25.6000802@redlinepy.com> Martin v. L?wis wrote: > Paul Watson wrote: > >> Any ideas why ./Modules/cjkcodecs/_codecs_cn.c fails to compile? It >> appears that the CODEC_STATELESS macro is concatenating 'hz' with a >> number and text. > > > More likely, hz is already defined to be 100, then forming 100_encode. > > It would be best if you could find out what AIX header file defines > hz to be 100, and whether there is any way to supress that definition. > > Regards, > Martin This is on AIX 4.3.3 $ grep -i _hz $(find . -name m_param.h) #define _HZ 100 /* ticks per second of the clock */ #define __hz HZ /* Berkeley uses lower case hz */ #define HZ _HZ #define hz __hz $ cc_r 2>&1|head -1 VisualAge C++ Professional / C for AIX Compiler, Version 5 From strombrg at dcs.nac.uci.edu Mon Nov 7 14:36:22 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 07 Nov 2005 19:36:22 GMT Subject: O_DIRECT on stdin? Message-ID: Is there a way of setting O_DIRECT on a preexisting file like sys.stdin? Does C allow this sort of thing? Thanks! From ejensen at visi.com Wed Nov 23 18:33:41 2005 From: ejensen at visi.com (Ed Jensen) Date: Wed, 23 Nov 2005 23:33:41 -0000 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> Message-ID: <11o9v2l5qqa7765@corp.supernews.com> Paul Boddie wrote: > It's interesting that you bring this tired thought experiment up in the > context of the original remark: "Its license is far more "free" than > GPL is." If we were focusing on the "vox pop" interpretation of the > word "free", that remark wouldn't make any sense at all: after all, > what's more gratis than gratis (to use a less ambiguous word)? My only intention was to point out that "Free Software" is a rather misleading term. I still think of the term "Free Software" as false advertising. > Python is moderately successful, yes, but the GPL is a useful tool to > ensure that certain freedoms are preserved. I've been made aware of a > certain level of dissatisfaction about whether organisations porting > Python to other platforms would choose to share their modifications and > improvements with anyone, or whether binary downloads with restrictive > usage conditions would be the best even the customers of such > organisations would be able to enjoy. Ensuring some of those freedoms > can be an effective way of making open source software projects > successful. I'm aware of this concern. I don't think it's justified. Unless you'd like to point out all those closed, proprietary Python implementations that are destroying civilization as we know it. > At least when it comes to software licensing, what probably upsets the > anti-GPL "pragmatic licensing" crowd the most is that Stallman is quite > often right; the BitKeeper debacle possibly being one of the more > high-profile cases of some group's "pragmatism" (or more accurately, > apathy) serving up a big shock long after they'd presumably dismissed > "the hippie nonsense". Stallman thinks selling closed, proprietary software is evil. Stallman thinks buying closed, proprietary software is evil. I find these opinions and "morals" fundamentally and obviously wrong. > Well, from what I've seen of open source software usage in business, a > key motivation is to freeload, clearly driven by people who neither see > nor understand any other dimension of software freedom than your "vox > pop" definition. Such users of open source software could make their > work a lot easier if they contributed back to the projects from which > they obtained the software, but I've seen little understanding of such > matters. Of course, businesses prefer to use euphemisms like "cost > reduction" or "price efficiency" rather than the more accurate > "freeloading" term, and they fail to see any long-term benefits in > anything other than zero cost, zero sharing acquisition and > redistribution of code. But then in some sectors, the game is all about > selling the same solution over and over again to the same customers, so > it's almost understandable that old habits remain. Wah, wah, I gave this software away for free, and people are actually using it without giving anything back! Wah, wah! >> but then that gives me the right to refer to GPL'd software as "free as in pushing my >> personal social agenda". > Pushing on whom, though? No-one makes you use GPL'd software by, for > example, installing it on almost every computer you can buy from major > vendors. If, on the other hand, you mean that some social agenda is > being imposed on you because, in choosing to redistribute someone's > work, you are obliged to pass on those freedoms granted to you by the > creator (or distributor) of that work, then complaining about it seems > little more than a foot-stamping exercise than anything else. Now you're just trying to put words into my mouth. I never said anything was being "pushed on" me. I never said anything was being "imposed on" me. I said an agenda was being pushed. Stallman and company have an agenda, and the GPL is their instrument of choice for pushing that agenda. From fredrik at pythonware.com Thu Nov 10 12:46:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Nov 2005 18:46:13 +0100 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com><1131506094.767452.156780@o13g2000cwo.googlegroups.com><1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: Norman Silverstone wrote: > > Heh, you will find that Python is practically executable pseudo-code! > > > > Untested: > > > > > > def guess_number(): > > # please don't cheat the poor computer... > > print "Guess a number." > > lo = 0 > > hi = 100 > > while True: > > guess = (lo+hi)//2 > > ans = raw_input("Is it %d? y/n " % guess) > > if ans in ('y', 'yes'): > > break > > ans = raw_input("Too high? y/n ") > > if ans in ("y", "yes"): > > hi = guess-1 > > else: > > lo = guess+1 > > > > This should run, and it will *almost* do what you want. > > Thanks for that but I think it is too simplistic. It appears OK for the > first guess, which is 50 but, what about the next guess. did you test the script? here's a simulator: import re number = 0 guess = None count = 0 def raw_input(prompt): global count, guess reply = "n" m = re.search("\d+", prompt) if m: # guess a number count = count + 1 guess = int(m.group()) if guess == number: reply = "y" else: # check if too high if guess > number: reply = "y" print prompt, reply return reply def guess_number(): # please don't cheat the poor computer... print "Guess a number." lo = 0 hi = 100 while True: guess = (lo+hi)//2 ans = raw_input("Is it %d? y/n " % guess) if ans in ('y', 'yes'): break ans = raw_input("Too high? y/n ") if ans in ("y", "yes"): hi = guess-1 else: lo = guess+1 for number in range(0, 100+1): print "NUMBER IS", number count = 0 guess_number() print "SUCCESS AFTER", count, "GUESSES" # end > Comments please. if this had been a java "let's pretend you're the java runtime" certification question, you would have failed. From arkanes at gmail.com Fri Nov 18 16:43:04 2005 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Nov 2005 15:43:04 -0600 Subject: check if com api is still available In-Reply-To: <9Erff.20624$Hj2.1070@news-server.bigpond.net.au> References: <3u67k3Fvep32U1@news.dfncis.de> <9Erff.20624$Hj2.1070@news-server.bigpond.net.au> Message-ID: <4866bea60511181343t7aa1f5e8w6ebeb8781fd60b20@mail.gmail.com> On 11/18/05, Neil Hodgson wrote: > Hermann Maier: > > > i am using the com api of a program and if this program is shut down and > > my program calls a method of the api, it crashs. that means, i need to > > check, if the com server is still available, before i can call for it. > > The server should not shut down while clients have outstanding > references to objects within it. > The Excel COM object has this behavior - if you call the Quit() method or (if you're controlling an interactive instance) the excel window is closed, further calls to the COM object will throw errors. I couldn't find a solution to this other than to just make sure you didn't do that. However, I didn't know about the ROT and maybe that will work. > > but i would prefer a > > solution that is more clean from the beginning. perhaps there is a > > windows event that can tell me, wenn the other application, that hosts > > the com server, is closed or perhaps i can do something with the guid of > > the com server, maybe there is a call where i can check, if a certain > > com server is available. > > All running COM servers should be in the "Running Object Table" > (ROT). If you search the net for this term you will find code that can > show what is in the ROT, so there must be an API. > > Neil > -- > http://mail.python.org/mailman/listinfo/python-list > From rhaper at houston.rr.com Sat Nov 5 18:20:31 2005 From: rhaper at houston.rr.com (Rod Haper) Date: Sat, 05 Nov 2005 23:20:31 GMT Subject: Using Which Version of Linux In-Reply-To: References: Message-ID: <37bbf.50495$5e4.36565@tornado.texas.rr.com> Dan M wrote: > > Personally I would recommend staying away from Fedora unless you have a > friend who is well-versed in it and willing to help. I like the > distributin ok (I run it on the laptop I'm writing this from) but it uses > RPMs for package distribution, and the rpm tools don't know how to > automatically downloaded dependencies like yum or apt do. Because of that > I have to say that the RPM package tools suck quite badly. Dan, I don't know what version of Fedora you are running but FC4 and FC3 use yum for updating. --- Rod From aum at spam.me.please Mon Nov 14 15:43:20 2005 From: aum at spam.me.please (aum) Date: Tue, 15 Nov 2005 09:43:20 +1300 Subject: q: console widgets for *nix and windows? Message-ID: Hi, Can anyone please recommend a widget library for text console, that works not only on *nix systems but windows /as well/? I'm looking for something a bit higher-level than pure curses, preferably with a gui-like set of widgets, event loop, handler methods etc. Thanks in advance for your recommendations. -- Cheers aum From tony.meyer at gmail.com Thu Nov 17 03:25:37 2005 From: tony.meyer at gmail.com (Tony Meyer) Date: Thu, 17 Nov 2005 21:25:37 +1300 Subject: python-dev summary In-Reply-To: <20051117062014.GA10920@caltech.edu> References: <20051117062014.GA10920@caltech.edu> Message-ID: On 17/11/2005, at 7:20 PM, Titus Brown wrote: >> [The HTML version of this Summary is available at >> http://www.python.org/dev/summary/2005-09-01_2005-09-15.html] > > no... no, it's not ;) Sorry; I should amend the copy that's posted to say "will be available". The summaries get posted here, to python-announce, and sent to Brett to be put online. The one here appears immediately, the python-announce one appears whenever a moderator has time to approve it, and the one online appears when Brett has time to put it up. =Tony.Meyer From bdesth.quelquechose at free.quelquepart.fr Sat Nov 12 20:16:05 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 Nov 2005 02:16:05 +0100 Subject: derived / base class name conflicts In-Reply-To: <1131724161.083151.255920@g14g2000cwa.googlegroups.com> References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> <1131677456.966817.147470@g44g2000cwa.googlegroups.com> <43747075$0$7344$636a55ce@news.free.fr> <1131724161.083151.255920@g14g2000cwa.googlegroups.com> Message-ID: <43768996$0$18770$626a14ce@news.free.fr> christopherlmarshall at yahoo.com a ?crit : > Your suggestion ('_name' -> implementation, 'name' -> API) This is not "my" convention, it's *the* (mostly agreed upon) Python convention. Like 'self', or CONSTANT, or a whole lot of things in Python. > makes sense > as a convention between programmers that know a fair amount about each > other's classes before using them. No need to know much. dir(modulename.ClassName) is enough. > I don't think it is reasonable in general to only subclass from base > classes you have studied the full API of, however. Depends on your definition of "studying the full API" !-) Now if your fear is to accidentally override something in the base class, it's just a matter of: print "API:" print [name for name in dir(modulename.ClassName) \ if not name.startswith('_')] print "IMPLEMENTATION:" print [name for name in dir(modulename.ClassName) \ if not name.startswith('_')] > The double > underscore is a decent solution to my problem. Possibly. It can also become a PITA. But it's you who know what your code need !-) > I imagine it must be used a lot in domains where people are making > heavy use of third party python code. I almost never used it (perhaps half-a-dozen times, and only in frameworks abstract base classes), and rarely saw it in 3rd part source code. From 28tommy at gmail.com Sun Nov 13 05:57:04 2005 From: 28tommy at gmail.com (28tommy) Date: 13 Nov 2005 02:57:04 -0800 Subject: Want to perform unattended installation of SW using python Message-ID: <1131879424.943510.320180@g47g2000cwa.googlegroups.com> Hi, I'm trying to automate an installation of some SW that is installed on Windows (you know - 'Start' ==> 'Next' ==> 'Next' ==> 'Finish' kind of installation). Is ther any way to perform that using python? Thank you. tommy From vd12005 at yahoo.fr Tue Nov 29 03:53:08 2005 From: vd12005 at yahoo.fr (vd12005 at yahoo.fr) Date: 29 Nov 2005 00:53:08 -0800 Subject: (newbie) N-uples from list of lists References: <1132776015.567869.214570@g14g2000cwa.googlegroups.com> <1132938602.483207.74600@f14g2000cwb.googlegroups.com> Message-ID: <1133254388.897596.125270@g47g2000cwa.googlegroups.com> great thanks to all. actually i have not seen it was a cross product... :) but then there are already few others ideas from the web, i paste what i have found below... BTW i was unable to choose the best one, speaking about performance which one should be prefered ? ### -------------------------------------------------- ### from title: variable X procuct - [(x,y) for x in list1 for y in list2] ### by author: steindl fritz ### 28 mai 2002 ### reply by: Jeff Epler def cross(l=None, *args): if l is None: # The product of no lists is 1 element long, # it contains an empty list yield [] return # Otherwise, the product is made up of each # element in the first list concatenated with each of the # products of the remaining items of the list for i in l: for j in cross(*args): yield [i] + j ### reply by: Raymond Hettinger def CartesianProduct(*args): ans = [()] for arg in args: ans = [ list(x)+[y] for x in ans for y in arg] return ans """ print CartesianProduct([1,2], list('abc'), 'do re mi'.split()) """ ### from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975 ### by: Raymond Hettinger def cross(*args): ans = [[]] for arg in args: ans = [x+[y] for x in ans for y in arg] return ans ### from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975 ### by: Steven Taschuk """ Iterator version, Steven Taschuk, 2003/05/24 """ def cross(*sets): wheels = map(iter, sets) # wheels like in an odometer digits = [it.next() for it in wheels] while True: yield digits[:] for i in range(len(digits)-1, -1, -1): try: digits[i] = wheels[i].next() break except StopIteration: wheels[i] = iter(sets[i]) digits[i] = wheels[i].next() else: break From martin at v.loewis.de Tue Nov 22 20:30:18 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Nov 2005 02:30:18 +0100 Subject: linking one extension module to another (Mac OSX) In-Reply-To: <1132649559.788680.20710@o13g2000cwo.googlegroups.com> References: <1132631865.024503.302080@g43g2000cwa.googlegroups.com> <4382b145$0$28799$9b622d9e@news.freenet.de> <1132649559.788680.20710@o13g2000cwo.googlegroups.com> Message-ID: <4383c62a$0$30488$9b622d9e@news.freenet.de> pianomaestro at gmail.com wrote: > I have C Extension classes distributed across several modules with > non-trivial interdependancies. I guess you are saying I should have > these in backend libraries and then put the module specific functions > in the module itself. It's going to be tricky because I am using > distutils and pyrex to do all this. Maybe Greg (Ewing) has some other > ideas. Alternatively, if you are always shipping the entire set: make them all a single extension module. For backwards compatibility, provide Python modules with the "old" module names, which export the symbols that used to be in that module. Regards, Martin From fredrik at pythonware.com Sun Nov 13 04:16:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Nov 2005 10:16:46 +0100 Subject: the button of cancel References: <8c11e4350511122015l63fc54e1md0e5a1c1a3cf6904@mail.gmail.com> Message-ID: Ben Bush wrote: > When I click the button of cancel, > I got the follwoing message. I want to see "Goodbye" on the console screen. > What to do? > KeyboardInterrupt: operation cancelled > num = input( "Enter a number between 1 and 100: " ) > while num < 1 or num > 100: > print "Oops, your input value (", num, ") is out of range." > num = input( "Be sure to enter a value between 1 and 100: " ) you need to catch the exception, and print the message you want. try: ... your code ... except KeyboardInterrupt: print "Goodbye!" see chapter 8.3 in the tutorial for more info: http://docs.python.org/tut/node10.html From donn at u.washington.edu Wed Nov 23 13:22:24 2005 From: donn at u.washington.edu (Donn Cave) Date: Wed, 23 Nov 2005 10:22:24 -0800 Subject: pipe related question References: Message-ID: In article , David Reed wrote: > Is there any way to have one program run another arbitrary program > with input from stdin and display the output as if you had run it in > a shell (i.e., you'd see some of the output followed by the input > they typed in and then a newline because they pressed return followed > by subsequent output, etc.). > > I can't use readline with the pipe because I don't know how much > output the arbitrary program has before it calls an input statement. > I've googled and understand that calling read() will deadlock when > the program is waiting for input. > > When I first write all the input to the input pipe and then call read > on the output pipe it works just the same as if I had run the program > as: program < input_file > > What I'd like to see is the input intermixed with the output as if > the user had typed it in. It sounds like there may be two problems here. You may need to go to some extra lengths to get the arbitrary program to adopt a convenient buffering strategy. I'm sure you have come across plenty of discussion of this problem in your review of the old traffic in this group, since it comes up all the time. The usual answer is to use a pseudotty device instead of a regular pipe. I don't know what's currently popular for Python support of this device, but there's builtin support on some platforms, cf. os.openpty and os.forkpty. It may be convenient in your case to turn ECHO on. The other problem is more intractable. If you want to know for sure when the arbitrary program expects input, well, UNIX doesn't support that. (Can you run your application on VMS?) The only thing I can think of is a select() with timeout, with some compromise value that will allow most outputs to complete without stalling longer than is really convenient. Donn Cave, donn at u.washington.edu From aahz at pythoncraft.com Mon Nov 28 13:11:43 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Nov 2005 10:11:43 -0800 Subject: General question about Python design goals References: Message-ID: In article , Sebastien Douche wrote: > >I use this thread to asking on python conception : why python have so >many builtins ? >I cannot understand why we use a builtins for open a file. Is it a old >decision ? If anyone have a pointer of this or can explain me. One of the primary goals for Python is to make it easy to use for new programmers. Particularly for sysadmins, opening a file for reading and writing is considered such a basic task that it's part of the builtins. There are some builtins slated for removal in Python 3.0 (e.g. apply(), which is superseded by *args/**kwargs being allows on the calling side). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair From jmdeschamps at gmail.com Sun Nov 6 20:48:00 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 6 Nov 2005 17:48:00 -0800 Subject: I need Motivation In-Reply-To: <1131089202.065204.48370@z14g2000cwz.googlegroups.com> References: <436b0b9b$0$11068$e4fe514c@news.xs4all.nl> <1131089202.065204.48370@z14g2000cwz.googlegroups.com> Message-ID: <1131328080.937498.86010@f14g2000cwb.googlegroups.com> And you know what? I almost sure most people on this newsgroup wouldn't feel maligned if somebody told them that's what happened to them. I'd put money that most pythonistas here would think 'Hey Great for you! good luck, and make these machines ever more useful and/or enjoyable for the rest of the universe and yourself!' But that's only how I feel about this perticular newsgroup and community! (But I've been knowned to be na?ve ...) From eternalsquire at comcast.net Wed Nov 16 17:06:32 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 16 Nov 2005 14:06:32 -0800 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> Message-ID: <1132178792.001827.280820@z14g2000cwz.googlegroups.com> >Utter poppycock. Who is to say that a particular entity holds an >exclusive "sales opportunity" to a particular individual? Are we to >protect the expectations of profit for some, at the expense of sharing >things with each other? Utter horse manure. Anyone can profit from something so long as it is thier own idea. >> Ourselves and our children are lost generations with respect to >> ethics, manners, >Ethics such as sharing, and helping one's neighbour? Giving away an illegal copy of software it not helping one's neighbor, it is making that neighbor an accessory to copyright infringement, a federal offense punishable not in excess of 10 years of $10K. Such a nieghbor should ask: "with friends like that, who needs enemies?" >I certainly hope our grandchildren will live in an environment that >encourages helping each other, yes. Helping each other cheat on a test is not helping, it is hurting. There is no difference ethically between plagiarism, cheating, or unauthorized copying. From rainbow.cougar at gmail.com Mon Nov 7 23:03:43 2005 From: rainbow.cougar at gmail.com (rainbow.cougar at gmail.com) Date: 7 Nov 2005 20:03:43 -0800 Subject: So, Which Version is Suitable for Beginners In-Reply-To: References: Message-ID: <1131422623.316293.300560@g44g2000cwa.googlegroups.com> I have found my novice Linux users take to SUSE (either Gnome or KDE) readily. Probably because the devfs interfaces to the windows interface readily. From tim.tadh at gmail.com Mon Nov 28 00:13:29 2005 From: tim.tadh at gmail.com (Tim Henderson) Date: 27 Nov 2005 21:13:29 -0800 Subject: Comparison problem In-Reply-To: References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: <1133154809.084481.138050@f14g2000cwb.googlegroups.com> of course the more correct way is most likely the use of short circuit evaluation. so somthing along lines of if (len(item) > 0) and (item[0] == '-'): pass would probably be the correct approach. From spam4bsimons at yahoo.ca Mon Nov 7 20:16:23 2005 From: spam4bsimons at yahoo.ca (Brendan) Date: 7 Nov 2005 17:16:23 -0800 Subject: Newbie Alert: Help me store constants pythonically In-Reply-To: <436EDDA8.5020600@REMOVEMEcyber.com.au> References: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> <436EDDA8.5020600@REMOVEMEcyber.com.au> Message-ID: <1131412583.285926.185740@g49g2000cwa.googlegroups.com> > How many is LOOONG? Ten? Twenty? One hundred? About 50 per Model > If it is closer to 100 than to 10, I would suggest > putting your constants into something like an INI file: > > [MODEL1] # or something more meaningful > numBumps: 1 > sizeOfBumps: 99 > > [MODEL2] > numBumps: 57 > sizeOfBumps: 245 > > > etc. > > Then sub-class the ConfigParser to create struct-like > objects from an ini file. Something vaguely like: > > # warning: pseudo-code, seriously not tested!!! > class Config2Consts(ConfigParser): > """Reads an INI file, and creates a struct-like > object from each section, storing that object > in the local scope with the name of the section. > """ > > class Struct: > def __init__(self): > pass > > def make_single_constant_object(self, sectionname): > obj = Struct() > for field in INI_FILE[sectionname]: > obj.__dict__[field.name] = field.value > locals().update({sectionname: obj}) > > > > If you are likely to be changing the constants (either > names, field names, or values) an hour or three > developing this code will save you a lot of heart-ache > later. Thanks for your reply Steve. I like this suggestion because it separates my config data from the code, which could mean less headaches editing the values later. It also lets me keep my constants language-neutral, which is good because I haven't convinced my boss yet that Python's the way to go. The only downside is that it doesn't do any 'name checking', so any mistakes in my config file won't show up until the middle of the analysis. Maybe this is a 'static language' mode of thinking, but it seems risky. Also my config files have (a tiny bit of) nested structure, such as: Model1( numBumps = 1 sizeOfBumps = 2 transversePlanes = [ Plane(type=3, z=4), Plane(type=5, z=6), Plane(type=3, z=8) ] ) which I'm not sure the .ini format can easily support. I could use (key buzzword voice) XML, but I fear that might send me down the 'overcomplicating things' path. Your suggestion has given me some new places to search Google (configparser, python config files), so I'll look around for better ideas. Brendan From eight02645999 at yahoo.com Tue Nov 1 20:54:45 2005 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 1 Nov 2005 17:54:45 -0800 Subject: python CGI,sybase and environ variables Message-ID: <1130896485.220506.103570@g43g2000cwa.googlegroups.com> hi i am writing a CGI to process some database transactions using the Sybase module. so in my CGI script, i have: ... import Sybase import cgitb; cgitb.enable(display=1 , logdir="/tmp/weblog.txt") ... ... the problem is , everytime i have ImportError: No module named Sybase flagged out. at first i think it's library path misconfiguration, so i put os.environ["SYBASE"] = '/path/to/sybase' os.environ["LD_LIBRARY_PATH"] = '/path/to/sybase/lib' before i import Sybase. but its still the same error Ok.so now, is it necesary to configure the web server's "nobody" user's profile to point to the Sybase libraries? or worse, configure root's profile to point to Sybase libraries? what's could be wrong? thanks for any help rendered. From didier.doussaud at gmail.com Wed Nov 30 03:42:57 2005 From: didier.doussaud at gmail.com (didier.doussaud at gmail.com) Date: 30 Nov 2005 00:42:57 -0800 Subject: Why I need to declare import as global in function In-Reply-To: References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> Message-ID: <1133340177.628299.181340@g44g2000cwa.googlegroups.com> I think I understand my problem, but first the sample code extracted to my project. Rq : it's an automatic run of unitary test, the names of unitary test are parameter of main program "imported" file via the "execfile" function (an usage of "import" instead may be a solution....) : file run.py : ---------------- def run_ut( test ) : # to have the problem the execfile MUST be in a function execfile( test ) run_ut( "ut_00.py" ) file ut_00.py : -------------------- import math def f() : ## global math # <-- just decomment this line to avoid error print "Second access :" print "\t",math.pi # ERROR print "First access :" print "\t",math.pi # OK f() From timr at probo.com Mon Nov 21 02:22:03 2005 From: timr at probo.com (Tim Roberts) Date: Mon, 21 Nov 2005 07:22:03 GMT Subject: Problem printing in Win98 References: <1132474167.583323.137390@z14g2000cwz.googlegroups.com> Message-ID: <6at2o117cb9a7b59h6le7g35qomk5gimtv@4ax.com> "Maravilloso" wrote: > >I'm trying to automatically send a postscript file to be printed to the >default printer in a Win98 PC, by means of using the instrucction: > > win32api.ShellExecute (0, "print", "file.ps", None, ".", 0) > >but it raises an exception with the message: > > error: (31, 'ShellExecute', 'A device attached to the system is not >functioning.') Roger is correct. In order to print a .ps file, you have to have installed an application that handles .ps files. You have probably installed GhostScript on your 2K/XP box. If you install it on your Win98 box, your ShellExecute should work. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From aleax at mail.comcast.net Mon Nov 14 21:29:34 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 14 Nov 2005 18:29:34 -0800 Subject: best way to discover this process's current memory usage, cross-platform? Message-ID: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> Having fixed a memory leak (not the leak of a Python reference, some other stuff I wasn't properly freeing in certain cases) in a C-coded extension I maintain, I need a way to test that the leak is indeed fixed. Being in a hurry, I originally used a q&d hack...: if sys.platform in ('linux2', 'darwin'): def _memsize(): """ this function tries to return a measurement of how much memory this process is consuming, in some arbitrary unit (if it doesn't manage to, it returns 0). """ gc.collect() try: x = int(os.popen('ps -p %d -o vsz|tail -1' % os.getpid()).read()) except: x = 0 return x else: def _memsize(): return 0 Having a _memsize() function available, the test then does: before = _memsize() # a lot of repeated executions of code that should not consume # any net memory, but used to when the leak was there after = _memsize() and checks that after==before. However, that _memsize is just too much of a hack, and I really want to clean it up. It's also not cross-platform enough. Besides, I got a bug report from a user on a Linux platform different from those I had tested myself, and it boils down to the fact that once in a while on his machine it turns our that after is before+4 (for any large number of repetitions of the code in the above comment) -- I'm not sure what the unit of measure is supposed to be (maybe blocks of 512 byte, with a page size of 2048? whatever...), but clearly an extra page is getting used somewhere. So, I thought I'd turn to the "wisdom of crowds"... how would YOU guys go about adding to your automated regression tests one that checks that a certain memory leak has not recurred, as cross-platform as feasible? In particular, how would you code _memsize() "cross-platformly"? (I can easily use C rather than Python if needed, adding it as an auxiliary function for testing purposes to my existing extension). TIA, Alex From rhettinger at gmail.com Wed Nov 23 13:03:13 2005 From: rhettinger at gmail.com (rhettinger at gmail.com) Date: 23 Nov 2005 10:03:13 -0800 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> Message-ID: <1132768993.161352.260810@g49g2000cwa.googlegroups.com> bonono at gmail.com wrote: > it seems that quite some people > don't see the language as the creator or wants them to see it. Here's my two cents on this recurring theme. While nothing forces a particular programming style, there is some merit to swimming with the current rather than against it. Observing five years of newsgroup posts, I've observed that many who struggle with language or get angry about some part of it are fighting the language rather than using it as intended/designed. IMO, following designer intent leads to happiness because Guido's philosophies so thoroughly pervade the language. So, when you accept his viewpoints, you'll find that all the parts of the language tend to fit together neatly and easily. Conversely, fighting the language tends to result in one struggle after the next. For example, there is a person currently working on a new proposal for a container freezing protocol. In order to overcome all the fundamental difficulties (like what to do with mutable values when freezing a dictionary), the proponent is finding that he has to suggest pervasive changes to the language (including mutable strings, recursive freezing protocols, mutation notifications, etc). I suspect that he is fighting the language. It is not so much that his idea is wrong, it is just that he is effectively creating another language that is not Python. My own experience with adapting to Guido's design-view relates to tuples and lists. To Guido, tuples are for records and lists are for iteration. My own inclination is to view tuples as immutable lists. Accordingly, it seems obvious to me that tuples should have count() and index() methods for better substitutability. However, I've learned that adapting to Guido's world-view leads to happiness because Python's function signatures tend to reflect his design view. So, when I'm thinking the Guido way, my code comes together seamlessly. When I persist with a conflicting viewpoint, I find myself having to make conversions, write work-arounds, or create more helper functions than otherwise needed. Keep this in mind when finding yourself madder than heck about mylist.sort() returning None or zip(it,it) intentionally not documenting its implementation quirks. IMO, using the tools as given leads to easily-written, clean, maintainable, beautiful code. Learn to love what makes Python great. Pounding a square object into a round hole should be a cue that you're doing things the hard way ;-) respectfully submitted, Raymond From grante at visi.com Tue Nov 1 18:13:58 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Nov 2005 23:13:58 -0000 Subject: Python's website does a great disservice to the language References: Message-ID: <11mftlmkcu3dqf0@corp.supernews.com> On 2005-11-01, Benjamin Niemann wrote: > Steven D'Aprano wrote: > >> http://www.python.com/ perhaps? > > Yep, let's make this the new official python site ;) Well, I have to admit that I think the scheme they use to get you load the large flash chunk is pretty clever. Most sites just have a large blank rectangle where the flash stuff is supposed to be. These guys have figured out that they should put something _under_ the flash rectangle that elicits a click out of people who have flash disabled by default. Um, not that I clicked, or anything... -- Grant Edwards grante Yow! Send your questions at to "ASK ZIPPY", Box 40474, visi.com San Francisco, CA 94140, USA From http Sun Nov 6 14:08:20 2005 From: http (Paul Rubin) Date: 06 Nov 2005 11:08:20 -0800 Subject: Learning multiple languages (question for general discussion) References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> <1h5hs5y.19u42x51mo5hupN%aleax@mail.comcast.net> <7xvez5wvgc.fsf@ruckus.brouhaha.com> <3t6ubgFr6f2dU1@uni-berlin.de> Message-ID: <7xslu9ppaz.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > It's a great book - I cetainly owe it the better part of my thesis > about multi level specification for functional languages. If you want > to understand type-systems, its a great comprehensive read. So do I really want to understand type systems? I mean, I think I understand Haskell types from reading the manual, but probably not at the level of that TAPL book. Am I going to find out anything important as an implementer? From steve at REMOVEMEcyber.com.au Thu Nov 3 01:48:47 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 03 Nov 2005 17:48:47 +1100 Subject: reading internet data to generate random numbers. References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> <11mj21gr6rjgc65@corp.supernews.com> <86ll06jr79.fsf@bhuda.mired.org> Message-ID: <4369B2CF.70201@REMOVEMEcyber.com.au> Mike Meyer wrote: > Grant Edwards writes: > >>On 2005-11-02, Neil Schemenauer wrote: >> >>>Grant Edwards wrote: >>>Using data from the Internet is just a bad idea. >> >>I think that the timing of certain network events is one of the >>Linux kernel's entropy sources. > > > BSD as well. The key word is "one". While network events don't make a > good source of random data, proplery combining such sources can create > good random data. Depends on what you mean by "random". In particular, the randomness of network events does not follow a uniform distribution, but then not many things do. Uniformly distributed random data is what you want for cryptography. If you are modelling physical events, you might want some other distribution, e.g. normal (bell curve), Poisson, exponential, binomial, geometric, hypergeometric, and so forth. I have no idea what distribution data from the Internet would have, I would imagine it is *extremely* non-uniform and *very* biased towards certain values (lots of "<" and ">" I bet, and relatively few "\x03"). But, for the sake of the argument, if that's the random distribution that you actually need, then the Internet would be a good source of randomness. <\pedant> Just not for encryption. It would be terrible for that. > Randomness is a deep subject. This is certainly true. I love the Dilbert cartoon where Dilbert is on a tour of Accounting. He comes across a troll sitting at a desk chanting "Nine, nine, nine, nine, ...". His guide says, "This is our random number generator." Dilbert looks skeptical and asks "Are you sure that's random?", to which the guide answers "That's the trouble with randomness, you can never be sure." -- Steven. From kylotan at gmail.com Mon Nov 14 07:01:09 2005 From: kylotan at gmail.com (Ben Sizer) Date: 14 Nov 2005 04:01:09 -0800 Subject: Python obfuscation In-Reply-To: <86br0r40rc.fsf@bhuda.mired.org> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> Message-ID: <1131969669.048494.55680@o13g2000cwo.googlegroups.com> Mike Meyer wrote: > > I have considered distributing my program as open source but with > > encrypted data. Unfortunately anyone can just read the source to > > determine the decryption method and password. Maybe I could put that > > into an extension module, but that just moves the weak link along the > > chain. > > This isn't a Python problem, it's a problem with what you're doing. Try > Alex's solution, and put the data on a network server that goes > through whatever authentication you want it to. To be fair, I don't think I have accused Python of having a problem, just mentioned that this is an area where Python is less appropriate than other languages which have a significant degree of obfuscation as a side-effect of their use. I already explained elsewhere that putting the data on the network is not always appropriate. I know people love web services and the like these days, but they are not the answer to everything. Even in situations where it is practical to keep all the data server-side, it still just moves the problem rather than solving it, in that instead of people copying the data they now copy the authentication for the data. Anecdotal evidence from experiences with online registration for Half-Life 2 and Windows XP would suggest that this method ends up annoying more legitimate customers than the usual copy-protection does. > It is? Is the Python disassembler so much advanced over the state of > the art of binary disassemblers, then? Or maybe it's the Python > decompilers that are so advanced? Decompyle (http://www.crazy-compilers.com/decompyle/ ) claims to be pretty advanced. I don't know if you can download it any more to test this claim though. > As far as I can tell, the only real > difference between Python bytecodes and x86 (for instance) binaries is > that Python bytecodes keep the variable names around so it can do > run-timme lookups. That's not that big a difference. It makes a lot of difference when you're hunting around for something or trying to understand a bit of code. Python bytecode (or at least, the output from dis) is also a lot more straightforward than x86 or 68K assembly to decipher. > > No, certainly not. But if you can mitigate your losses easily enough - > > without infringing upon anyone else's rights, I must add - then why not > > do so. > > Elsewhere in the thread, you said: > > > I'd just like to make it non-trivial to make or use additional copies. > > How do you do that without infringing my fair use rights? Yes, I suppose my terminology there was wrong. The term I should probably have used was 'distribute usable additional copies'. Generally speaking I believe in the "like a book" interpretation of rights... you should have the right to give it away, sell it to someone, lend it, excerpt parts for review or criticism, but not to distribute additional copies that essentially duplicate the original. On the other hand though, what you term a 'fair use right' is not necessarily viewed that way under law. The relevant part of the law (at least in the US) says "it is not an infringement for the owner of a copy of a computer program to make or authorize the making of another copy or adaptation of that computer program provided [...] that such new copy or adaptation is for archival purposes only", which is quite distinct, legally speaking, from saying "you have the right to make a copy or adaptation for archival purposes". However, this is drifting more into the legal area which I am less interested in. Really I'd just like to be able to use Python for my work and am interested in finding the best way of doing so. -- Ben Sizer. From pythonnew at gmail.com Sat Nov 12 23:27:30 2005 From: pythonnew at gmail.com (Ben Bush) Date: Sat, 12 Nov 2005 20:27:30 -0800 Subject: triangulation Message-ID: <8c11e4350511122027j4ebd1c52yc01d92697a2e3a23@mail.gmail.com> Is there any pure python ocde there thoguh it is slow? Not many people know C very well and it will be great to have some python code even for education use. Ben I know someone once mentioned that they tried writing one of the Delaunay triangulation algorithms in pure Python and abandoned it for being unusably slow. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Wed Nov 30 05:58:17 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2005 10:58:17 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: Antoon Pardon wrote: > But lets just consider. Your above code could simply be rewritten > as follows. > > res = list() > for i in range(10): > res.append(i*i) > I don't understand your point here? You want list() to create a new list and [] to return the same (initially empty) list throughout the run of the program? > Personnaly I think that the two following pieces of code should > give the same result. > > def Foo(l=[]): def Foo(l): > ... ... > > Foo() Foo([]) > Foo() Foo([]) > > Just as I think, you want your piece of code to give the same > result as how I rewrote it. > > I have a problem understanding people who find the below don't > have to be equivallent and the upper must. The left one is equivalent to: __anon = [] def Foo(l): ... Foo(__anon) Foo(__anon) The left has one list created outside the body of the function, the right one has two lists created outside the body of the function. Why on earth should these be the same? Or to put it even more simply, it seems that you are suggesting: __tmp = [] x = __tmp y = __tmp should do the same as: x = [] y = [] From steve.morin at gmail.com Fri Nov 18 15:16:40 2005 From: steve.morin at gmail.com (Steve) Date: 18 Nov 2005 12:16:40 -0800 Subject: Web-based client code execution In-Reply-To: <3u6q0kFvnv1qU2@individual.net> References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> <3u6q0kFvnv1qU2@individual.net> Message-ID: <1132345000.666629.233190@g47g2000cwa.googlegroups.com> You universally won't be able to do that with javascript, only with and extension on firefox. ActiveX will limit you to windows only with ie. Which isn't bad you still get a 80% market share. From fredrik at pythonware.com Tue Nov 22 12:56:04 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 18:56:04 +0100 Subject: PIL FITs image decoder References: <1132681491.921657.291860@z14g2000cwz.googlegroups.com> Message-ID: "jbrewer" wrote: > I'm trying to read in a FITs image file for my research, and I decided > that writing a file decoder for the Python imaging library would be the > easiest way to accomplish this for my needs. FITs is a raw data format > used in astronomy. > > Anyway, I followed the example in the PIL documentation online, and I > also had a look at the FITs image stub file included with PIL 1.1.5. I > cooked up something that should work (or nearly work), but I keep > running into either one of two errors (below). The crux of the problem > appears to be that my plugin isn't being registered properly and isn't > being read at runtime when I call Image.open(). > > 1.) The library loads the FitsStubImagePlugin.py file from the > site-packages directory (instead of my plugin) and then gives the > following error: unfortunately, the stub loaders (which were introduced in 1.1.5) may over- ride more specific plugins. this will be fixed in 1.1.6. I don't see any obvious problems with your file, except that you should in- herit from ImageFile, not StubImageFile: class FitsImageFile(ImageFile.StubImageFile): should be class FitsImageFile(ImageFile.ImageFile): but I assume you've already tried that. if you can you mail me (or point me to) a sample file, I can take a look. From bokr at oz.net Tue Nov 22 15:03:16 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 20:03:16 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> Message-ID: <438378f3.485063444@news.oz.net> On 22 Nov 2005 11:11:23 GMT, Duncan Booth wrote: >metiu uitem wrote: > >> Say you have a flat list: >> ['a', 1, 'b', 2, 'c', 3] >> >> How do you efficiently get >> [['a', 1], ['b', 2], ['c', 3]] > >That's funny, I thought your subject line said 'list of tuples'. I'll >answer the question in the subject rather than the question in the body: > >>>> aList = ['a', 1, 'b', 2, 'c', 3] >>>> it = iter(aList) >>>> zip(it, it) >[('a', 1), ('b', 2), ('c', 3)] > Thank you for that. That is cool ;-) Regards, Bengt Richter From cfajohnson at gmail.com Tue Nov 8 22:33:47 2005 From: cfajohnson at gmail.com (Chris F.A. Johnson) Date: Tue, 8 Nov 2005 22:33:47 -0500 Subject: Goto XY References: <1131499644.561039.16420@g14g2000cwa.googlegroups.com> Message-ID: On 2005-11-09, ale.of.ginger at gmail.com wrote: > Is there some command in python so that I can read a key's input and > then use a gotoxy() function to move the cursor on screen? e.g.: > (psuedo-code) You can use curses, but that may be more trouble than it's worth. If you don't mind limiting your program to an ANSI-type terminals (vt100, xterm, rxvt, linux, putty, etc....), then you can just use the codes to position the cursor: ESC = '\033' CSI = ESC + "[" def printat(row,col,arg=""): sys.stdout.write( CSI + str(row) + ";" + str(col) + 'H' + str(arg)) > When the right arrow is pushed, cursor gotoxy(x+1,y) To read a single keystroke, see Claudio Grondi's post in the thread "python without OO" from last January. Function and cursor keys return more than a single character, so more work is required to decode them. The principle is outlined in ; the code there is for the shell, but translating them to python should be straightforward. I'll probably do it myself when I have the time or the motivation. -- Chris F.A. Johnson | Author: | Shell Scripting Recipes: Any code in this post is released | A Problem-Solution Approach, under the GNU General Public Licence | 2005, Apress From iddw at hotmail.com Fri Nov 18 19:03:46 2005 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 18 Nov 2005 18:03:46 -0600 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <98c1n1pjakk6huav7n1poou2d8kbskb5ah@4ax.com> Message-ID: Sorry for the delayed response. I somehow missed this earlier. On Tue, 8 Nov 2005 15:39:09 +0000 (UTC) in comp.lang.python, roy at panix.com (Roy Smith) wrote: >Dave Hansen wrote: >> Of course, I write _far_ more code in C than Python. But I've seen >> enough bugs of the sort where someone wrote 1200000 when they meant Digression: 1 was enough. >> 12000000, that I see great value in being able to specify 12_000_000. > >I'll admit that being able to write 12_000_000 would be convenient. >On the other hand, writing 12 * 1000 * 1000 is almost as clear. In C, Perhaps, but it's pretty obvious that something's wrong when you have to resort to ugly tricks like this to make the value of a simple integer constant "clear." And think about 64 (or longer) -bit unsigned long long hexadecimal values. How much nicer is 0xFFF0_FF0F_F0FF_0FFF_ULL than 0xFFF0FF0FF0FF0FFFULL? I guess we could do something like ((((0xFFF0ULL<<16)|0xFF0FULL)<<16)|0xF0FFULL)<<16)|0x0FFFULL), but I'm not sure it's any better. Regards, -=Dave -- Change is inevitable, progress is not. From fredrik at pythonware.com Tue Nov 1 09:36:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 1 Nov 2005 15:36:36 +0100 Subject: Scanning a file References: <1130497567.764104.125110@g44g2000cwa.googlegroups.com><7xek65nal0.fsf@ruckus.brouhaha.com><1130505731.850947.68690@o13g2000cwo.googlegroups.com><87ek65kbw5.fsf@lucien.dreaming><1h5760l.1e2eatkurdeo7N%aleaxit@yahoo.com><3siakvFohl3aU1@individual.net><1h57cij.16dkc141lds4s4N%aleaxit@yahoo.com><1h597yx.wjk2a71spyjhyN%aleaxit@yahoo.com><3smn47FoolfbU1@individual.net><3snboiFolt77U1@individual.net> <1h5be7i.1k1k09i1c543fcN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: >> As far as I know, Python simply relies on the opreating system to close >> files left open at the end of the program. > > Nope, see > leobject.c?rev=2.164.2.3&view=markup> that's slightly misleading: CPython will make a decent attempt (via the module cleanup mechanism: http://www.python.org/doc/essays/cleanup.html ), but any files that are not closed by that process will be handled by the OS. CPython is not designed to run on an OS that doesn't reclaim memory and other re- sources upon program exit. From noway at nospam.com Tue Nov 1 12:45:11 2005 From: noway at nospam.com (CppNewB) Date: Tue, 01 Nov 2005 17:45:11 GMT Subject: Python's website does a great disservice to the language Message-ID: I was trying to advocate using Python for an upcoming prototype, so my boss went out to take a look at the documentation and try and get a feel for what the language is all about. First comment; "I hope the language is designed better than the site." The site is readable, but is amateurish. If I had an ounce of design skills in me, I would take a stab at it. Maybe we could round up a couple of designers to donate some time? Maybe we could build a basic CMS on top of Django or TurboGears (displaying Python's capability as a web development stack)? From steve at REMOVETHIScyber.com.au Wed Nov 23 17:31:25 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 24 Nov 2005 09:31:25 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> Message-ID: On Wed, 23 Nov 2005 15:34:49 +0000, Ed Jensen wrote: > Try this little experiment: Walk up, at random, to 100 people on the > street. Show them a software CD-ROM -- a game, a word processor, > whatever. Tell them it's free. Then ask them what they think that > means. > > 99 times out of 100, they'll think it means it's free-as-in-beer. Oh no!!! Are you telling me that people's first thought when you hand them a physical object and say it is free is to think that you mean free of cost??? Say it isn't so!!! > They *won't* think it means they'll get the source code, and the right > to tweak that source code. They *won't* think it means they have the > right to infinitely redistribute it. So what? You just tell them, and then they *will* think that they have the right to infinitely redistribute it, because they've just be told. If you tell them "This FREE software that I am giving you for FREE, you are FREE to make copies for all your friends for FREE" and they still don't get it, then they are an idiot. > At best, the GPL/FSF engaged in what I consider false advertising. > Free Software (note the capital 'F' and 'S') *isn't*, by the most > widely understood and assumed definition of "free". Really? So when I take my GPLed software, and legally install it on 100 PCs without paying one single cent for licence fees, it isn't free of cost? You a living in a strange and mysterious world, where things that cost nothing aren't free. Of course, any particular vendor is FREE (there's that word again) to try to charge me as much money as they like for the FREE software that I can get for FREE from another vendor. If they can convince me that they are offering enough added value to justify paying money for something I can get for FREE from one of their competitors, I may even pay for that added value. > They should have > called it "liberated software" or "share and share alike software" or > "free as in herpes" software. As in Open Source Software perhaps? > Free Software is certainly not free > software, since it comes heavily encumbered by licensing issues. Firstly, you contradict yourself. You argue that "free as in speech" doesn't count for squat because 99 in 100 people think *first* of "free as in beer". Fine -- you've laid the ground rules, you live by them. If that's the only definition of "free" that you'll accept, then stick with it: "heavily encumbered by licensing issues" is irrelevant. What counts is cost. Then by this restrictive definition of "free", Free and Open Source Software *is* free, because I am FREE to redistribute it for FREE. Secondly, you are either guilty of rhetorical exaggeration, or you are exceedingly ignorant of what the various licenses out in the real world *actually* say. To describe the GPL and similar as "heavily encumbered" is, quite frankly, idiotic. Have you ever bothered to read proprietary software licences? They are the heavily encumbered licences, with restrictions on when, where and how you can you the software, how many copies you can make, whether and how many backup copies you can create, whether or not you can transfer the licence to somebody else, and whatever other restrictions they think they can get away with. Microsoft, for example, frequently restricts your legal ability to publish benchmarks for their software. No, software under the GPL is not in the public domain. I make no apologies for that. GPLed software is copyrighted, and supplied under a licence where the software users are FREE (there's the word that you think people don't understand) to use the software any way they like, FREE to redistribute it, FREE to publish benchmarks, FREE to copy it, FREE to create derivative works, and FREE to give it away for FREE, so long as the user lives by a simple rule: whatever freedoms the GPL licence gives you, you may not take away from the people you distribute the software too. > The success of things like Python -- which is not GPL licensed, afaik > -- pretty much proves the GPL is unnecessary for the success of free > projects. The GPL is just some bizarre social agenda being pushed by > some crazies, and a lot of programmers (who are not lawyers) fell for > the hippie nonsense. Ah, I see -- trolling. All that commie pinko nonsense about Free Speech by the Founding Fathers, all just hippie crap, right? > So, you may like to bandy around the mildly offensive "free as in > freeloading", but then that gives me the right to refer to GPL'd > software as "free as in pushing my personal social agenda". Of course you are FREE to do so, and I won't even charge you. That doesn't make what you say meaningful. Is the Python licence not "pushing my personal social agenda" too? What about proprietary licences that prohibit making backup copies? Doesn't that push a social agenda too, an agenda to make it expected that every time your software needs to be reinstalled you have to go out a buy a new one? -- Steven. From bkhl at stp.lingfil.uu.se Tue Nov 1 12:48:18 2005 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Tue, 01 Nov 2005 18:48:18 +0100 Subject: Flat file, Python accessible database? References: Message-ID: <877jbsxnrx.fsf@lucien.dreaming> Karlo Lozovina <_karlo_ at _mosor.net_> writes: > I've been Googling around for _small_, flat file (no server > processes), SQL-like database which can be easily access from Python. If you need it to be SQL-like, SQLite seems to be the right thing. It's not clear to me what you mean by "flat" file here, but if you mean it should be human readable, maybe the csv module is the thing. http://docs.python.org/lib/module-csv.html -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From aleax at mail.comcast.net Tue Nov 1 00:05:04 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 31 Oct 2005 21:05:04 -0800 Subject: Scanning a file References: <1130497567.764104.125110@g44g2000cwa.googlegroups.com> <7xek65nal0.fsf@ruckus.brouhaha.com> <1130505731.850947.68690@o13g2000cwo.googlegroups.com> <87ek65kbw5.fsf@lucien.dreaming> <1h5760l.1e2eatkurdeo7N%aleaxit@yahoo.com> <3siakvFohl3aU1@individual.net> <1h57cij.16dkc141lds4s4N%aleaxit@yahoo.com> <1h597yx.wjk2a71spyjhyN%aleaxit@yahoo.com> <3smn47FoolfbU1@individual.net> <3snboiFolt77U1@individual.net> Message-ID: <1h5be7i.1k1k09i1c543fcN%aleax@mail.comcast.net> Steve Holden wrote: ... > > The runtime knows it is doing it. Please allow the runtime to tell me > > what it knows it is doing. Thanks. > > In point oif fact I don't believe the runtime does any such thing > (though I must admit I haven't checked the source, so you may prove me > wrong). > > As far as I know, Python simply relies on the opreating system to close > files left open at the end of the program. Nope, see : """ static void file_dealloc(PyFileObject *f) { int sts = 0; if (f->weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *) f); if (f->f_fp != NULL && f->f_close != NULL) { Py_BEGIN_ALLOW_THREADS sts = (*f->f_close)(f->f_fp); """ etc. Exactly how the OP wants to "allow the runtime to tell [him] what it knows it is doing", that is not equivalent to reading the freely available sources of that runtime, is totally opaque to me, though. "The runtime" (implementation of built-in object type `file`) could be doing or not doing a bazillion things (in its ..._dealloc function as well as many other functions), up to and including emailing the OP's cousin if it detects the OP is up later than his or her bedtime -- the language specs neither mandate nor forbid such behavior. How, exactly, does the OP believe the language specs should "allow" (presumably, REQUIRE) ``the runtime'' to communicate the sum total of all that it's doing or not doing (beyond whatever the language specs themselves may require or forbid it to do) on any particular occasion...?! Alex From jaco at neottia.net Sun Nov 20 09:50:10 2005 From: jaco at neottia.net (Eric Jacoboni) Date: Sun, 20 Nov 2005 15:50:10 +0100 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> <86hda8hsft.fsf@bhuda.mired.org> Message-ID: Mike Meyer writes: > I've seen at least one language (forget which one) that allowed such > separators, but only for groups of three. So 123_456 would be valid, > but 9_1 would be a syntax error. Ada allows underscores in numeric literals since 1983, without enforcing any grouping. The Ruby language allows also this notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the same for real numbers...). When you have the habit to represent literals like that, all other big numeric literals or workarounds to create grouping seem cryptic. -- Eric Jacoboni, ne il y a 1435938104 secondes From fredrik at pythonware.com Mon Nov 14 14:49:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Nov 2005 20:49:34 +0100 Subject: more newbie help needed References: <20051114192046.64486.qmail@web35901.mail.mud.yahoo.com> Message-ID: Steve Holden wrote: > Note, however, that there are more pythonic ways to perform this task. > You might try: > > for index in range(len(fruit)): > letter = fruit[-index-1] > print letter > > as one example. I'm sure other readers will have their own ways to do > this, many of them more elegant. looks like you've missed some recent additions: for char in reversed(fruit): print char From chandu at trillian.us Mon Nov 7 18:27:06 2005 From: chandu at trillian.us (Chandu) Date: 7 Nov 2005 15:27:06 -0800 Subject: struct.calcsize problem Message-ID: <1131406026.908312.13530@g44g2000cwa.googlegroups.com> In using the following struct format I get the size as 593. The same C struct is 590 if packed on byte boundary and 596 when using pragma pack(4). I am using pack(4) and added 3 spares at the end to get by. hdrFormat = '16s 32s 32s B 8s H 8s H 4s H H 20s 64s 64s 64s 32s 32s 64s L L B B B B B 64s 64s' Any ideas on what I am doing wrong? From deets at nospam.web.de Sat Nov 5 07:43:49 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 05 Nov 2005 13:43:49 +0100 Subject: control webbrowser remotely? In-Reply-To: <51cnm1d4bmf51cmqf1ig641sub4qninj2g@4ax.com> References: <51cnm1d4bmf51cmqf1ig641sub4qninj2g@4ax.com> Message-ID: <3t3no5Fqth4kU1@uni-berlin.de> Martin Bless wrote: > Web browsers like Firefox have really cool abilities nowadays. Objects > in the current document can be addressed and manipulated by > Javascript. Not very comfortable and not easy to debug. > > Q: Is there a way to reach objects in the document from Python? > That would be cool! > > Like for instance it's possible to control Excel remotely on Windows. > > Anybody knows something? Its called automation and available in windows for ages. Its implemented via the COM component object model, and this can be used with Mark Hammond's win32 extensions for Python. However, the Firefox object model (based on XCOM I believe) is a different beast - might be able to get a grip on it, but its firefox own thing then. And I'm not sure if it is possible to embed python instead of JScript. Regards, Diez From mardy at users.sourceforge.net Mon Nov 21 18:50:40 2005 From: mardy at users.sourceforge.net (Mardy) Date: Mon, 21 Nov 2005 23:50:40 GMT Subject: the name of a module in which an instance is created? References: Message-ID: Hi Steven, Le die Mon, 21 Nov 2005 11:37:37 -0700, Steven Bethard ha scribite: [...] > In the basic situation, where the instance is created in the same module > as the class, I can figure out 'mod' and 'name' like:: > > cls = type(self) > name = cls.__module__ > mod = __import__(cls.__module__) I'm not sure I got your problem correctly, however see if this helps: $ cat > test.py class myclass: name = __module__ ^D $ python Python 2.3.5 (#2, Jun 19 2005, 13:28:00) [GCC 3.3.6 (Debian 1:3.3.6-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import test >>> a = test.myclass() >>> a.name 'test' This works, as we define "name" to be a class attribute. Is this useful to you? -- Saluti, Mardy http://interlingua.altervista.org From qwweeeit at yahoo.it Thu Nov 3 13:00:07 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 3 Nov 2005 10:00:07 -0800 Subject: Web automation (was: Pressing a Webpage Button) Message-ID: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> Hi all, Elliot Temple on the 1 June wrote: > How do I make Python press a button on a webpage? I looked at > urllib, but I only see how to open a URL with that. I searched > google but no luck. > For example, google has a button how would i make a script to press that button? I have a similar target: web automation, which needs not only to press web buttons but also fill up input fields (like in your case the search field of Google). On the suggestion of gmi... at gmail.com, I tried twill (http://www.idyll.org/~t/www-tools/twill.html). I think it can be the solution: I already applied it for reading data from an asp file (http://groups.google.it/group/comp.lang.python/browse_frm/thread/23b50b2c5f2ef377/2e0a593e08d28baf?q=qwweeeit&rnum=2#2e0a593e08d28baf) I try to solve your problem using the interactive mode (but twill can also be called as a module). Set twill in interactive mode: twill-sh - load Google webpage: go www.google.it (I'm Italian!) - show the page with the command 'show' - Get the page forms: showforms ## __Name______ __Type___ __ID________ __Value__________________ hl hidden (None) it ie hidden (None) ISO-8859-1 q text (None) meta radio all [''] of ['', 'lr=lang_it', 'cr=count ... 1 btnG submit (None) Cerca con Google 2 btnI submit (None) Mi sento fortunato current page: http://www.google.it The input field is q (Type:text), while there are two buttons (Type: submit) and a radio button meta (Type: radio). - fill values: fv 0 q twill (being "twill" the search string") - press the search button: fv 1 btnG "Cerca con Google" submit twill answers with the query to Google: http://www.google.it/search?hl=it&ie=ISO-8859-1&q=twill&btnG=Cerca+con+Google&meta= - save the search result on a file: save_html /home/qwweeeit/searching_twill.html Here they are the 1st 10 hits of the search! Don't ask me to continue! Perhaps asking to the author of twill (C. Titus Brown)... With such a method you can bypass the Google's restrictions, because you are using the browser (only building automatically the query). And this answers to the right observation of Grant Edwards: > Ah, never mind. That doesn't work. Google somehow detects > you're not sending the query from a browser and bonks you. Bye. From steve at REMOVETHIScyber.com.au Fri Nov 4 23:16:06 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 15:16:06 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: On Fri, 04 Nov 2005 12:10:11 +0000, Antoon Pardon wrote: >> There are good usage cases for the current inheritance behaviour. I asked >> before what usage case or cases you have for your desired behaviour, and >> you haven't answered. Perhaps you missed the question? Perhaps you haven't >> had a chance to reply yet? Or perhaps you have no usage case for the >> behaviour you want. > > There are good use cases for a lot of things python doesn't provide. > There are good use cases for writable closures, but python doesn't > provide it, shrug, I can live with that. Use cases is a red herring > here. Is that a round-about way of saying that you really have no idea of whether, how or when your proposed behaviour would be useful? Personally, I think that when you are proposing a major change to a language that would break the way inheritance works, there should be more benefits to the new way than the old way. >> Some things are a matter of taste: should CPython prefer <> or != for not >> equal? Some things are a matter of objective fact: should CPython use a >> byte-code compiler and virtual machine, or a 1970s style interpreter that >> interprets the source code directly? >> >> The behaviour you are calling "insane" is partly a matter of taste, but it >> is mostly a matter of objective fact. I believe that the standard >> model for inheritance that you call insane is rational because it is >> useful in far more potential and actual pieces of code than the behaviour >> you prefer -- and the designers of (almost?) all OO languages seem to >> agree with me. > > I didn't call the model for inheritance insane. Antoon, I've been pedanted at by experts, and you ain't one. The behaviour which you repeatedly described as not sane implements the model for inheritance. The fact that you never explicitly said "the standard OO model of inheritance" cuts no ice with me, not when you've written multiple posts saying that the behaviour of that standard inheritance model is not sane. >> The standard behaviour makes it easy for code to do the right thing in >> more cases, without the developer taking any special steps, and in the >> few cases where it doesn't do the right thing (e.g. when the behaviour >> you want is for all instances to share state) it is easy to work >> around. By contrast, the behaviour you want seems to be of very limited >> usefulness, and it makes it difficult to do the expected thing in >> almost all cases, and work-arounds are complex and easy to get wrong. > > Please don't make this about what I *want*. I don't want anything. I > just noted that one and the same reference can be processed multiple > times by the python machinery, resulting in that same reference > referencing differnt variables at the same time and stated that that was > unsane behaviour. "Unsane" now? Heaven forbid that I should criticise people for inventing new words, but how precisely is unsane different from insane? In standard English, something which is not sane is insane. >> The standard behaviour makes it easy for objects to inherit state, and >> easy for them to over-ride defaults. The behaviour(s) you and Graham >> want have awkward side-effects: your proposed behaviour would mean that >> class attributes would mask instance attributes, or vice versa, meaning >> that the programmer would have to jump through hoops to get common >> types of behaviour like inheriting state. > > You don't know what I want. You only know that I have my criticism of > particular behaviour. You seem to have your idea about what the > alternative would be like, and project that to what I would want. Well now is a good time for you to stop being so coy and tell us what you want. You don't like the current behaviour. So what is your alternative? I've given you some suggestions for alternative behaviour. You've refused to say which one you prefer, or suggest your own. If you're just trolling, you've done a great job of it because you fooled me well and good. But if you are serious in your criticism about the behaviour, then stop mucking about and tell us what the behaviour should be. Otherwise your criticism isn't going to have any practical effect on the language at all. >> That's an objective claim: please explain what makes your behaviour >> more rational than the standard behaviour. Is your behaviour more >> useful? Does it make code easier to write? Does it result in more >> compact code? What usage cases? > > What my behaviour? I don't need to specify alternative behaviour in > order to judge specific behaviour. If you are serious about wanting the behaviour changed, and not just whining, then somebody has to come up with an alternative behaviour that is better. If not you, then who? Most of the folks who have commented on this thread seem to like the existing behaviour. -- Steven. From venkatasubramanian at gmail.com Thu Nov 3 08:18:22 2005 From: venkatasubramanian at gmail.com (venk) Date: 3 Nov 2005 05:18:22 -0800 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: <1131023902.277600.189980@g49g2000cwa.googlegroups.com> You see, The seen behavior is due to the result of python's name binding,scoping scheme. Let me give you an example, class A: i=0 def t(self): print self.i self.i=4 then a=A() a.i is 0 a.t() then, A.i is 0 a.i is 4 In the function, it first searches for i in its local scope, on not finding it, accesses the class object's i. then the next line, is an assignment, which binds (creates a new variable) in the instance's scope. you can use the buit-in id function to verify it. the same thing happens in the case of b.a = b.a + 2 .... search for b.a not found, read the value from the enclosing scope (of the class object).... then assign b.a to the local scope, with the value 3. But, I think your question about the sanity of the behaviour should be analysed sincerely.... if, k=0 def f(): print k k=k+1 raises UnboundLocalError, then how is it accepted in the former case? hmmm.... maybe, my arguments are hapazard.... but, i'll get to know when i'm flamed ;) From simon.brunning at gmail.com Tue Nov 15 06:05:49 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 15 Nov 2005 11:05:49 +0000 Subject: compare list In-Reply-To: <1d987df30511150258j7848d3d5o61905f5ac935a6b0@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <1d987df30511142330t39b137fdpdc9eee56e73d6e1f@mail.gmail.com> <4379AA95.80806@cc.umanitoba.ca> <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> <8c7f10c60511150227v297140e1n@mail.gmail.com> <1d987df30511150258j7848d3d5o61905f5ac935a6b0@mail.gmail.com> Message-ID: <8c7f10c60511150305p29c7ab48u@mail.gmail.com> On 15/11/05, Shi Mu wrote: > Yes, i am using python 2.3, > I have used from sets import * > but still report the same error: > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > NameError: name 'set' is not defined I said analogous, not identical. try (untested): from sets import Set as set -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From jmeile at hotmail.com Mon Nov 7 16:49:24 2005 From: jmeile at hotmail.com (Josef Meile) Date: Mon, 07 Nov 2005 22:49:24 +0100 Subject: useradd command in Zope In-Reply-To: <436FCB7D.1030803@hotmail.com> References: <27E78F03553BA0493F67A83E@dhcp1.sb.haufe.de> <436A09D6.6030503@wildenhain.de> <1131349220.30174.60.camel@Andrea.peacock.de> <436F1EB6.4040905@wildenhain.de> <436FCB7D.1030803@hotmail.com> Message-ID: <436FCBE4.9000402@hotmail.com> Sorry, I replied to the Wrong list :-( Josef Meile wrote: >> su zope (or whoever your zope runs) >> ./yourmethod.py someuser somepass >> >> You will see it fail (apart from the fact you need >> the #!/path/to/python.bin and set the execution bit >> with chmod a+x before you try) >> >> >> > i tried using another user outside of zope ..... >> working very well(adding user to system).... > > Perhaps the other user is either root or it belongs to the root's > groups. > >> owner of external method is root and set_user_id bit is set..... >> but problem is when i run attached app it is not adding user .... > > set_user_id only works with C binary files. So, here you have to use > sudo. > > Regards, > Josef > From andrea_gavana at tin.it Wed Nov 2 19:01:44 2005 From: andrea_gavana at tin.it (Andrea Gavana) Date: Thu, 3 Nov 2005 01:01:44 +0100 Subject: wxPython: updating style of StaticText from event generated by button References: <1130886746.328723.109570@f14g2000cwb.googlegroups.com> <4367f8fb$0$24643$4fafbaef@reader3.news.tin.it> <1130888759.884816.247730@o13g2000cwo.googlegroups.com> Message-ID: <43680299$0$24641$4fafbaef@reader3.news.tin.it> Hello Kees, > Thanks :), I'll give both of your hints a try. What I basically want to > do is have something like an "old style" button in win xp that's either > "up" or "down", since I couldn't find a more straightforward method I > thought taking a text widget and adjusting the border at mouse click > would be the best alternative no? I would suggest you to take a look to the wxPython "custom" buttons; you can find them in the demo, under "Custom Controls" ==> "GenericButtons". There you will find "old style" buttons, that can be simple buttons or toggle buttons (with "up" and "down" states). I have XP, and they look like "old style" buttons. Moreover (just to promote my web site and my widgets, freely available to all wxPython users ;-)))) ), if you would like to use "non-rectangular" buttons-toggle buttons, you could take a look at: http://xoomer.virgilio.it/infinity77/eng/freeware.html#shapedbutton > One question then, what's the use of having a method like > SetWindowStyle() if it doesn't really do anything at runtime? Is it > indeed just intended for the few widgets that do support it? This is more a wxWidgets question that a wxPython one. However, quoting the wxWidgets manual: wxWindow::SetWindowStyleFlag virtual void SetWindowStyleFlag(long style) Sets the style of the window. Please note that some styles cannot be changed after the window creation and that Refresh() might be called after changing the others for the change to take place immediately. SetWindowStyleFlag is the same as SetWindowStyle. I don't have an answer to your question, but maybe some wxWidgets expert can give you some more hints (I don't use wxWidgets, only wxPython). HTH. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77 From jepler at unpythonic.net Mon Nov 7 11:37:19 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 7 Nov 2005 10:37:19 -0600 Subject: Tkinter and X11 In-Reply-To: References: Message-ID: <20051107163719.GB4532@unpythonic.net> There should be no problem with this. After all, even the "greeter" is just an X application. Depending on which login manager you use (xdm/kdm/gdm/whatever) the details of getting your Tkinter app to actually be run will vary, though. In gdm, it looks like adding it to the file /etc/X11/gdm/Init/default may be the ticket. It is probably best to run app.tk.call("rename", "send", "") in your program, for the reasons outlined in the send(n) manpage: SECURITY The send command is potentially a serious security loophole. On Unix, any application that can connect to your X server can send scripts to your applications. These incoming scripts can use Tcl to read and write your files and invoke subprocesses under your name. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jason at tishler.net Mon Nov 21 07:42:41 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 21 Nov 2005 07:42:41 -0500 Subject: tkinter and cygwin In-Reply-To: References: Message-ID: <20051121124241.GA380@tishler.net> John, On Mon, Nov 21, 2005 at 08:18:09PM +0900, John wrote: > I've recently started learning python programming and have been > experimenting with a few basic GUI programs. My work system is > cygwin/Windows XP. I use X-windows in cygwin but when I run my > python/tkinter program from an x-win terminal , a normal XP window is > opened up. For better or worse, Cygwin's tcltk package is essentially a Win32 build. So, the behavior you are observing is expected although not necessarily desired. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From jeremy at emperorlinux.com Tue Nov 29 16:08:13 2005 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Tue, 29 Nov 2005 16:08:13 -0500 Subject: ncurses' Dark Devilry In-Reply-To: <*firstname*nlsnews-8F0080.15501829112005@news.verizon.net> References: <*firstname*nlsnews-8F0080.15501829112005@news.verizon.net> Message-ID: <1133298493.3871.53.camel@localhost.localdomain> On Tue, 2005-11-29 at 20:50 +0000, Tony Nelson wrote: > In article , > Jeremy Moles wrote: > > > I'm working on a project using ncurses w/ Python. As an aside, I > > implemented addchstr in the cursesmodule.c file in Python SVN, if anyone > > wants me to try and get that made permanent. > > > > AT ANY RATE... > > > > I was wondering--and this is more a general curses question rather than > > a Python one, but I know there are some old-timers here who have made > > curses obey before--is there a way to "repaint" a portion of screen > > without stealing the "cursor?" That is: > > > > I have a focus "wheel" of sorts that allows the user to do input on > > various wigets and windows and whatnot. However, if I want to quickly > > call addstr somewhere else in the application I have to: > > > > 1. Store the YX coords of the cursor currently > > 2. Use the cursor in the "current" action > > 3. Restore the old cursor location > > > > I know there are ways around this as I have seen curses apps that, for > > example, have a clock that updates every second without stealing > > "focus." > > > > I tried implementing/using addchstr (mentioned above) to no success. > > > > Any ideas? Is this just the plain wrong place to ask this? :) > > I've only tried to read the Python Library Curses docs, but I thought > that the Window object method addstr() would do what you want. Perhaps I should have been more specific. :) addstr (or any of it's brothers, even those bound to a subwin instance) write values to an internal buffer/object that then gets flipped (refreshed()) onto the physical screen. However. All of the routines I can find in the ncurses library want to take control of the "cursor" object. That is: they either want to advance it's position (addstr) or not (addchstr), but they both certainly grab "control" of it; at least, visually. Basically what I'm looking for is a way to refresh a portion of a curses-controlled "window" without affecting the current location of the cursor or having to manually move it and move it back. From frank at chagford.com Wed Nov 30 01:03:46 2005 From: frank at chagford.com (Frank Millman) Date: 29 Nov 2005 22:03:46 -0800 Subject: sax.make_parser() segfaults In-Reply-To: <1133278824.029426.142640@z14g2000cwz.googlegroups.com> References: <1133278824.029426.142640@z14g2000cwz.googlegroups.com> Message-ID: <1133330626.904373.176390@g44g2000cwa.googlegroups.com> Frank Millman wrote: > Hi all > > I am using Python 2.4.1. I have machines running FC4, RH9, and MSW > Server 2003 for testing. > > If I call sax.make_parser() from the interpreter or from a stand-alone > program, it works fine on all machines, but in the following setup it > works correctly on MSW, but segfaults on both FC4 and RH9. > > The setup is a client program running wxPython as a gui, and Twisted as > a means of connecting to a server. Progress report - I have narrowed it down to wxPython. I wrote small stand-alone programs, one using Twisted, one using wxPython. Twisted works fine, wxPython segfaults. If no-one here can help, I will try asking on the wxPython mailing list. Frank From http Mon Nov 28 22:53:49 2005 From: http (Paul Rubin) Date: 28 Nov 2005 19:53:49 -0800 Subject: Instantiating classes which are derived from built-in types. References: <1h6r3kz.1w1dj8fyl4ey7N%aleax@mail.comcast.net> Message-ID: <7x1x10rtwy.fsf@ruckus.brouhaha.com> aleax at mail.comcast.net (Alex Martelli) writes: > A is oldstyle -- a wart existing for backwards compatibility. I think it's time for "from __future__ import newclasses" since I hate having to type "class A(object):" instead of "class A:" all over the place. From zanesdad at bellsouth.net Tue Nov 22 11:19:07 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 22 Nov 2005 11:19:07 -0500 Subject: help with using temporary files In-Reply-To: <1132675417.303025.105490@f14g2000cwb.googlegroups.com> References: <1132675417.303025.105490@f14g2000cwb.googlegroups.com> Message-ID: <438344FB.3090601@bellsouth.net> Gerard Flanagan wrote: >Hello > > I'm sure its basic but I'm confused about the error I get with the >following code. Any help on basic tempfile usage? > > >ActivePython 2.4.1 Build 247 (ActiveState Corp.) based on >Python 2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)] >on win32 >Type "help", "copyright", "credits" or "license" for more information. > > >>>>from tempfile import NamedTemporaryFile >>>> >>>>tmp = NamedTemporaryFile() >>>>tmp.write("Hello") >>>>tmp.close() >>>> >>>>print tmp.name >>>> >>>> >c:\docume~1\gerard\locals~1\temp\tmpxqn4yl > > >>>>f = open(tmp.name) >>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? >IOError: [Errno 2] No such file or directory: >'c:\\docume~1\\gerard\\locals~1\\temp\\tmpxqn4yl' > > >Thanks > >Gerard > > > It gets created: In [24]: import tempfile In [25]: t = tempfile.NamedTemporaryFile() In [26]: t.name Out[26]: '/tmp/tmp9bmhap' In [27]: ls -l /tmp/tmp* -rw------- 1 jmjones jmjones 0 Nov 22 11:15 /tmp/tmp9bmhap In [28]: t.write("123") In [29]: t.flush() In [30]: ls -l /tmp/tmp* -rw------- 1 jmjones jmjones 3 Nov 22 11:15 /tmp/tmp9bmhap In [31]: t.close() In [32]: ls -l /tmp/tmp* ls: /tmp/tmp*: No such file or directory From the docstring, it gets automatically deleted on close: def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", prefix=template, dir=None): """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to os.fdopen (default "w+b"). 'bufsize' -- the buffer size argument to os.fdopen (default -1). The file is created as mkstemp() would do it. Returns an object with a file-like interface; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed. """ HTH, - jmj From aleax at mail.comcast.net Wed Nov 9 22:25:27 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 9 Nov 2005 19:25:27 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> <1131426966.939823.231830@z14g2000cwz.googlegroups.com> <1h5of5f.1f7in1b1e1fa4wN%aleax@mail.comcast.net> <1131517112.247477.35030@g14g2000cwa.googlegroups.com> Message-ID: <1h5rxho.nxmo0z15zne5jN%aleax@mail.comcast.net> wrote: ... > I made a successful installer for Windows using Mingw32 and Python 2.4. Great, thanks. > I needed to edit setup.py to list gmp as a required library. > > if sys.version.find('MSC')==-1: > gmpy_ext = Extension('gmpy', sources=['src/gmpy.c'], > # library_dirs=['/usr/local/lib'], > libraries=['gmp']) > else: > gmpy_ext = Extension('gmpy', sources=['src/gmpy.c'], > include_dirs=['./src'], > libraries=['gmp']) # I added libraries! > > Will you be updating the information in setup.py file? Done, in the current CVS version. > Tomorrow, I'll recreate my build process on another computer. I am > willing to create Windows installers. Wonderful! > Which versions of Python do you want to support? I have tested gmpy with 2.3 and 2.4 on Mac, and those two and also 2.2 on Linux. I think supporting 2.2 with a Windows download is probably unneeded, but 2.4 is a must and I suspect 2.3 would be nice... > Do you want versions that include GMP tailored for specific processors? My gut reaction here is that people with special processors, Windows, and demanding performance needs should probably get their own development environments and build GMP and gmpy accordingly. Any opinions from the public on this one...? > With GMP 4.1.4 compiled for pentium3, and running on a 1.8Ghz Pentium > M, I'm able to calculate the decimal form of 2^25964951 (the 43rd > Mersenne prime) in 10 seconds. The prior gmpy release takes just over > 14 seconds. Without gmpy, Python takes 25.4 seconds. On an Athlon > MP2800+ (2.133Ghz) with GMP compiled for that processor, I can do it in > 6.6 seconds using gmpy and 22.4 seconds without gmpy. I'm working with > blocks of 1000 digits and using a combination of Toom-Cook and > Nussbaumer convolution to perform the multiplies and squares. Sounds quite decent -- about a 2.5 to 3+ times speedup wrt Python, and some speedup wrt gmpy 1.0 (all GMP's merit -- I didn't address performance aspects at all in this delta). Just out of curiosity: what performance do you get on the Athlon with a pentium3-compiled GMP? > I did very that the tp_compare errors are fixed. I removed the warnings > filter in my code and the warning did occur with the old gmpy but did > not occur with my version. Excellent. Sounds like an "all systems go"...!-) Thanks, Alex From jepler at unpythonic.net Fri Nov 4 14:42:01 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Fri, 4 Nov 2005 13:42:01 -0600 Subject: fcntl.flock() not working when called from a function In-Reply-To: <1131132819.081353.213180@z14g2000cwz.googlegroups.com> References: <1131132819.081353.213180@z14g2000cwz.googlegroups.com> Message-ID: <20051104194200.GA12778@unpythonic.net> The file you open() may be closed as soon as it is no longer possible to refer to it. So in the first case, because the top-level variable 'f' continues to refer to the opened file, the file may not be closed. In the second case, no variable refers to the opened file after lock() returns, so Python is free to close the file at any time. In fact, Python happens to close the function exactly when lock() returs. If you want an open file descriptor that is not automatically closed, use os.open(). Or, store the file descriptor somewhere so you can later close() or unlock it at an appropriate time. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From spam at this.fu Wed Nov 23 16:39:45 2005 From: spam at this.fu (dado) Date: Wed, 23 Nov 2005 22:39:45 +0100 Subject: moving mouse? In-Reply-To: References: Message-ID: dado wrote: > I'm implementing a "self-tutorial" into my app, > and wondering if there's a way of moving a mouse > cursor on command? probably using sys,os modules? I also figured this would be useful for making 'remote desktop' kinda thing... From roy at panix.com Tue Nov 29 19:01:13 2005 From: roy at panix.com (Roy Smith) Date: Tue, 29 Nov 2005 19:01:13 -0500 Subject: Looking for good beginner's tutorial References: <438ce39e$1_1@newspeer2.tds.net> Message-ID: In article <438ce39e$1_1 at newspeer2.tds.net>, Kent Johnson wrote: > Roy Smith wrote: > > My wife wants to learn Python. Can anybody suggest a good tutorial > > for her to read? She's a PhD molecular biologist who is a pretty > > advanced Unix user. She mucks about with Perl scripts doing things > > like text processing and even some simple CGI scripts, but has no > > formal programming training. > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > Kent That looks like just what I need, thanks! I even see two tutorials aimed at bioinformatics people, which hit the spot perfectly. From bonono at gmail.com Tue Nov 22 19:00:24 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 16:00:24 -0800 Subject: about sort and dictionary In-Reply-To: <86y83g1bww.fsf@bhuda.mired.org> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> Message-ID: <1132704024.711460.194310@f14g2000cwb.googlegroups.com> Mike Meyer wrote: > rurpy at yahoo.com writes: > > I think this is just another (admittedly minor) case of Python's > > designers using Python to enforce some idea of programming > > style purity. > > You say that as if it were a bad thing. > I would say "interesting" thing. As it seems that quite some people don't see the language as the creator or wants them to see it. From pianomaestro at gmail.com Tue Nov 22 03:52:39 2005 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: 22 Nov 2005 00:52:39 -0800 Subject: linking one extension module to another (Mac OSX) In-Reply-To: <4382b145$0$28799$9b622d9e@news.freenet.de> References: <1132631865.024503.302080@g43g2000cwa.googlegroups.com> <4382b145$0$28799$9b622d9e@news.freenet.de> Message-ID: <1132649559.788680.20710@o13g2000cwo.googlegroups.com> Martin v. L?wis wrote: > Simon Burton wrote: > > I'm having some trouble linking one extension module to another because > > the linker expects a "lib" prefix and my python modules cannot have > > this prefix. > > This is a Good Thing (tm) :-) Don't link extension modules to each > other; this is really asking for trouble. Instead, come up with a > function pointer API in one module, put that into a CObject, and > access the CObject through import statements. > > Alternatively, make both extension modules link to the same > backend library. > > Regards, > Martin I have C Extension classes distributed across several modules with non-trivial interdependancies. I guess you are saying I should have these in backend libraries and then put the module specific functions in the module itself. It's going to be tricky because I am using distutils and pyrex to do all this. Maybe Greg (Ewing) has some other ideas. Thanks for the warning. Simon. From scott.daniels at acm.org Wed Nov 30 11:05:50 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 30 Nov 2005 08:05:50 -0800 Subject: Debugging of Python code in embedded interpreter In-Reply-To: <438d7816$0$27013$91cee783@newsreader02.highway.telekom.at> References: <438d7816$0$27013$91cee783@newsreader02.highway.telekom.at> Message-ID: <438dcb17@nntp0.pdx.net> Thomas Korimort wrote: > Hi! > > I have embedded a Python interpreter into a C++ framework. When running > some Python code in the interpreter, how can i get a traceback with line > number file..., when an exception occurs? > > Greetings, Thomas Korimort. Google for "python traceback", there seems to be interesting output. --Scott David Daniels scott.daniels at acm.org From avnit7 at gmail.com Tue Nov 22 18:22:30 2005 From: avnit7 at gmail.com (avnit) Date: 22 Nov 2005 15:22:30 -0800 Subject: hex string to hex value In-Reply-To: References: Message-ID: <1132701750.841307.97890@g14g2000cwa.googlegroups.com> If you just want to convert a string to an integer, it would be: >>> int(n) in your case it would be: >>> m=66 >>> n=int(hex(m)) From bkhl at stp.lingfil.uu.se Mon Nov 14 16:55:51 2005 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Mon, 14 Nov 2005 22:55:51 +0100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> Message-ID: <87psp2ao7s.fsf@lucien.dreaming> Steven D'Aprano writes: > Why does the byte string "\x6f\x70\x65\x6e\x65\x64" have intrinsic > meaning when the int 0 doesn't? It certainly doesn't mean anything to > non-English speakers. > > If all you want is human readable byte strings, then just use them: > > class MyFile: > def open(self): > self.state = "opened" > def close(self): > self.state = "closed" So, I guess no one read my explanation of why this an issue about more than implementing enums (which is fairly trivial, as we have seen). -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From pierre.barbier at cirad.fr Sun Nov 13 11:03:47 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sun, 13 Nov 2005 17:03:47 +0100 Subject: Proposal for adding symbols within Python In-Reply-To: <87mzk8pnxc.fsf@lucien.dreaming> References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <87mzk8pnxc.fsf@lucien.dreaming> Message-ID: <437763c2$0$18813$636a55ce@news.free.fr> Bj?rn Lindstr?m a ?crit : > Ben Finney writes: > > >>I've yet to see a convincing argument against simply assigning values >>to names, then using those names. > > > The problem with that is that you can't pass around the names of objects > that are used for other things. Obviously they make enums unnecessary, > but only people damaged by non-dynamic languages could think that's the > main point. ;-) > > Being able to do that precludes the need for converting going back and > forth between strings and method names when you need to do things like > keeping a list of function names, even when you need to be able to > change what those function names point to. > > Python doesn't really need to introduce a new type to do this. It's > already there, as what we usually just call names. Probably this > discussion would benefit from talking about names rather than symbols, > as that seems to confuse some people. > > So, Python already has symbols. What we need is a way to refer to these > symbols explicitly. I would suggest to do it like in Lisp: > > quote(spam) > > Of course, this would preferably be implemented so that it doesn't just > work on simple names: > > quote(spam(eggs)) > > I syntactic sugar, like ' in Lisp, could be introduced later, but I > don't think that would be strictly necessary. > Well, if this already exists in Python's internals, then, it would be great just to expose them. Now, just being able to write : >>> quote(spam) quote(spam) requires a new syntax so that spam is not resolved *before* calling the quote method. Pierre From bonono at gmail.com Tue Nov 22 22:05:23 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 19:05:23 -0800 Subject: Converting a flat list to a list of tuples In-Reply-To: <4383da5d.510001563@news.oz.net> References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <438301ef$0$29180$8fcfb975@news.wanadoo.fr> <1132674151.370320.100130@g44g2000cwa.googlegroups.com> <4383897d.489297222@news.oz.net> <1132705945.406071.137590@z14g2000cwz.googlegroups.com> <4383da5d.510001563@news.oz.net> Message-ID: <1132715123.600280.226080@g14g2000cwa.googlegroups.com> Bengt Richter wrote: > On 22 Nov 2005 16:32:25 -0800, "bonono at gmail.com" wrote: > > > > >Bengt Richter wrote: > >> On 22 Nov 2005 07:42:31 -0800, "George Sakkis" wrote: > >> > >> >"Laurent Rahuel" wrote: > >> > > >> >> Hi, > >> >> > >> >> newList = zip(aList[::2], aList[1::2]) > >> >> newList > >> >> [('a', 1), ('b', 2), ('c', 3)] > >> >> > >> >> Regards, > >> >> > >> >> Laurent > >> > > >> >Or if aList can get very large and/or the conversion has to be > >> >performed many times: > >> > > >> >from itertools import islice > >> >newList = zip(islice(aList,0,None,2), islice(aList,1,None,2)) > >> > > >> Or, if you want to include fractional groups at the end > >> > >> >>> aList = ['a', 1, 'b', 2, 'c', 3] > >> >>> from itertools import groupby > >> >>> def grouper(n): > >> ... def git(): > >> ... while True: > >> ... for _ in xrange(n): yield 0 > >> ... for _ in xrange(n): yield 1 > >> ... git = git() > >> ... def grouper(_): return git.next() > >> ... return grouper > >> ... > >> >>> [tuple(g) for _, g in groupby(aList, grouper(2))] > >> [('a', 1), ('b', 2), ('c', 3)] > >> >>> [tuple(g) for _, g in groupby(aList, grouper(3))] > >> [('a', 1, 'b'), (2, 'c', 3)] > >> >>> [tuple(g) for _, g in groupby(aList, grouper(4))] > >> [('a', 1, 'b', 2), ('c', 3)] > >> > >Personally, I would like to see it as [('a',1,'b',2), ('c',3, > >None,None)], as a list of tuple of equal length is easier to be dealt > >with. > > > >i = iter(aList) > >zip(i,chain(i,repeat(None)), > >chain(i,repeat(None)),chain(i,repeat(None))) > > > Yes, but OTOH you might like to loop and catch ValueError when/if the last tuple > doesn't unpack properly. Then you don't have to worry about None vs a sentinel :-) > That to me is a matter of style. I in general prefer the no catch/except way of coding, the filter/map way(or the unix pipe way). Not that one is better than another. But I think your solution for this case is a bit hard to swallow. I would rather do it the more imperative way of : def split(s,n): a=[] c=0 for x in s: a.append(x) c+=1 if c%n == 0: yield a a=[] if a !=[]: yield a list(split(aList,4)) From steven.bethard at gmail.com Sat Nov 19 14:07:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 19 Nov 2005 12:07:09 -0700 Subject: textwrap.dedent() drops tabs - bug or feature? In-Reply-To: References: Message-ID: Peter Hansen wrote: > Steven Bethard wrote: > >> Note that even though the tabs are internal, they are still removed by >> textwrap.dedent(). The documentation[1] says: > > ... > >> So it looks to me like even if this is a "feature" it is undocumented. >> I'm planning on filing a bug report, but I wanted to check here first >> in case I'm just smoking something. > > While I wouldn't say it's obvious, I believe it is (indirectly?) > documented and deliberate. > > Search for this in the docs: > """ > expand_tabs > (default: True) If true, then all tab characters in text will be > expanded to spaces using the expandtabs() method of text. > """ Thanks for double-checking this for me. I looked at expand_tabs, and it's part of the definition of the TextWrapper class, which is not actually used by textwrap.dedent(). So I think the textwrap.dedent() expanding-of-tabs behavior is still basically undocumented. I looked at the source code, and the culprit is the first line of the function definition: lines = text.expandtabs().split('\n') I filed a bug_ report, but left the Category unassigned so that someone else can decide whether it's a doc bug or a code bug. STeVe .. _bug: http://python.org/sf/1361643 From steve at REMOVETHIScyber.com.au Sat Nov 5 18:23:44 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 06 Nov 2005 10:23:44 +1100 Subject: Using Which Version of Linux References: Message-ID: On Sat, 05 Nov 2005 04:26:38 -0600, blahman wrote: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. Solaris is not Linux, although both are like Unix. In my opinion, Debian is not newbie friendly. In my experience, Ubunto is HUGELY over rated. The installation was easy, the user experience was like being poked in the eye with a blunt stick. In my experience, Fedora is very newbie friendly, as well as being quite powerful for non-newbies. If you are in Australia or the USA, and start looking for commercial support, you'll have less grief if you use Fedora than most other distros. Although it has to be said, multimedia support is rather lacking due to licencing issues. (And, in fairness, multimedia support is still Linux's biggest weakness compared to OS X and Windows.) I hear that Mandrake and SuSE are very popular in Europe. If you don't mind really horrible German industrial industrial punk themed desktops, you could do a lot worse than play around with the Knoppix LiveCD. That would be the quickest way to get started: no installation necessary. -- Steven. From http Sun Nov 6 19:31:54 2005 From: http (Paul Rubin) Date: 06 Nov 2005 16:31:54 -0800 Subject: PyFLTK - an underrated gem for GUI projects References: Message-ID: <7xhdap47t1.fsf@ruckus.brouhaha.com> aum writes: > To me, wxPython is like a 12-cylinder Hummer, ... > Whereas PyFLTK feels more like an average suburban 4-door sedan Interesting. What would Tkinter be at that car dealership? What about PyGTK? From pieterswart at comcast.net Sat Nov 5 07:07:42 2005 From: pieterswart at comcast.net (Pieter Swart) Date: 5 Nov 2005 04:07:42 -0800 Subject: Using graphviz to visualize trace.py output, anybody? In-Reply-To: <1130874949.408641.288070@g49g2000cwa.googlegroups.com> References: <1130710534.618559.40680@g43g2000cwa.googlegroups.com> <1130874949.408641.288070@g49g2000cwa.googlegroups.com> Message-ID: <1131192462.345588.132950@g43g2000cwa.googlegroups.com> svenn.are at bjerkem.de wrote: > I was originally thinking of piping the output of trace.py into a text > file and then have python massage that text file into a dot file for > graphviz to visualize. > > Some formatting is possible with graphviz, but I would expect the graph > to be very dependent on how the program under test runs so I have > little idea what to expect. > To mangle graphs and their drawing via graphviz on multilple platforms, you might also want to try networkx combined with pygraphviz (available from networkx.lanl.gov) Cheers, Pieter From steve at REMOVETHIScyber.com.au Fri Nov 11 22:32:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 12 Nov 2005 14:32:26 +1100 Subject: odd behavior References: <1131737687.314760.265370@g44g2000cwa.googlegroups.com> Message-ID: On Fri, 11 Nov 2005 11:34:47 -0800, Greg wrote: > Forgive me, and be kind, as I am just a newby learning this language > out of M.L. Hetland's book. The following behavior of 2.4.1 seems very > strange >>>> x = ['aardvark', 'abalone', 'acme', 'add', 'aerate'] >>>> x.sort(key=len) >>>> x > ['add', 'acme', 'aerate', 'abalone', 'aardvark'] >>>> x.sort(reverse=True) >>>> x > ['aerate', 'add', 'acme', 'abalone', 'aardvark'] > The function called on line 4, at least to me, should work on x as it > was on line 3, not the previously existing x on line 1. What gives? Why do you think it isn't operating on x as it is? The second sort is sorting in reverse lexicographic order, which is the result you get. I'm not running Python 2.4 so I can't test this, but to get the result you want I guess you want this: py> x.sort(key=len, reverse=True) py> x ['aardvark', 'abalone', 'aerate', 'acme', 'add'] or: py> x.sort(key=len) py> x.reverse() -- Steven. From bonono at gmail.com Tue Nov 22 22:50:12 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 19:50:12 -0800 Subject: Anyway to clarify this code? (dictionaries) In-Reply-To: <86ek5812a3.fsf@bhuda.mired.org> References: <1132711108.860281.59900@g49g2000cwa.googlegroups.com> <86ek5812a3.fsf@bhuda.mired.org> Message-ID: <1132717811.989127.55520@g14g2000cwa.googlegroups.com> Mike Meyer wrote: > def my_search(another, keys, x): > new = dict() > for k in keys: > if another[k] >= x: > new[k] = another[k] > return new > BTW, this would raise exception if k is not in another. From pmartin at snakecard.com Sat Nov 5 16:08:10 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Sat, 05 Nov 2005 21:08:10 +0000 Subject: starting an X11 session from Python References: <848bf.3759$HB.1191@dukeread12> Message-ID: Nothing, but that was not my question. Regards, Philippe Sybren Stuvel wrote: > Philippe C. Martin enlightened us with: >> Have there been any attempt to do so, and is there any source out >> there that could help me get started ? > > What's stopping you from using system(), exec() or the likes to start > "startx", "xinit" or simply "X"? > > Sybren From grante at visi.com Wed Nov 9 13:50:56 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 09 Nov 2005 18:50:56 -0000 Subject: PYTHON LOOSING FOR JAVA??????? References: <1131401093.921769.173160@o13g2000cwo.googlegroups.com> <436FD5D4.7010307@v.loewis.de> <797fe3d40511081246h46169553x1f2a1289b1837864@mail.gmail.com> Message-ID: <11n4h8g4qf2o53d@corp.supernews.com> On 2005-11-09, James Colannino wrote: > Bill Mill wrote: > >>+1 QOTW >> >> > > My ignorance shows here. What does that mean? :-P It's a "vote" for Qutoe of the Week. -- Grant Edwards grante Yow! Are we live or at on tape? visi.com From robert.kern at gmail.com Sat Nov 26 23:54:49 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 26 Nov 2005 20:54:49 -0800 Subject: Syntax In-Reply-To: <1133065081.696769.32570@z14g2000cwz.googlegroups.com> References: <1133065081.696769.32570@z14g2000cwz.googlegroups.com> Message-ID: calad.sigilon at gmail.com wrote: > If you use 'from os import *' then you shouldn't preface the commands > with os. > > So, two options: > > from os import * > print "Working Path: %s" % getcwd() > > OR > > import os > print "Working Path: %s" % os.getcwd() > > One of these two ways you're not supposed to use for security reasons, > but I'm spacing on which one. I don't think there are any *security* reasons, but stylistically, "import os" is greatly preferred. When someone else reads your code, they will immediately know where getcwd() comes from. -- 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 sigzero at gmail.com Sat Nov 12 17:01:57 2005 From: sigzero at gmail.com (Robert Hicks) Date: 12 Nov 2005 14:01:57 -0800 Subject: Can't uninstall wxPython In-Reply-To: <1131695728.930992.307880@g49g2000cwa.googlegroups.com> References: <1131695728.930992.307880@g49g2000cwa.googlegroups.com> Message-ID: <1131829498.968215.183090@g47g2000cwa.googlegroups.com> Justin wrote: > I have two versions of wxPython installed on my Mac (OS X Tiger). One > is version 2.6.1.0 and the other is version 2.6.0.0. I want to keep > the newer version, but I can't seem to uninstall either one using the > uninstall_wxPython.py script. > > When I run that script, I get this error message: > $ sudo: uninstall_wxPython.py: command not found > > Is there any way I could delete one, or both, of these installations > manually? For some reason, whenever I try to run a wxPython script, it > uses the older version of wxPython and it doesn't always run correctly. > > Thanks in advance. If it has the x bit set you will have to do something like this: sudo ./uninstall_wxPython.py Otherwise pass "python" explicitly: sudo python uninstall_wxPython.py I think that it is going to wipe out all your wxPython installs...so you will need to reinstall the version you wanted. HTH, Robert From gh at ghaering.de Thu Nov 3 10:57:34 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 03 Nov 2005 16:57:34 +0100 Subject: Python and MySQL In-Reply-To: References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: <436A336E.6020604@ghaering.de> Thomas Bartkus wrote: > [some posters having the idea that MySQLdb works without a C extension] > Okay - I neglected to look at the [site-packages] directory itself. Here I > do find [_mysql.pyd] full of binary code. A MySQLdb related file that > doesn't seem to have a corresponding file with Python source code. Mea > culpa! This is on MS Windows [C:\Python23]. > > But heck! Now I'm looking at the /usr/lib/python2.3/site-packages on a > Mandrake Linux box. No [_mysql.] pyd here! Fewer files overall and while > there are other file extensions, everything seems to have a corresponding > [.py]. MySQLdb is based on a C extension module called _mysql on all platforms. The C extension modules have the extension ".pyd" on Windows by default, and ".so" on Unix. It would in theory be possible to do without a C extension, but then you would have to implement the MySQL client-server protocol (http://dev.mysql.com/doc/internals/en/client-server-protocol.html) in Python, for example using the socket module. Implementing a pure-Python package to interface a database by implementing the client-server protocol in Python has been done already for PostgreSQL, but I don't think it has been done for MySQL, yet. -- Gerhard From mhellwig at xs4all.nl Thu Nov 24 17:26:38 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 24 Nov 2005 23:26:38 +0100 Subject: wxPython Licence vs GPL In-Reply-To: <86oe49wyky.fsf@bhuda.mired.org> References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> <86oe49wyky.fsf@bhuda.mired.org> Message-ID: <43863e25$0$11061$e4fe514c@news.xs4all.nl> Mike Meyer wrote: > > Well, they chose to make it available to others for reuse. But > software "unavailable to those who can't afford it" is better than "no > software at all" That I do not agree with, I think it depends on which your side of the fence you are. For instance I have a specific problem, there are currently 2 product available that come close to solving it, one costs $24,999 and the other is above that. That is about $23,999 above what I can afford to solve my problem, so I have the option to leave the problem as it is or try to tackle it myself. Stubborn that I am, I am currently creating my own solution, knowing well that other solutions exist and I can only make a poor copy of those already existing effort > >> However I make a poor defender for the GPL because, as you can read in >> my previous posts, I don't really believe in it. > > The question is wether or not it believes in you :-) > > I believe in GPL'ed software - I use it regularly. On the other hand, > I don't believe that it represents the best license to release > software if the goal is to improve the lot of humanity. The > restrictions are on "distribution", not on use, so it doesn't really > keep people from using said software commercially. For instance, one > or more of your examples may have been worth developing for internal > use. They then decided there was a profit to be made in distributing > it commercially, and proceeded to do so because they could. Without > the profit motive, they may not have done the extra work involved in > preparing the IP for distribution and doing the distribution. Yeah well, GPL works reasonable well but perhaps not for what it was intended. > > Personally, I release stuff under a BSD-like license, historically > having included requirements that I be notified of bug fixes, and/or > that I be given copies of commercial software that included my code. I > eventually gave up on them as unenforceable. Thats the trouble with restrictions, how do you enforce them, with license I don't found it worth the hazzle. BSD/MIT style license is a good substitute of no license at all. -- mph From aleax at mail.comcast.net Thu Nov 24 17:20:51 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 24 Nov 2005 14:20:51 -0800 Subject: Why is dictionary.keys() a list and not a set? References: <8664qi3oef.fsf@bhuda.mired.org> <1h6iyik.86v3t3z8icd7N%aleax@mail.comcast.net> <1h6j466.1pwsjsevabcuxN%aleax@mail.comcast.net> Message-ID: <1h6jbmp.vo1aoh1fw1u1mN%aleax@mail.comcast.net> Christoph Zwerschke wrote: > Alex Martelli wrote: > > > An alternative theory, of course, is "God made the natural numbers; all > > else is the work of man" -- and that one is by a German, too (Kronecker, > > if I recall correctly). > > Yes, it was Kronecker. But even natural numbers are usually constructed > with sets using Peano's axioms. Peano's axioms are perfectly abstract, as far as I recall. Russell and Whitehead did try to construct naturals from sets (defining, e.g., '5' as "the set of all sets with five items"), but that was before the inherent contradictions of set theory were widely known (though Russell himself had destroyed Frege's attempts at theorization by pointing out one such contradiction, the one wrt the "set of all sets that don't include themselves as a member" if I recall correctly). Later, Goedel showed that any purely formal theory that's powerful enough to model natural arithmetic cannot be both complete and consistent... > > The hope to found all of mathematics on set theory was primarily a > > _British_ effort, as I see it (Russell and Whitehead), and failed a > > long time ago... I'm not sure what, if anything, a mathematician of > > today would propose as the foundational theory... > > Perhaps "string theory" ;-) So probably strings should become the Some physicists, maybe, surely not mathematicians though! Alex From steven.bethard at gmail.com Tue Nov 22 14:19:15 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 Nov 2005 12:19:15 -0700 Subject: the name of a module in which an instance is created? In-Reply-To: References: Message-ID: <5cednUHIc9Ss8h7enZ2dnUVZ_vudnZ2d@comcast.com> Mardy wrote: > I'm not sure I got your problem correctly, however see if this helps: > > $ cat > test.py > class myclass: > name = __module__ > ^D > [snip] > > >>> import test > >>> a = test.myclass() > >>> a.name > 'test' > > This works, as we define "name" to be a class attribute. > Is this useful to you? Unfortunately, no, this is basically what I currently have. Instead of a.name printing 'test', it should print '__main__'. I want the name of the module in which the *instance* is created, not the name of the module in which the *class* is created. STeVe P.S. Note that I already discussed two possible solutions which I didn't much like: (1) pass __name__ to the class instance, e.g. ``a = test.myclass(__name__)`` or (2) declare an empty sublcass of myclass in the second module (in your case, at the interactive prompt). From jmdeschamps at gmail.com Wed Nov 9 07:01:01 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 9 Nov 2005 04:01:01 -0800 Subject: Newb ?? In-Reply-To: <1131506094.767452.156780@o13g2000cwo.googlegroups.com> References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> Message-ID: <1131536396.151691.55410@z14g2000cwz.googlegroups.com> ## Here you always get 100... This is false , sorry for the wrong comment on this part, it should rather be: ## randrange is from start to end-1 the_number = random.randrange(1,101) JM (But the rest of my comment seems OK) From steve at REMOVETHIScyber.com.au Fri Nov 4 22:42:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 14:42:26 +1100 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> <1131023021.643251.113330@f14g2000cwb.googlegroups.com> <1h5fwpi.1wjmgm417fbm8dN%aleax@mail.comcast.net> <1131033712.535402.193520@z14g2000cwz.googlegroups.com> <1h5grc5.1f520xizhqvucN%aleax@mail.comcast.net> <1131128383.049466.179370@f14g2000cwb.googlegroups.com> <42gt33-cst.ln1@rogers.com> Message-ID: On Fri, 04 Nov 2005 20:55:48 -0500, Chris F.A. Johnson wrote: So that people reading your reply know what you are commenting about. (Now, imagine that you're reading from a newsgroup where Chris' post has disappeared off the server, or perhaps never showed up at all.) -- Steven. From bignose+hates-spam at benfinney.id.au Mon Nov 14 00:08:26 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Nov 2005 16:08:26 +1100 (EST) Subject: Abstract Base Classes References: Message-ID: Ben Finney wrote: > I want my modules to (sometimes) define an abstract base exception > class, that all other exceptions in that module inherit from. [re-posting with the implementation properly foo-ified] Not a whole lot of feedback on this, so here's the implementation I decided upon. class FooException(Exception): """ Base class for all exceptions in this module """ def __init__(self): if self.__class__ is FooException: raise NotImplementedError, \ "%s is an abstract class for subclassing" % self.__class__ class FooBarTypeError(TypeError, FooException): """ Raised when the foo gets a bad bar """ class FooDontDoThatError(AssertionError, FooException): """ Raised when the foo is asked to do the wrong thing """ This allows the exceptions for the module to behave similarly to their leftmost base exception; but because they all inherit from the abstract base class exception for the module, it also allows for this idiom: import foo try: foo.do_stuff(bar) except FooException, e: special_error_handler(e) Any more comment on this technique? Any other significant use cases for abstract base classes? -- \ "For man, as for flower and beast and bird, the supreme triumph | `\ is to be most vividly, most perfectly alive" -- D.H. Lawrence. | _o__) | Ben Finney From jsfrank.chen at msa.hinet.net Wed Nov 16 00:45:33 2005 From: jsfrank.chen at msa.hinet.net (Thomas Moore) Date: Wed, 16 Nov 2005 13:45:33 +0800 Subject: Is there any Iterator type example? Message-ID: Hi: Nice example too! But what I really want to know is how to use __iter()__ and next() in a class with an example. >> How about this one: >>...... From peter at engcorp.com Mon Nov 21 19:39:42 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Nov 2005 19:39:42 -0500 Subject: Command line In-Reply-To: <1132617423.411302.55190@o13g2000cwo.googlegroups.com> References: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> <4382586f.411203839@news.oz.net> <1132617423.411302.55190@o13g2000cwo.googlegroups.com> Message-ID: amfr wrote: > Thanks for your help. Another question, is there an built in md5/sha1 > function in python? Yes. Although it's a long list, it is worthwhile as a newbie for one to peruse the list of standard modules from time to time, until you gain a familiarity with what is there. http://docs.python.org/modindex.html -Peter From larry.bates at websafe.com Thu Nov 17 15:05:53 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 17 Nov 2005 14:05:53 -0600 Subject: os.spawnl error In-Reply-To: <1132257061.597353.70670@g43g2000cwa.googlegroups.com> References: <1132257061.597353.70670@g43g2000cwa.googlegroups.com> Message-ID: <437CE2A1.60705@websafe.com> The backslashes in your path are being interpreted as escape characters (e.g. \n is a newline). Try instead: os.spawnl(os.P_NOWAIT,r'c:\windows\notepad.exe') or os.spawnl(os.P_NOWAIT,'c:\\windows\\notepad.exe') -Larry Bates Salvatore wrote: > Hello, > > Does someone already had ths problem ? > > >>>>os.spawnl(os.P_NOWAIT,'c:\windows\notepad.exe') > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\os.py", line 565, in spawnl > return spawnv(mode, file, args) > OSError: [Errno 22] Invalid argument > > Regards > > Salvatore > From jstroud at mbi.ucla.edu Mon Nov 7 20:23:07 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 7 Nov 2005 17:23:07 -0800 Subject: how to modify code while debugging it without having to stop and then restart debugger In-Reply-To: References: Message-ID: <200511071723.07366.jstroud@mbi.ucla.edu> On Monday 07 November 2005 16:56, python wrote: > > so how can i use python to debug code and change that code without having > to restart the code. look into reload() -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at REMOVETHIScyber.com.au Fri Nov 18 23:09:30 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 15:09:30 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> Message-ID: On Tue, 15 Nov 2005 03:06:31 -0800, Ben Sizer wrote: > My interest lies in being able to use encrypted data (where 'data' can > also include parts of the code) so that the data can only be read by my > Python program, and specifically by a single instance of that program. > You would be able to make a backup copy (or 20), you could give the > whole lot to someone else, etc etc. I would just like to make it so > that you can't stick the data file on Bittorrent and have the entire > world playing with data that was only purchased once. Well, if and when you find a way to make water not wet and three-sided squares, then you can turn your mind towards solving the *really* hard problem: how to make bytes not copyable. -- Steven. From steve at REMOVEMEcyber.com.au Wed Nov 23 02:52:33 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 23 Nov 2005 18:52:33 +1100 Subject: Anyway to clarify this code? (dictionaries) References: <1132711108.860281.59900@g49g2000cwa.googlegroups.com> Message-ID: <43841FC1.50209@REMOVEMEcyber.com.au> javuchi wrote: > I want to avoid converting the dictionary to a list and then to a > dictionay. Are there speed penalties for such a conversion? You mean, is it faster to write, test, debug and execute slow Python code rather than letting Python's built-in routines written in fast C do the job? I have no idea. Perhaps you should try it and see. Write some code to do it all manually, and time it. Make sure you use realistic test data: if your users will be using dictionaries with 10,000 items, there is no point in testing only dictionaries with 10 items. For accuracy, run (say) 20 tests, and look at the average speed. Of better still, use the timeit module. -- Steven. From pmartin at snakecard.com Sat Nov 5 12:31:51 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Sat, 05 Nov 2005 17:31:51 +0000 Subject: SCLOGON 0.1 Smart Card event daemon for GNU/Linux Message-ID: Dear all, This is to announce the release of the event deamon I intend to use in SCLOGIN; a GPL project that attempts to: 1) give the current logon managers (gdm, kdm, ...) the necessary plugins to support vendor-independant smart card logon 2) be a complete logon manager itself SCLOGIN will be discussed here: www.snakecard.com/WordPress and found here: www.snakecard.com/SCLOGON. Regards, Philippe From fperez.net at gmail.com Fri Nov 11 00:29:30 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 10 Nov 2005 22:29:30 -0700 Subject: need an example of Python numarray to C++ and back again, Boost / SWIG? References: <1131547248.473442.313820@g47g2000cwa.googlegroups.com> <1131634767.323353.110480@g14g2000cwa.googlegroups.com> Message-ID: PL wrote: > I looked at Stefan's post - but he remarks that "Unfortunately, Blitz > jealously guards its data (restricted pointers), so that it is not so > easy to do the conversion in the other direction. If anyone knows an > answer to this problem, I'd be glad to hear it" > > I've previously looked at Phillip Austin's 'num_util' and Paulo J. S. > Silva's 'COIN' example, but even from those two, I can't figure out a > way to do: Python 2D numarray --> C++ (process array) --> Python 2D > numarray. I may be missing something, but what I've done in the past for this is have the C++ code simply reuse the Numeric data pointer. This way, when I exit the C++ extension (I've used blitz++ for the job), the array as seen from the python side has been 'magically' modified. Obviously this means that I can't allocate new arrays in C++ which can be transfered over to python without paying the price of a copy, but in my cases that hasn't been a problem: I do all 'allocations' in python (via arr=Numeric.empty(...)) and let the blitz code fill in the arrays. This has the advantage that the blitz array creation is extremely cheap, as only the shape tuple needs to be copied (not the data region). The following little snippet is pretty much all that's needed if the above description happens to work for you. This code is mostly taken from weave's internals: // -*- C++ -*- #ifndef PY_TO_BLITZ_H #define PY_TO_BLITZ_H #include "Python.h" #include "Numeric/arrayobject.h" #include "blitz/array.h" using namespace blitz; // Convert a Numpy array to a blitz one, using the original's data (no copy) template static Array py_to_blitz(const PyArrayObject* arr_obj) { const int T_size = sizeof(T); TinyVector shape(0); TinyVector strides(0); int *arr_dimensions = arr_obj->dimensions; int *arr_strides = arr_obj->strides; for (int i=0;i((T*) arr_obj->data,shape,strides,neverDeleteData); } #endif // PY_TO_BLITZ_H Cheers, f From thorsten at thorstenkampe.de Tue Nov 1 04:45:42 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 1 Nov 2005 09:45:42 +0000 Subject: OpenSSL in Python References: <1130425810.431748.39660@g14g2000cwa.googlegroups.com> <1130807503.274960.158820@g14g2000cwa.googlegroups.com> Message-ID: <1f3kn7vzljxwg.ikqig3y23qrv$.dlg@40tude.net> * Thorsten Kampe (2005-11-01 09:36 +0100) > * dcrespo (2005-11-01 01:11 +0100) >>> wouldn't your question then not be more appropriate on the >>> OpenSSL newsgroup/mailinglist/forum/whatever? >> >> Well, I think that because python is the language where I want it to >> run, I ask it right here. > > You might think again. Your problem is not related to Python in any > way. > >> OpenSSL is written in C, so they wont help me. > > Who's "they"? You mean (probably) that the developers won't help you installing OpenSSL because you need it for Python?! Holy Sh**... No one cares what you need it for. If you would need it for Ruby or Perl it still would have nothing to do with Ruby or Perl. From boklm at mars-attacks.org Tue Nov 8 07:54:16 2005 From: boklm at mars-attacks.org (Nicolas Vigier) Date: Tue, 8 Nov 2005 13:54:16 +0100 (CET) Subject: recursive function call In-Reply-To: References: Message-ID: <52575.192.54.193.37.1131454456.squirrel@invaders.mars-attacks.org> Peter Otten said: > Here is a non-recursive approach: > > def tolist(arg): > if isinstance(arg, list): > return arg > return [arg] > > def f(arg1, arg2, more_args): > for arg1 in tolist(arg1): > for arg2 in tolist(arg2): > # real code > > If it were my code I would omit the tolist() stuff and instead always > pass lists (or iterables) as the function's first two arguments. Hmm, that's right. After all it's not very useful to be able to give a single element, passing a list all the time is more simple. That's what I'll do. I got the idea of passing a list or a singe element because that's what they do in SCons, but in my case it's not really usefull. Thanks -- http://n0x.org/ - boklm at mars-attacks.org From lycka at carmen.se Thu Nov 24 05:10:20 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 24 Nov 2005 11:10:20 +0100 Subject: Writing big XML files where beginning depends on end. Message-ID: We're using DOM to create XML files that describes fairly complex calculations. The XML is structured as a big tree, where elements in the beginning have values that depend on other values further down in the tree. Imagine something like below, but much bigger and much more complex: 7 2 1 5 We have to stick with this XML structure for now. In some cases, building up a DOM tree in memory takes up several GB of RAM, which is a real showstopper. The actual file is maybe a magnitute smaller than the DOM tree. The app is using libxml2. It's actually written in C++. Some library that used much less memory overhead could be sufficient. We've thought of writing a file that looks like this... 7 2 1 5 ...and store {"#": "15", "#1.1", "10" ... } in a map and then read in a piece at a time and performs some simple change and replace to get the correct values in. Then we need something that allows parts of the XML file to be written to file and purged from RAM to avoid the memory problem. Suggestions for solutions are appreciated. From jstroud at mbi.ucla.edu Sun Nov 6 01:45:37 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 5 Nov 2005 22:45:37 -0800 Subject: __new__ Message-ID: <200511052245.37627.jstroud@mbi.ucla.edu> Hello All, I'm running 2.3.4 I was reading the documentation for classes & types http://www.python.org/2.2.3/descrintro.html And stumbled on this paragraph: """ __new__ must return an object. There's nothing that requires that it return a new object that is an instance of its class argument, although that is the convention. If you return an existing object, the constructor call will still call its __init__ method. If you return an object of a different class, its __init__ method will be called. """ The quote implies that when I call carol, b.__init__ should be called. However, this does not seem to be the case (see code below). What am I not understanding? Shouldn't the interpreter call b.__init__ when b is returned from carol.__new__? James py> class bob(object): ... def __init__(self): ... print self.x ... x = 2 ... py> class carol(object): ... def __new__(cls): ... return b ... py> b=bob() py> b.x 2 py> c = carol() # should print "2" py> c <__main__.bob object at 0x404333cc> -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bonono at gmail.com Fri Nov 4 01:51:18 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 3 Nov 2005 22:51:18 -0800 Subject: I need Motivation In-Reply-To: References: Message-ID: <1131087078.834433.279890@o13g2000cwo.googlegroups.com> blah at blah.blah wrote: > I m not a python Expert or anythin > i need help, i m losin my motivation to continue with python > can anyone inspire me again.??? Why continue then ? From nick at craig-wood.com Tue Nov 15 08:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 15 Nov 2005 07:30:03 -0600 Subject: simulating #include in python Message-ID: We are currently investigating whether to move the data files from our application into python for ease of maintenance. Each data item turns into a class definition with some class data. The python approach looks great, but there is one feature that we'd like to have. Currently the data files can include other data files. Typically thats used to import standard definitions from somewhere else (rather like #include in C - conceptually its a completely textual import). We use them something like this include("../../standard_definitions") include("../shared_definitions") class A(base_from_standard_definitions): pass class B(A): pass include("more_definitions") The includes act much more like #include than import - all the symbols from the file before the include() must be available to the included file and the included file must export all its symbols back to the parent. These can of course be re-arranged to work in a pythonic way using 'from x import *' and putting "../.." on sys.path instead of the includes. However there are over 500 of these files so I'd prefer a more automatic solution which doesn't require re-arrangement in the interim. (The re-arrangement is needed because "more_definitions" above might refer to A, B or anything defined in standard/shared_definitions leading to mutually recursive imports and all the pain they cause) I have implemented a working prototype, but it seems such a horrendous bodge that there must surely be a better way! I'd really like to be able to run an __import__ in the context of the file thats running the include() but I haven't figured that out. Here is the code (avert your eyes if you are of a sensitive nature ;-) Any suggestions for improvement would be greatly appreciated! def include(path): # Add the include directory onto sys.path native_path = path.replace("/", os.path.sep) directory, module_name = os.path.split(native_path) if module_name.endswith(".py"): module_name = module_name[:-3] old_sys_path = sys.path if directory != "": sys.path.insert(0, directory) # Introspect to find the parent # Each record contains a frame object, filename, line number, function # name, a list of lines of context, and index within the context. up = inspect.stack()[1] frame = up[0] parent_name = frame.f_globals['__name__'] parent = sys.modules[parent_name] # Poke all the current definitions into __builtin__ so the module # uses them without having to import them old_builtin = __builtin__.__dict__.copy() overridden = {} poked = [] for name in dir(parent): if not (name.startswith("__") and name.endswith("__")): if hasattr(__builtin__, name): overridden[name] = getattr(__builtin__, name) else: poked.append(name) setattr(__builtin__, name, getattr(parent, name)) # import the code module = __import__(module_name, parent.__dict__, locals(), []) # Undo the modifications to __builtin__ for name in poked: delattr(__builtin__, name) for name, value in overridden.items(): setattr(__builtin__, name, value) # check we did it right! Note __builtin__.__dict__ is read only so # can't be over-written if old_builtin != __builtin__.__dict__: raise AssertionError("Failed to restore __builtin__ properly") # Poke the symbols from the import back in for name in dir(module): if not (name.startswith("__") and name.endswith("__")): setattr(parent, name, getattr(module, name)) # Restore sys.path sys.path = old_sys_path -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mwm at mired.org Sat Nov 5 20:58:35 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 20:58:35 -0500 Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> <7x4q6q7f6b.fsf@ruckus.brouhaha.com> Message-ID: <86hdaqsfjo.fsf@bhuda.mired.org> Paul Rubin writes: > Mike Meyer writes: >> The thing is, the library documentation that Xah Lee is complaining >> about is a *reference document*. It says so right in the title: >> "Python Library Reference". As such, it makes lousy tutorial >> documentation. > I'm not sure which particular library Xah Lee was complaining about > but lots of the lib docs are awful even as references. That's true, but Xah Lee's proposed fixes do nothing to address this problem. >> The Python Cookbook should show up a lot in this search. If other >> people are providing tutorial documentation, then it's not at clear >> that the PSF should be duplicating that effort. > It seems to me that since the PSF is so persnickety about code > licenses (and that is a good thing), it should be persnickety about > documentation licenses too. Lots of FSF documentation projects were > undertaken because while there were good docs in existence for > whatever it was, there were none that the FSF could include in its > distros. It's similarly not so great if Python users have to rely on > proprietary docs. Of course the PSF has to prioritize its tasks and > some things will necessarily stay far down on the "list" for quite a > while, but they should at least BE on the list. To my knowledge the PSF isn't doing anything about including the documentation with their distribution, so they shouldn't care about the licenses. Wanting to bundle a good tutorial for everything in the library might be on the list, but the licenses on third-party tutorials shouldn't matter until you are considering bundling them. In that light, the only major omission I can think of is Tkinter, as the only good docs - tutorial, reference, or otherwise - is the Grayson's book. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From onurb at xiludom.gro Wed Nov 23 09:02:40 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 23 Nov 2005 15:02:40 +0100 Subject: user-defined operators: a very modest proposal In-Reply-To: References: Message-ID: <43847681$0$21623$636a15ce@news.free.fr> Joseph Garvin wrote: > Tom Anderson wrote: > >> Jeff Epler's proposal to use unicode operators would synergise most >> excellently with this, allowing python to finally reach, and even >> surpass, the level of expressiveness found in languages such as perl, >> APL and INTERCAL. s/expressiveness/unreadability/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aleax at mail.comcast.net Mon Nov 14 09:50:54 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 14 Nov 2005 06:50:54 -0800 Subject: gmpy/decimal interoperation References: <1h5z5pl.rbt4q91q4qw27N%aleax@mail.comcast.net> Message-ID: <1h6085p.tv514618th5g1N%aleax@mail.comcast.net> Raymond L. Buvel wrote: ... > This is a bit off topic but I would like to know how you would go about > doing an implicit operation with an mpz and Decimal becoming a Decimal. I would tweak Decimal.__new__ to accept an mpz and perform an int() on it before proceeding as it does now, for example. > I would like to use something like this to make the float and complex > types more interoperable with mpq and cmpq in my clnum module > (http://calcrpnpy.sourceforge.net/clnumManual.html). In those cases, I > would like the mpq to degrade to float and the cmpq to degrade to > complex (right now they just raise exceptions). Seems like you need to > either modify the target type to recognize the new one or the code has > to get very complex to handle all the combinations. Modifying the target type is indeed what I had in mind (for Decimal). As long as the target-type is Python-coded, you can substitute its __new__ with a wrapped version. Unfortunately, float and complex aren't; but fortunately, Python does have for these cases appropriate special methods/slot that your SOURCE type can implement. In gmpy, I have float 'upgraded' to mpq (with a Stern-Brocot heuristic), but it wouldn't be any harder to have the mpq 'degrade' to float instead. Alex From steve at holdenweb.com Wed Nov 23 04:33:09 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Nov 2005 09:33:09 +0000 Subject: Hot to split string literals that will across two or more lines ? In-Reply-To: References: Message-ID: Mohammad Jeffry wrote: > I tried to use this method in my code like this:- > --------------------------------------------------------------------------------- > #!/usr/bin/python > > > def print_sql(): > sql = '''aaaaaaaaaaaaaaaaaaaaaaa > bbbbbbbbbbbbbbbbbbbbbbb'''.replace("\n","") > print sql > > print_sql() > > --------------------------------------------------------------------------------- > > the ouput of this is aaaaaaaaaaaaaaaabbbb...... > > I can always do this :- > --------------------------------------------------------------------------------- > #!/usr/bin/python > > > def print_sql(): > sql = '''aaaaaaaaaaaaaaaaaaaaaaa > bbbbbbbbbbbbbbbbbbbbbbb'''.replace("\n","") > print sql > > print_sql() > > --------------------------------------------------------------------------------- > > but it looks ugly > > [...] In your particular case, if it really is SQL you're dealing with then you shouldn't worry about what it looks like when you print it - the SQL interpreter certainly won't care. Many SQL statements are so long that it actually helps readability to have newlines in them. There have been plenty of solutions presented in the earlier posts in this thread if you really do need to represent multi-line strings. 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 fredrik at pythonware.com Mon Nov 14 16:45:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Nov 2005 22:45:03 +0100 Subject: more newbie help needed References: <20051114192046.64486.qmail@web35901.mail.mud.yahoo.com> Message-ID: Craig Marshall wrote: > Or, if you're *really* just trying to reverse the string, then the > following might read more easily (although it's probably longer): > fruit = list(fruit) > fruit.reverse() > fruit = ''.join(fruit) same thing, on one line: fruit = "".join(reversed(fruit)) same thing, in one operation: fruit = fruit[::-1] From cito at online.de Tue Nov 29 04:55:11 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 29 Nov 2005 10:55:11 +0100 Subject: General question about Python design goals In-Reply-To: <86k6estfkd.fsf@bhuda.mired.org> References: <86k6estfkd.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Christoph Zwerschke wrote: >>A programming language is not a "work of art". If you are an artist, >>you may break symmetry and introduce all kinds of unexpected >>effects. Actually, as an artist, you purposfully want to provoke >>astonishment. But if I am using a programming language or a user >>interface, I don't want to be confronted with inconsistent >>behavior. Here, the "principle of least astonishment" is much more >>helpful (in my little mind's humble optionion). > > But a programming language (or UI) is not just a collection of syntax > and and interfaces - it's an implementation. You need to keep in mind > that "practicality beats purity". If following POLA makes the > implementation an order of magnitude slower or larger, then you don't > follow POLA - at least until you can do it without that cost. I do not deny this. As an example, if tuples can be used as keys of dicts, you might first naively assume that lists could also work. This is not the case for practicality (performance) reasons and because it would be difficult or impossible to guarantee the uniqueness of keys. In this case, POLA is overruled by other goals or inherent necessities. But that does not mean that POLA in itself is not an important guiding principle for programming languages (or UI). -- Christoph From satyakiranl at gmail.com Thu Nov 24 18:33:41 2005 From: satyakiranl at gmail.com (Satya Kiran) Date: Thu, 24 Nov 2005 18:33:41 -0500 Subject: multiple raw_inputs Message-ID: <6f4842a0511241533k29c3f170g163cf735c2b8ac89@mail.gmail.com> Hi there! I m a python newbie,infact,I m a newbie to programming and I was suggested it was a good idea to start it with python. I was trying a program which needs three integers from the user.I got it by using raw_input thrice. Is there a better way(s) to do it? Can a user be prompted thrice with a single raw_input and something additional? thanks in advance, Kiran Saty -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Thu Nov 10 01:29:55 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 10 Nov 2005 00:29:55 -0600 Subject: xml.minidom and user defined entities References: Message-ID: Fredrik Lundh wrote: > Nick Craig-Wood wrote: > > > I'm using xml.minidom to parse some of our XML files. Some of these > > have entities like "°" in which aren't understood by xml.minidom. > > ° is not a standard entity in XML (see below). No probably not... > > These give this error. > > > > xml.parsers.expat.ExpatError: undefined entity: line 12, column 1 > > > > Does anyone know how to add entities when using xml.minidom? > > the document is supposed to contain the necessary entity declarations > as an inline DTD, or contain a reference to an external DTD. (iirc, mini- > dom only supports inline DTDs, but that may have been fixed in recent > versions). The document doesn't define the entitys either internally or externally. I don't fancy adding an inline definition either as there are 100s of documents I need to process! > if you don't have a DTD, your document is broken (if so, and the set of > entities is known, you can use re.sub to fix replace unknown entities with > the corresponding characters before parsing. let me know if you want > sample code). I was kind of hoping I could poke my extra entities into some dict or other in the guts of xml.minidom... However the job demands quick and nasty rather than elegant so I'll go for the regexp solution I think, as the list of entities is well defined. Thanks for your help Nick -- Nick Craig-Wood -- http://www.craig-wood.com/nick From smcg4191zz at friizz.RimoovAllZZs.com Sun Nov 13 17:02:07 2005 From: smcg4191zz at friizz.RimoovAllZZs.com (Stuart McGraw) Date: Sun, 13 Nov 2005 15:02:07 -0700 Subject: Python Book References: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> Message-ID: <11nfdv67tfvt246@corp.supernews.com> David Beasley's Essential Python (New Riders). It's a little dated now (covers only up to version 2.2) but lucid, consise, well organized. It restricts itself to Python's syntax and semantics and does not waste time explaining basic programming concepts. I made several attempts to learn Python but found the Python docs pretty poor, and the tutorial books I looked at were incredibly ponderous and slow. It wasn't until I got Beasley's book that I could actual find info effectively enough to start actually writing Python code. I still most often refer to it in preference to the Python docs. "David Rasmussen" wrote in message news:43779016$0$2111$edfadb0f at dtext02.news.tele.dk... > What is the best book for Python newbies (seasoned programmer in other > languages)? > > /David From pinkfloydhomer at gmail.com Tue Nov 8 04:43:43 2005 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: 8 Nov 2005 01:43:43 -0800 Subject: Addressing the last element of a list In-Reply-To: <1131442540.244858.290110@z14g2000cwz.googlegroups.com> References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> Message-ID: <1131443023.638868.212340@f14g2000cwb.googlegroups.com> But if lst[42]["pos"] happens to hold an integer value, then a = lst[42]["pos"] will _copy_ that integer value into 'a', right? Changing 'a' will not change the value at lst[42]["pos"] From steve.horsley at gmail.com Tue Nov 1 15:15:14 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Tue, 01 Nov 2005 20:15:14 +0000 Subject: callback for ctypes In-Reply-To: References: Message-ID: James Hu wrote: > Hi, gurus, > > I would like to use ctypes to implement callback function for QImage > Camera to capture image asynchronously, and I have the c++ code of > callback, but I am totally in the dark, the ctypes tutorial is not good > enough for me to do that, does someone know where to dig more info for > ctypes callback implementation? > > Thanks, > > James I've done one, but I can't get back to you with details until this time tomorrow. If nobody else is helping by then, I'll try. Steve From fredrik at pythonware.com Tue Nov 22 09:51:30 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 15:51:30 +0100 Subject: the first element in the list of list References: <8c11e4350511220636p59b22d63pced73232aed06379@mail.gmail.com> Message-ID: Ben Bush wrote: > I have a lis: > [[1,3],[3,4],[5,6],[8,9],[14,0],[15,8]] > I want a code to test when the difference between the first element in > the list of list is equal to or larger than 6, then move the previous > lists to the end of the list. that is: > [[14,0],[15,8],[1,3],[3,4],[5,6],[8,9]] have you tried doing this yourself? how far did you get? can you post the code so we can help you figure out what you need to fix? is this a homework assignment? here's a oneliner: L = [x for x in L if x[0]-x[1] >= 6] + [x for x in L if x[0]-x[1] < 6] depending on how you define "difference", you may need to replace x[0]-x[1] with abs(x[0]-x[1]) From kjcsb at orcon.net.nz Thu Nov 3 13:01:58 2005 From: kjcsb at orcon.net.nz (Cameron Beattie) Date: Fri, 4 Nov 2005 07:01:58 +1300 Subject: Issues with pyperl: perl2.so not found Message-ID: <009601c5e0a0$af905c70$0b00a8c0@HOUSTON> I am attempting to install pyperl and am having an issue where it can't find perl2.so. I think this is one of those ones where it's looking under the stairs for something which is actually in the laundry under a pile of dirty clothes. cd /tmp/pyperl* cd Python-Object; perl Makefile.PL; make install cd .. python setup.py install python test.py Traceback (most recent call last): File "apply.py", line 1, in ? import perl ImportError: perl2.so not found echo $PATH /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin find -name perl2.so ./usr/lib/python2.4/site-packages/perl2.so whereis python python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 /usr/lib/python2.3 /usr/include/python2.4 /usr/share/man/man1/python.1.gz whereis perl perl: /usr/bin/perl /usr/share/man/man1/perl.1.gz python -V Python 2.4.1 perl -v This is perl, v5.8.6 built for i386-linux-thread-multi Obviously I've done something wrong and any clues to point me or the system in the right direction would be appreciated. Regards Cameron From maxm at mxm.dk Tue Nov 8 05:06:38 2005 From: maxm at mxm.dk (Max M) Date: Tue, 08 Nov 2005 11:06:38 +0100 Subject: Sending email in utf-8? In-Reply-To: <1131388898.175850.301140@o13g2000cwo.googlegroups.com> References: <1131381565.320532.229310@g49g2000cwa.googlegroups.com> <1131388898.175850.301140@o13g2000cwo.googlegroups.com> Message-ID: <43707877$0$38734$edfadb0f@dread12.news.tele.dk> morphex wrote: > That works, kinda. I get strange characters now like this > > """ > Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST) > Message-Id: <200511071838.jA7IcTKR095057 at thinkering.com> > To: morten at nidelven-it.no, morten at nidelven-it.no > From: morten at nidelven-it.no > Subject: Order confirmation > Content-Type: text/plain; charset="utf-8" > X-Bogosity: No, tests=bogofilter, spamicity=0.000000, version=0.92.8 > > Thank you for your order, it is copied here for your convenience, and > we will process it shortly. > > Name: ?? > Phone: ?? > Email: morten at nidelven-it.no > Comments: asdf > """ > > but at least it doesn't raise any errors. > This is a method I have clipped from one of my projects. It should pretty much cover everything you would want to do while sending mails. def Workgroup_mailFormAction(self, to=None, cc=None, bcc=None, inReplyTo=None, subject=None, body='', attachments=None, mfrom=None, REQUEST=None): """ Sends a message. Many of the input parameters are not currently used, but can be used for skinning the functionlity. """ site_encoding = self._site_encoding() ################## # Create the message msg = Message() msg.set_payload(body, site_encoding) ##################################### # if attachment, convert to multipart # file fields are posted even if empty, so we need to remove those :-s if attachments is None: attachments = [] attachments = [a for a in attachments if a] if attachments: mimeMsg = MIMEMultipart() mimeMsg.attach(msg) for attachment in attachments: # Add the attachment tmp = email.message_from_string(str(attachment.headers)) filename = tmp.get_param('filename', 'Attachment', 'Content-Disposition') # clean up IE paths filename = filename[max(filename.rfind('/'), filename.rfind('\\'), filename.rfind(':') )+1:] contentType = tmp['Content-Type'] attach_part = Message() attach_part.add_header('Content-Type', contentType, name=filename) attach_part.add_header('Content-Disposition', 'attachment', filename=filename) attach_part.set_payload(attachment.read()) Encoders.encode_base64(attach_part) mimeMsg.attach(attach_part) msg = mimeMsg ######################## # set headers on message #### if to is None: to = [] if mfrom: to.append(mfrom) msg['From'] = mfrom msg['Reply-To'] = mfrom to = ','.join(to) if to: msg['To'] = to #### if cc is None: cc = [] cc = ','.join(cc) if cc: msg['Cc'] = cc #### if bcc is None: bcc = [] bcc = ','.join(bcc) if bcc: msg['Bcc'] = bcc #### msg['Date'] = self.ZopeTime().rfc822() # needed by some servers if inReplyTo: msg['In-Reply-To'] = inReplyTo msg['Subject'] = Header(subject, site_encoding) ################## # Send the message SMTPserver = self._mailhost() success = 0 try: cleaner = lambda adresses: [adress.strip() for adress in adresses.split(',') if adress.strip()] all_receivers = cleaner(to) + cleaner(cc) + cleaner(bcc) all_receivers = list(set(all_receivers)) if all_receivers: # only send if any recipients self._mailhost().send(str(msg), mto=all_receivers, mfrom=mfrom) success = 1 except: pass -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From rganesan at myrealbox.com Tue Nov 22 23:37:30 2005 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Wed, 23 Nov 2005 10:07:30 +0530 Subject: Why are there no ordered dictionaries? References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> <1132715742.672265.259740@o13g2000cwo.googlegroups.com> Message-ID: >>>>> bonono at gmail com writes: > what would be the definition of "sorted" and "ordered", before we can > go on ? Sorted would be ordered by key comparison. Iterating over such a container will give you the keys in sorted order. Java calls this a SortedMap. See http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html C++ STL map container is also a Sorted Associative container. See http://www.sgi.com/tech/stl/Map.html Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan | http://rganesan.blogspot.com From y.glodt at sitasoftware.lu Wed Nov 9 08:35:41 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 09 Nov 2005 14:35:41 +0100 Subject: append to non-existing list In-Reply-To: References: Message-ID: <4371FB2D.2090000@sitasoftware.lu> Juho Schultz wrote: > Yves Glodt wrote: >> Hello, >> >> if I do this: >> >> for row in sqlsth: >> ________pkcolumns.append(row[0].strip()) >> ________etc >> >> >> without a prior: >> >> pkcolumns = []; >> >> >> I get this error on first iteration: >> UnboundLocalError: local variable 'pkcolums' referenced before assignment >> >> I guess that's normal as it's the way python works...?!? >> >> My question is: Is there no way to append to a non existing list? >> >> I am lazy for declaring it first, IMHO it bloats the code, and (don't >> know if it's good to say that here) where I come from (php) I was used >> to not-needing it... >> >> >> regards, >> Yves > > You mean you want to type "pkcolumns" only once to keep your code short? > Would something like this be useful? > > pkcolumns = [row.strip() for row in sqlsth] I will look into this, maybe it's what I need, thanks! From fredrik at pythonware.com Wed Nov 23 03:21:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 09:21:59 +0100 Subject: Cmd Module References: <1132732095.960874.286370@g43g2000cwa.googlegroups.com> Message-ID: Godwin Burby wrote: > I was just curious about using the cmd module for building my > own command line interface. i saw a problem. The script is as follows: it helps if you include the code you were running, instead of some approximation of it. File "test", line 10 if passwd = 'godwin': print "You are a valid user" ^ SyntaxError: invalid syntax Traceback (most recent call last): File "", line 4, in ? NameError: name 'cmd' is not defined > The interpreter reports that the first argument to super should be a > type rather than a class object and for the do_login function it says > that function needs only one argument but two are given. I solved the > above errors by adding the following code: > > Cmd.__init__(self) > > def do_login(self,passwd='godwin') > > But i know that my first code should work without any problems or is > there a problem with it. super() only works for new-style classes. the second argument problem is because do_ methods are called with a second argument: >>> import cmd >>> help(cmd) Help on module cmd: ... 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method is passed a single argument consisting of the remainder of the line. ... (if you type "login", you get an empty string. if you type "login foo", you get the string "foo". etc). From python at rcn.com Sat Nov 19 23:28:40 2005 From: python at rcn.com (Raymond Hettinger) Date: 19 Nov 2005 20:28:40 -0800 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> Message-ID: <1132460920.666321.264290@f14g2000cwb.googlegroups.com> Gustav H?llberg wrote: > I tried finding a discussion around adding the possibility to have > optional underscores inside numbers in Python. This is a popular option > available in several "competing" scripting langauges, that I would love > to see in Python. > > Examples: > 1_234_567 > 0xdead_beef > 3.141_592 I suppose it could be done. OTOH, one could argue that most production code has no business hardwiring-in numerical constants greater than 999 ;-) From steve at REMOVETHIScyber.com.au Thu Nov 3 17:31:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 09:31:23 +1100 Subject: reading internet data to generate random numbers. References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> <11mj21gr6rjgc65@corp.supernews.com> <86ll06jr79.fsf@bhuda.mired.org> <4369B2CF.70201@REMOVEMEcyber.com.au> <11mkcg2l9d89qff@corp.supernews.com> Message-ID: On Thu, 03 Nov 2005 16:40:43 -0500, Peter Hansen wrote: > Steven D'Aprano wrote: >> On Thu, 03 Nov 2005 15:51:30 +0000, Grant Edwards wrote: >>> >>>I've never heard of anybody using the data as source of >>>entropy. >> >> Me neither, but the original poster did ask how to read every nth byte >> of "the Internet stream", so I assumed he had something like that in mind. > > And to think that if you'd just waited for the OP to explain what the > heck he meant by "the Internet stream", you'd have saved ever so much > time. ;-) Has he done so yet? I can't see it anywhere. -- Steven. From roy at panix.com Tue Nov 8 10:39:09 2005 From: roy at panix.com (Roy Smith) Date: Tue, 8 Nov 2005 15:39:09 +0000 (UTC) Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <98c1n1pjakk6huav7n1poou2d8kbskb5ah@4ax.com> Message-ID: Dave Hansen wrote: > Of course, I write _far_ more code in C than Python. But I've seen > enough bugs of the sort where someone wrote 1200000 when they meant > 12000000, that I see great value in being able to specify 12_000_000. I'll admit that being able to write 12_000_000 would be convenient. On the other hand, writing 12 * 1000 * 1000 is almost as clear. In C, the multiplication would be done at compile time, so it's not even any less efficient. I'm not sure how Python handles that, but if it turned out to be a serious run-time performance issue, it's easy enough to factor it out into something that's done once and stored. Bottom line, embedded no-op underscores in numbers would be nice (and, IHMO, should be added), but the lack of such a feature should not be used as an excuse to write such unreadable monstrosities as 12000000 in source code. Semi-related: see Jakob Nielsen's complaint about having to enter credit card numbers as 16-digit strings with no breaks on web forms (http://www.useit.com/alertbox/designmistakes.html, item #7, last bullet point). From mwm at mired.org Sat Nov 5 19:42:59 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 19:42:59 -0500 Subject: Using Which Version of Linux References: <861x1v72um.fsf@bhuda.mired.org> <11mqg4pml76r947@corp.supernews.com> Message-ID: <86y842sj1o.fsf@bhuda.mired.org> Grant Edwards writes: > On 2005-11-05, Mike Meyer wrote: >> "Programmer-friendly" is pretty vague. Gentoo is the only Linux distro >> I've run into (which excludes a *lot* of Unix distros) that I'd >> consider programmer friendly, because it doesn't split packages up >> into "user stuff" and "developer stuff". That means you have to >> install two packages instead of one if you want to build things >> against that software. On the other hand, it uses it's own "package" >> manager - emerge - so you can't take advantage of rpms/debs from other >> systems (or you couldn't last time I looked into it). It also installs >> the least amount of "bundled" software, which I consider a programmer >> friendly behavior. > I just switched one of my computers to gentoo, and I like it a > lot. It's very no-nonsense, but there are alot of available > packages and everything (so far) just works. However, it's not > for the impatient (or at least not for the poor and impatient). > Since it compiles packages from source, a full-featured desktop > install on a slow machine can take days to finish. This is one of the things I love about the *BSD systems. The package system is "two-headed". You an do pkg_add, and it'll act like yum or apt-get, and install binaries for the package and all the requirements for it. Or you can cd to /usr/ports/category/pkg-name and do "make install", and it will download, compile and install all the required software and the port you're building (I do that to change the isntalltion prefix on the packages). If you want to create customized packages, you just do "make package". I found creating a port (and hence package) to be much easier than creating a .deb or .rpm, but that may just be me. For real control, you can install the portupgrade package. That said, the author of the BSD ports system thinks the architecture is wrong. It handles the building, installation, fetching and requirements all by itself. He thinks the yum/apt-get approach, where one tool handles package installation duties, and another deals with requirements fetching is much saner. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From hcslmf at texlife.com Mon Nov 21 15:08:38 2005 From: hcslmf at texlife.com (brolewis) Date: 21 Nov 2005 12:08:38 -0800 Subject: Reading a subprocesses stdout on Windows Message-ID: <1132603718.835058.146620@z14g2000cwz.googlegroups.com> I have been trying for several weeks now to write a program that allows me to read the stdout of a process that I spawn and once I receive feedback, act appropriately. More specifically, I need to create an SSH tunnel using plink on Windows XP. Once the tunnel is successfully created, then I need to run my program over that tunnel. If there is an error in the creation of the tunnel, then I need to abort and warn the users. My needs are 'small' but I just lack the know-how to get it done. I need to be able to spawn off plink so that it can continue to run in the background without interferring with the flow of my program. However, I would like to get the feedback to know if/when a successful connection has been made so that I know the appropriate actions to take. In the past, I spawned off a process using os.spawnl set into a thread and would pause for 10 seconds to give plink time to connect. However, it probably goes without saying this is not the best solution by any stretch of the imagination. My old command was (with obviously fake data): os.spawnl(os.P_NOWAIT, 'plink', 'plink', 'someuser at somehost.com', '-N', '-L 111:200.200.200.200:7000') Then I would poll Windows to see if plink had started. If it hadn't started, I would raise an exception. However, there are plenty of times where plink starts but no connection is made. As with most questions like this one, any and all help would be greatly appreciated. Lewis From http Fri Nov 11 12:20:10 2005 From: http (Paul Rubin) Date: 11 Nov 2005 09:20:10 -0800 Subject: LARGE numbers References: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> <1131691903.961955.19950@o13g2000cwo.googlegroups.com> <1h5uqy3.sdzwkkuvu86mN%aleax@mail.comcast.net> <7xmzkbkw0j.fsf@ruckus.brouhaha.com> <1131729342.754040.316620@o13g2000cwo.googlegroups.com> Message-ID: <7xek5nt839.fsf@ruckus.brouhaha.com> casevh at comcast.net writes: > Python's native longs use Karatsuba multiplication with is O(n^1.585). > My early version of DecInt (BigDecimal) uses 4-way Toom-Cook ... Wow, cool! Thanks. From fredrik at pythonware.com Fri Nov 18 10:02:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Nov 2005 16:02:44 +0100 Subject: Adding through recursion References: <1132320167.127338.92460@g47g2000cwa.googlegroups.com> <1132324258.091428.287910@g44g2000cwa.googlegroups.com> Message-ID: martin.clausen at gmail.com wrote: > I still don't get it. I tried to test with x = 0 and found that to > work. How come since the value of y is right and it is printed right it > "turns into" None when returned by the return statement ? because you're not returning the value to the print statement; you're returning it to your own function, which throws it away. if you add "raise Exception" to the "x == 0" path, you get this traceback: $ python add.py 6 Traceback (most recent call last): File "add.py", line 10, in ? print add(2, 4) File "add.py", line 8, in add add(x, y) File "add.py", line 8, in add add(x, y) File "add.py", line 4, in add raise Exception Exception which shows that you're a couple of levels down when you find the right value. and since the "add(x, y)" call at line 8 throws away the result, the "print" statement at line 10 will never see it. From luca.bs at gmail.com Thu Nov 10 08:28:47 2005 From: luca.bs at gmail.com (LB) Date: 10 Nov 2005 05:28:47 -0800 Subject: ANN: P(x) 0.2 applet builder In-Reply-To: References: <86br0t6mtz.fsf@bhuda.mired.org> <1131610240.716331.50600@g14g2000cwa.googlegroups.com> Message-ID: <1131629327.452501.88460@o13g2000cwo.googlegroups.com> Sorry, I can only obtain a windows with caption: "VRML Console" and text: [ Info] Unable to open input file: http://www.mired.org/downloads/P(x)-0.2.tar.gz [ Info] Compilation error: Unrecognized header string ? LB From fredrik at pythonware.com Wed Nov 2 11:45:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Nov 2005 17:45:46 +0100 Subject: Python's website does a great disservice to the language References: <1130873528.812783.75600@g43g2000cwa.googlegroups.com> Message-ID: "CppNewB" wrote: > But the logos look like they were done in Paint that's probably why the designers won a prestigious design award for their: "...innovative letter designs and typographic experiments, which are testimony to their unconventional thinking about, and use of, existing software applications. By actually modifying the software they are able to escape the standard of existing digital letters. In doing so, their letter types show a kind of obstreperous mentality and sense of humour." a version of Paint that works on a Mac, an obstreperous mentality, and a sense of humour. what else do you need? From nephish at xit.net Mon Nov 7 10:04:24 2005 From: nephish at xit.net (nephish at xit.net) Date: 7 Nov 2005 07:04:24 -0800 Subject: need help extracting data from a text file Message-ID: <1131375863.977379.120620@f14g2000cwb.googlegroups.com> Hey there, i have a text file with a bunch of values scattered throughout it. i am needing to pull out a value that is in parenthesis right after a certain word, like the first time the word 'foo' is found, retrieve the values in the next set of parenthesis (bar) and it would return 'bar' i think i can use re to do this, but is there some easier way? thanks From venkatasubramanian at gmail.com Thu Nov 3 09:28:41 2005 From: venkatasubramanian at gmail.com (venk) Date: 3 Nov 2005 06:28:41 -0800 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: <1131028121.687069.295580@g43g2000cwa.googlegroups.com> Again (blink) quoting from the docs " For targets which are attribute references, the initial value is retrieved with a getattr() and the result is assigned with a setattr(). Notice that the two methods do not necessarily refer to the same variable. When getattr() refers to a class variable, setattr() still writes to an instance variable. For example: class A: x = 3 # class variable a = A() a.x += 1 # writes a.x as 4 leaving A.x as 3 " I felt a wee bit clear after going thru the doc... attribute referencing is not the same as searching the variable in the enclosing scopes.... But, i still feel the inconsistency... From luismgz at gmail.com Thu Nov 3 08:03:33 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 3 Nov 2005 05:03:33 -0800 Subject: Python for .NET and IronPython References: <1130979633.835814.251720@g47g2000cwa.googlegroups.com> Message-ID: <1131023013.509521.139620@g49g2000cwa.googlegroups.com> I just want to clarify that the above mentioned web site (www.ironpython.com) is no longer maintained. If you want to get updated information on IronPython, you should visit this site: www.gotdotnet.com/Workspaces/Workspace. aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742 Or the mailing list here: http://lists.ironpython.com/pipermail/users-ironpython.com/ By the way, the current version is 0.9.3 and it's advancing at a pretty fast pace towards version 1.0. Luis From masudtarek at gmail.com Mon Nov 14 17:04:40 2005 From: masudtarek at gmail.com (masudtarek at gmail.com) Date: 14 Nov 2005 14:04:40 -0800 Subject: Searching date and and time from a text file Message-ID: <1132005880.158423.45690@g43g2000cwa.googlegroups.com> Hi, I am new in Python programming. Can anybody give me any idea about how to detect more than one date and time (like 11/11/2005 , 10-12-2006, 12:30 etc) from a text file and keep them in a list. From spam4bsimons at yahoo.ca Tue Nov 8 11:40:14 2005 From: spam4bsimons at yahoo.ca (Brendan) Date: 8 Nov 2005 08:40:14 -0800 Subject: Newbie Alert: Help me store constants pythonically In-Reply-To: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> References: <1131294796.953860.187500@g49g2000cwa.googlegroups.com> Message-ID: <1131468014.050802.12690@g44g2000cwa.googlegroups.com> Thanks for all the suggestions everyone. After a bit of googling on the c.l.p. group, I see that building config files is one of those 'Everyone has a favourite way of doing it' types of problems, with lots of reimplementations. I should change the thread topic to "Yet Another Config File Question"! Based on my requirements (thanks again for helping me identify these), my config file should: a) store numbers, strings, bools, keyed dictionaries and un-keyed lists b) store nested structures of the above c) be language neutral, preferably well supported in other languages, and editors d) have a simple api in Python, preferably translating values to native types e) be validated when read I've checked out ConfigParser, ConfigObj, Pickle, PyYaml and gnossis.xml.serialize, and none meet all the above criteria (though they're all neat). So I've decide to use ...drumroll please.... plistlib ( http://svn.python.org/projects/python/trunk/Lib/plat-mac/plistlib.py ). Why plists? - I've got a simple api (readPlist(pathOrFile), writePlist(rootObject, pathOrFile) ) already installed with macPython - I have a dirt simple plist editor for knocking out the hundreds of config values I need ( http://homepage.mac.com/bwebster/plisteditpro.html ) - The file format is xml, which is well supported in all languages. - Since plists are the standard approach on the mac (though they aren't OS specific by definition), the XML schema is well documented (http://developer.apple.com/documentation/Darwin/Reference/ManPages/man5/plist.5.html), and shared with thousands of other apps, so I won't have to worry about obsolescence. So away I go. If anyone can suggest reasons I should avoid this approach, please let me know before I get too invested. Otherwise, this might be a reasonable avenue for standardizing Python. (I hope that doesn't draw to many flames :) Brendan. From aleax at mail.comcast.net Sat Nov 12 12:46:06 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 12 Nov 2005 09:46:06 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> Message-ID: <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> Paul Rubin wrote: > "The Eternal Squire" writes: > > Without copyright, how could one possibly earn a living writing a > > novel? > > This guy seems to be doing ok: http://craphound.com > His publishers are the only ones allowed to sell his novels commercially, > but you can download them all and print them out noncommercially for > your own personal enjoyment or to share with your friends. No obfuscation > is needed. One might also quip (not truthfully in Cory's specific case, I hasten to add!-) that many of today's novels are intrinsically obfuscated enough to need no further technological help on that front;-). Quips aside, the question is a sensible one to ask -- not as a rhetorical question, as TES apparently intended, of course, and not just about novels (many different creative endeavours may require different answers). The "novel" as a specific literary form is not that old, just a few centuries, but the issues were not very different for many other literary forms over the ages and cultures, and many different answers have been given or attempted. For example, Virgil was writing poems (epic and otherwise), not novels, but that's not very relevant to the question of how he made a living; the classic solution, in his case, was to find rich patrons willing to pay him to do so. Of course, there are obvious problems with this model... for example, Virgil was paid to write the Aeneid because his patrons liked its patriotism (as well as its towering artistic qualities), but a work with equally good art but an anti-patriotic ideology would have been much harder to monetize at that time (and also risked landing the author in the soup, as Ovid found out, but that's another issue, quite unrelated to monetization). Zooming forwards a couple of millennia, we see the model of "serialization" -- having the novel published in periodic installments by a magazine. Avid readers, we're told, crowded the piers of New York waiting for ship to land which carried the magazine with the latest installment of some Dickens novel -- and Dumas and Sue, in France, had fully comparable success in similar ways. At that time, copyright existed, in theory, but practically wasn't very well enforced (most particularly, I believe, in the USA, where the probability of a British publisher of actually enforcing a copyright was laughably low...) -- nevertheless, the reasonable cheapness of magazines coupled with the readers' urgency for the next installment let these authors earn a comfortable living anyway. Here, the problem is presumably that you need VERY popular novels for this to work -- but then, a tiny fraction of novelists actually make a comfortable living from just their novels, even with today's monetization approaches. Modern equivalent of serialization (publishing one chapter at a time on the web, the next chapter to come only if the author receives enough payment for the previous one) have been attempted, but without much success so far; however, the holy grail of "micropayments" might yet afford a rebirth for such a model -- if paying for a chapter was extremely convenient and cheap, enough people might choose to do so rather than risk the next chapter never appearing. Remember that, by totally disintermediating publishers and bookstores, a novelist may require maybe 1/10th of what the book would need to gross in stores, in order to end up with the same amount of cash in his or her pockets. One could go on for a long time, but the key point is that there may or may not exist viable monetization models for all sorts of endeavours, including the writing of novels, depending on a lot of other issues of social as well as legal structures. Let's not be blinded by one model that has worked sort of decently for a small time in certain sets of conditions, into believing that model is the only workable one today or tomorrow, with conditions that may be in fact very different. Alex From ahn1 at llnl.gov Wed Nov 30 19:14:41 2005 From: ahn1 at llnl.gov (ahn1 at llnl.gov) Date: 30 Nov 2005 16:14:41 -0800 Subject: A bug in struct module on the 64-bit platform? Message-ID: <1133396081.089848.252550@o13g2000cwo.googlegroups.com> Hi, I have a user who complained about how "struct" module computes C struct data size on Itanium2 based 64-bit machine. His first reproducer was -------------------------------------- #!/usr/local/bin/python import struct fmthead = '12id5i5d7id5i3di12i3di' fmtsize = struct.calcsize(fmthead) print fmthead,fmtsize -------------------------------------- And it prints 12id5i5d7id5i3di12i3di 292 And he further provided >>struct.calcsize('idi') 16 >>struct.calcsize('idid') 24 >>struct.calcsize('did') 20 In response to those, I created corresponding C struct and computed the data size using "sizeof" operation (gcc was used for compilation), but they don't seem to match. Is this a known problem? Best, -Dong From lycka at carmen.se Wed Nov 9 08:27:46 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 09 Nov 2005 14:27:46 +0100 Subject: how to modify code while debugging it without having to stop and then restart debugger In-Reply-To: References: Message-ID: python wrote: > so how can i use python to debug code and change that code without having to restart the code. I don't know how well the commercial GUIs, such as Wing IDE manage to handle debugging. Perhaps that's worth looking into. It's my impression that debugger support in Python is weaker than e.g. VB, because Python programmers don't need and use debuggers so much. I think there are several reasons for this: - It's easy to experiment with code in the interactive interpreter. - Python programs don't dump. There is rarely a need to put a breakpoint at some known safe place and single-step from there until it crashes, and then redo everything, trying to find at what place before the crash you really had your bug. You'll almost always get a controlled exception in Python. - The tracebacks you get when exceptions appear are very informative, and typically enough to spot the bugs more or less at once. I debugged python programs I've never seen before last night and today. There were maybe half a dozen bugs, and in all cases, the tracebacks showed me exactly what I needed to do to fix the problems at once. - Due to Python's expressiveness, typical Python programs are shorter and simpler than comparable programs written in other languages. If you have spaghetti code, you really need to single-step to understand what is going on. Python code is typically well structured. - With Python, it's common that people write unit tests using e.g. the unittest or doctest libraries. With a test driven approach as described in Extreme Programming, you run your tests very often, with small changes in the code between each test run. - With object-oriented programming, it's easier to structure your code so that each chunk of code (e.g. method) is easy to understand. In other words, the divide and conquer approach to problem solving works better. I guess another reason is that Microsoft has put a lot of money into making VB and friends user friendly. These products are very much geared into accomodating beginners, and a nice looking GUI has been a very high priority. For an open source tool such as Python, where the people who drive development are the people who need to use the tool, being beginner friendly isn't the top priority (even though Python has succeeded well in that regard anyway). Aspects such as stability and consistency in semantics is considered much more important. (VB has a prettier GUI, but Python is a much prettier language...) From nephish at xit.net Wed Nov 2 13:53:13 2005 From: nephish at xit.net (nephish at xit.net) Date: 2 Nov 2005 10:53:13 -0800 Subject: question about urllib and parsing a page Message-ID: <1130957593.322210.185450@o13g2000cwo.googlegroups.com> hey there, i am using beautiful soup to parse a few pages (screen scraping) easy stuff. the issue i am having is with one particular web page that uses a javascript to display some numbers in tables. now if i open the file in mozilla and "save as" i get the numbers in the source. cool. but i click on the "view source" or download the url with urlretrieve, i get the source, but not the numbers. is there a way around this ? thanks From exarkun at divmod.com Tue Nov 8 20:59:05 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 8 Nov 2005 20:59:05 -0500 Subject: Goto XY In-Reply-To: <1131499644.561039.16420@g14g2000cwa.googlegroups.com> Message-ID: <20051109015905.10365.159452505.divmod.quotient.5449@ohm> On 8 Nov 2005 17:27:24 -0800, ale.of.ginger at gmail.com wrote: >Is there some command in python so that I can read a key's input and >then use a gotoxy() function to move the cursor on screen? e.g.: >(psuedo-code) > >When the right arrow is pushed, cursor gotoxy(x+1,y) > You can uses curses for this, on platforms where curses is supported. Twisted Conch also includes some terminal manipulation code. Both are basically POSIX-only, though Twisted might expand to work with win32 at some point. At some point in the past I think there was a win32 curses port, but I don't think it's maintained anymore. Jean-Paul From tuvas21 at gmail.com Fri Nov 4 12:47:03 2005 From: tuvas21 at gmail.com (Tuvas) Date: 4 Nov 2005 09:47:03 -0800 Subject: Tkinter- New Window Message-ID: <1131126422.958411.66860@f14g2000cwb.googlegroups.com> Is there a way to make a new window pop up using Tkinter? I have some functions that require more data in my interface than I have space for, and would like to be able to pop up a new window to request this information. Thanks! From dcrespo at gmail.com Tue Nov 8 10:15:44 2005 From: dcrespo at gmail.com (dcrespo) Date: 8 Nov 2005 07:15:44 -0800 Subject: XML GUI In-Reply-To: <1131461919.243378.231750@g43g2000cwa.googlegroups.com> References: <1131457704.275657.237970@g49g2000cwa.googlegroups.com> <1131461186.068052.81270@g14g2000cwa.googlegroups.com> <1131461562.995828.141580@g49g2000cwa.googlegroups.com> <1131461919.243378.231750@g43g2000cwa.googlegroups.com> Message-ID: <1131462944.444302.34720@f14g2000cwb.googlegroups.com> www.wxpython.org Look for the Docs and examples file. It has a full list of interesting examples, including the way for loading GUIs from xrc files. The xrc files can be generated from DialogBlocks, XRCEditor, wxDesigner. Daniel From donn at u.washington.edu Wed Nov 30 17:19:41 2005 From: donn at u.washington.edu (Donn Cave) Date: Wed, 30 Nov 2005 14:19:41 -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> <1133368487.648595.50950@z14g2000cwz.googlegroups.com> <86sltdn6ma.fsf@bhuda.mired.org> Message-ID: In article <86sltdn6ma.fsf at bhuda.mired.org>, Mike Meyer wrote: > "Harald Armin Massa" writes: > >>Faster than assembly? LOL... :) > > why not? Of course, a simple script like "copy 200 bytes from left to > > right" can be handoptimized in assembler and run at optimum speed. > > Maybe there is even a special processor command to do that. > > Chances are, version 1 of the system doesn't have the command. Version > 2 does, but it's no better than the obvious hand-coded loop. Version 3 > finally makes it faster than the hand-coded loop, if you assume you > have the instruction. If you have to test to see if you can use it, > the hand-coded version is equally fast. Version 4 makes it faster even > if you do the test, so you want to use it if you can. Of course, by > then there'll be a *different* command that can do the same thing,j and > is faster in some conditions. > > Dealing with this in assembler is a PITA. If you're generating code on > the fly, you generate the correct version for the CPU you're running > on, and that's that. It'll run at least as fast as hand-coded > assembler on every CPU, and faster on some. Actually I think the post you quote went on to make a similar point. I read yesterday morning in the paper that the Goto Basic Linear Algebra Subroutines, by a Mr. Kazushige Goto, are still the most efficient library of functions for their purpose for use in supercomputing applications. Apparently hand-optimized assembler for specific processors. http://seattlepi.nwsource.com/business/250070_goto29.html (actually from the NY Times, apparently) Donn Cave, donn at u.washington.edu From pythonnew at gmail.com Sat Nov 12 23:15:45 2005 From: pythonnew at gmail.com (Ben Bush) Date: Sat, 12 Nov 2005 20:15:45 -0800 Subject: the button of cancel Message-ID: <8c11e4350511122015l63fc54e1md0e5a1c1a3cf6904@mail.gmail.com> When I click the button of cancel, I got the follwoing message. I want to see "Goodbye" on the console screen. What to do? Traceback (most recent call last): File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\py\use\whileprint.py", line 8, in ? num = input( "Be sure to enter a value between 1 and 100: " ) File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\app.py", line 368, in Win32Input return eval(raw_input(prompt)) File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\app.py", line 363, in Win32RawInput raise KeyboardInterrupt, "operation cancelled" KeyboardInterrupt: operation cancelled num = input( "Enter a number between 1 and 100: " ) while num < 1 or num > 100: print "Oops, your input value (", num, ") is out of range." num = input( "Be sure to enter a value between 1 and 100: " ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bonono at gmail.com Thu Nov 24 21:22:11 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 18:22:11 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: Message-ID: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> Christoph Zwerschke wrote: > jepler at unpythonic.net schrieb: > > You can already get a set from a dictionary's keys in an efficient manner: > >>>>l = dict.fromkeys(range(10)) > >>>>set(l) > > Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > > Good point. I expected that set(l) = set(l.items()) and not > set(l.keys()), but the latter would not work with mutable values. See > discussion with Martin. puzzled. items() return tuples which I believe can be element of set ? Or I misread you ? From iainking at gmail.com Mon Nov 7 11:43:12 2005 From: iainking at gmail.com (Iain King) Date: 7 Nov 2005 08:43:12 -0800 Subject: need help extracting data from a text file In-Reply-To: <1131379939.695158.298640@g47g2000cwa.googlegroups.com> References: <1131375863.977379.120620@f14g2000cwb.googlegroups.com> <1131378550.887946.127680@g43g2000cwa.googlegroups.com> <1131379939.695158.298640@g47g2000cwa.googlegroups.com> Message-ID: <1131381792.217882.248520@z14g2000cwz.googlegroups.com> nephish at xit.net wrote: > this is cool, it is only going to run about 10 times a day, > > the text is not written out like foo(bar) its more like > foo blah blah blah (bar) > then I guess you worked this out, but just for completeness: keywordPos = textfile.find("foo") start = textfile.find("(", keywordPos) end = textfile.find(")", start) value = textfile[start:end] Iain From martin at v.loewis.de Wed Nov 23 19:25:51 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Nov 2005 01:25:51 +0100 Subject: Embedding a CPython Script engine in a .NET application. In-Reply-To: References: Message-ID: <43850890$0$25854$9b622d9e@news.freenet.de> Carl Waldbieser wrote: > Has anyone had any experience embedding a CPython engine in a .NET > application? In the COM/ActiveX world, it was pretty easy to use Mark > Hammond's win32 modules to create a script engine component that you could > expose other COM objects to, but I was not sure how I would go about doing > something similar in a .NET environment. I don't have experience with this specific problem, but in general, .NET is really good at calling COM objects (in fact, this was historically the sole reason for creating .NET: to make COM better usable). So just import, in VS.NET, the Python interpreter to your project (Add Reference), and use the C# functions that the COM interop code gives you. Regards, Martin From blahman Fri Nov 4 06:06:02 2005 From: blahman (blah@blah.blah) Date: Fri, 04 Nov 2005 05:06:02 -0600 Subject: Fork() and exec() dont work Message-ID: i m using Windows XP, and by tomorrow i will have have fedora core installed too. the problem is, when i use these "fork() and exec()" my windows doesnt do anything, python gives an error about the module, the kind of error when u know u r wrong. is it because these commands work on linux? if so, is it better for me to stick with fedora for my python programs or use windows? -- * Posted with NewsLeecher v3.0 Beta 7 * http://www.newsleecher.com/?usenet From apardon at forel.vub.ac.be Fri Nov 4 03:35:28 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 08:35:28 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: Op 2005-11-03, Magnus Lycka schreef : > Antoon Pardon wrote: >> Op 2005-11-03, Steven D'Aprano schreef : >> >> >>>>There are two possible fixes, either by prohibiting instance variables >>>>with the same name as class variables, which would allow any reference >>>>to an instance of the class assign/read the value of the variable. Or >>>>to only allow class variables to be accessed via the class name itself. >>> >>>There is also a third fix: understand Python's OO model, especially >>>inheritance, so that normal behaviour no longer surprises you. >> >> >> No matter wat the OO model is, I don't think the following code >> exhibits sane behaviour: >> >> class A: >> a = 1 >> >> b = A() >> b.a += 2 >> print b.a >> print A.a >> >> Which results in >> >> 3 >> 1 > > On the other hand: > > >>> class C: > ... a = [1] > ... > >>> b=C() > >>> b.a += [2] > >>> b.a > [1, 2] > >>> C.a > [1, 2] > > I can understand that Guido was a bit reluctant to introduce > += etc into Python, and it's important to understand that they > typically behave differently for immutable and mutable objects. All fine by me. I won't be using python any less because of this, because I use class variable very little and you can avoid this problem by avoiding instance that shadow class variables and always refer to class variables by class name. But that doesn't mean we should consider this kind of behaviour as it should be, just because it is in python. -- Antoon Pardon From fredrik at pythonware.com Tue Nov 29 04:36:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Nov 2005 10:36:00 +0100 Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org><8664qcv6i5.fsf@bhuda.mired.org><7x64qcii9o.fsf@ruckus.brouhaha.com> <1133213623.305032.232740@z14g2000cwz.googlegroups.com> Message-ID: Paddy wrote: > I would consider > t = ([1,2], [3,4]) > to be assigning a tuple with two list elements to t. > The inner lists will be mutable but I did not know you could change the > outer tuple and still have the same tuple object. you can't. but since hash(tuple) is defined in terms of map(hash, t), the resulting tuple is not hashable. also see: http://effbot.org/zone/python-hash.htm#tuples From grante at visi.com Tue Nov 22 20:33:06 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 23 Nov 2005 01:33:06 -0000 Subject: hex string to hex value References: <1132701750.841307.97890@g14g2000cwa.googlegroups.com> <1132703785.938991.11090@z14g2000cwz.googlegroups.com> Message-ID: <11o7hmisa60283e@corp.supernews.com> On 2005-11-23, tim wrote: >>>>>int(hex(m),16) >>>>> >>>>> >>66 >> >>Fredrik Lundh's solution works if the hex string starts with "0x" >>(which it will when the string is created with the hex function). >> > aren't you converting from a hex string to a decimal value here? No. He's converting from a hex string to an integer object. -- Grant Edwards grante Yow! It's OKAY --- I'm an at INTELLECTUAL, too. visi.com From bokr at oz.net Sat Nov 12 05:27:16 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 12 Nov 2005 10:27:16 GMT Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131627394.890394.200070@g44g2000cwa.googlegroups.com> <4373bcbc.150778327@news.oz.net> <1131675601.931303.177890@g14g2000cwa.googlegroups.com> <1h5tz2c.1lmc7tlk7ge03N%aleax@mail.comcast.net> <43755c74.257202327@news.oz.net> <1131765889.428337.77320@g14g2000cwa.googlegroups.com> Message-ID: <4375b5d8.280086172@news.oz.net> On Sat, 12 Nov 2005 08:12:43 +0100, Peter Otten <__peter__ at web.de> wrote: >bonono at gmail.com wrote: > >> However, I found something interesting which I don't quite understand : >> >> list((x for x in [1,2,3] if x<2 or stop())) works >> >> but >> >> a = [ x for x in [1,2,3] if x <2 or stop() ] doesn't. > >Here's how Carl Banks explained it to me when Bengt came up with this >trick. > >http://mail.python.org/pipermail/python-list/2005-April/274051.html > Thanks (I guess, or is guilt being pinned? ;-) for the attribution. BTW, that thread is easier to follow on google: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ca7ba6ca9d70d24c/fdcadd1e3eba61cd But googling shows I wasn't the first to come up with iter([]).next() to raise Stopiteration. Usual suspect: http://groups.google.com/group/comp.lang.python/browse_thread/thread/41495e4f5d3e1c2a/84c158ff18d08ece#84c158ff18d08ece It probably stuck subconsciously in my mind and just came back when I wanted a StopIteration expression for terminating a generator expression. Regards, Bengt Richter From steve at REMOVETHIScyber.com.au Thu Nov 3 10:00:52 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 02:00:52 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> Message-ID: On Thu, 03 Nov 2005 12:50:51 +0000, Antoon Pardon wrote: >>> I don't care what should be different. But a line with only one >>> referent to an object in it, shouldn't be referring to two different >>> objects. >> >> It doesn't. > > Yes it does. If the b.a refers to the instance variable, then an > AttributeError should be raised, because the instance variable doesn't > exist yet, so you can't add two to it. Then you don't approve of inheritance? That's fine, it is your choice, but as far as I know, all OO languages include inheritance. I can't imagine why you would want this to happen: py> class BetterList(list): ... def wobble(self): ... """Wobble a list.""" ... pass ... py> L = BetterList((1, 2, 3)) py> L.sort() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'BetterList' object has no attribute 'sort' (It just goes to show that Explicit is better than Implicit is not *always* true.) > If the b.a refers to the class variable then two should be added to it. > > Neither happens instead we get some hybrid in which an instance varible > is created that gets the value of class variable incrented by two. Which is precisely the expected behaviour. First you fetch the instance attribute, which by the rules of inheritance falls back to the value of the class attribute if it doesn't yet exist (which, in this specific case, it does not). Then you add two to it, and store the result in the instance attribute. You can't increment the object 1 because it is immutable. >>> In the line: b.a += 2, the b.a should be refering to the class >>> variable or the object variable but not both. So either it could raise >>> an attribute error or add two to the class variable. >> >> It does exactly what you say. It adds 2 to the a *instance variable* of >> the object instance in 'b'. > > There is no instance variable at that point. How can it add 2, to > something that doesn't exist at the moment. By the standard rules of inheritance. -- Steven. From cfajohnson at gmail.com Wed Nov 9 00:30:21 2005 From: cfajohnson at gmail.com (Chris F.A. Johnson) Date: Wed, 9 Nov 2005 00:30:21 -0500 Subject: Goto XY References: Message-ID: On 2005-11-09, Jean-Paul Calderone wrote: > On Tue, 8 Nov 2005 22:33:47 -0500, "Chris F.A. Johnson" wrote: >> [snip] >> >> To read a single keystroke, see Claudio Grondi's post in the >> thread "python without OO" from last January. >> >> Function and cursor keys return more than a single character, so >> more work is required to decode them. The principle is outlined in >> ; >> the code there is for the shell, but translating them to python >> should be straightforward. I'll probably do it myself when I have >> the time or the motivation. >> > > Like this? > > http://cvs.twistedmatrix.com/cvs/trunk/twisted/conch/insults/insults.py?view=markup&rev=14863 More or less; probably much less. -- Chris F.A. Johnson | Author: | Shell Scripting Recipes: Any code in this post is released | A Problem-Solution Approach, under the GNU General Public Licence | 2005, Apress From bill.mill at gmail.com Thu Nov 10 16:29:53 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu, 10 Nov 2005 16:29:53 -0500 Subject: Python obfuscation In-Reply-To: <1131640817.644852.7070@g44g2000cwa.googlegroups.com> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> Message-ID: <797fe3d40511101329l73cfdd9at6099306e03a710a7@mail.gmail.com> On 10 Nov 2005 08:40:17 -0800, Ben Sizer wrote: > Alex Martelli wrote: > > > This is (a minor) one of the many reasons that make webservices the way > > of the future (hey, even *MSFT* noticed that recently, it seems...). > > But they are not suitable for all applications, and probably never will > be. > Your only solution, then, is to write unpopular code. Because, as Alex said, it will otherwise be broken into. Let's look at two very popular pieces of code: Half-Life 2 and Windows XP. How are they secured? Previous version of these software products used sophisticated client-side programming to try and be secure, but the security was nonexistant. Users share keys and cracks with each other. Now, both of these programs require verification (phone and/or web) to be used. The only truly secure method of assuring that they're not used in ways you don't intend is to require the user to contact you to use it, and that's a deal with the devil. One you might need to make if security is that important to you, as Microsoft and Valve have decided it is, but it's a deal with the devil nonetheless. Peace Bill Mill bill.mill at gmail.com From pierre_dot_barbier at _nospam_cirad.fr Mon Nov 14 12:20:58 2005 From: pierre_dot_barbier at _nospam_cirad.fr (Pierre Barbier de Reuille) Date: Mon, 14 Nov 2005 18:20:58 +0100 Subject: Not enough arguments for format string In-Reply-To: References: Message-ID: <4378c758$0$29617$636a15ce@news.free.fr> Kevin Walzer a ?crit : > I'm getting an error in a Python script I'm writing: "not enough > arguments for format string." The error comes at the end of the > os.system command, referenced below. Any ideas? > > --- > > import EasyDialogs > import os > import sys > > > password = EasyDialogs.AskPassword("To launch Ethereal, please enter > your password:") > binpath = os.path.join(os.path.dirname(sys.argv[0]), > '/opt/local/bin/ethereal') > > os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export > DISPLAY; echo %s | sudo -S %s; sudo -k' %password %binpath) > > TypeError: not enough arguments for format string > > Well, just try : os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export DISPLAY; echo %s | sudo -S %s; sudo -k' % (password, binpath) ) The reason is, you have 2 "%s" in yor string, thus after the "%" operator, you need a 2-element tuple ! If you have either more or less element, you'll get a TypeError ! In your code above you put a single element ... Pierre From enas_khalil at yahoo.com Mon Nov 14 18:09:23 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Mon, 14 Nov 2005 15:09:23 -0800 (PST) Subject: how to convert between type string and token Message-ID: <20051114230923.42243.qmail@web30505.mail.mud.yahoo.com> hello all when i run the code : # -*- coding: cp1256 -*- from nltk.tagger import * from nltk.corpus import brown from nltk.tokenizer import WhitespaceTokenizer # Tokenize ten texts from the Brown Corpus train_tokens = [] xx=Token(TEXT=open('fataha2.txt').read()) WhitespaceTokenizer().tokenize(xx) for l in xx: train_tokens.append(l) #Initialise and train a unigram tagger mytagger = UnigramTagger(SUBTOKENS='WORDS') for tok in train_tokens: mytagger.train(tok) #Once a UnigramTagger has been trained, the tag() method can be used to tag new text: text_token = Token(TEXT="????? ??? ?? ????????") WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token) mytagger.tag(text_token) print 'The first example : Using Unigram Tagger the reseults are : ' print acc = tagger_accuracy(mytagger, train_tokens) print ' With Accuracy :Accuracy = %4.1f%%,' % (100 * acc) i got the following error : Traceback (most recent call last): File "F:\MSC first Chapters\unigramgtag1.py", line 14, in -toplevel- for tok in train_tokens: mytagger.train(tok) File "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py", line 324, in train assert chktype(1, tagged_token, Token) File "C:\Python24\Lib\site-packages\nltk\chktype.py", line 316, in chktype raise TypeError(errstr) TypeError: Argument 1 to train() must have type: Token (got a str) please i want a help on how to recover this error , in other words how can i convert between type string and token , as im still new in python thanks in advance --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gdamjan at gmail.com Tue Nov 1 08:12:05 2005 From: gdamjan at gmail.com (Damjan) Date: Tue, 01 Nov 2005 14:12:05 +0100 Subject: cx_Oracle, is anything selected? References: <3snp20Foku05U1@uni-berlin.de> Message-ID: >> Is there a way to see if the SELECT in cx_Oracle didn't return anything? >> I want to optimize the situation when the number of selected rows is >> zero. Is select count(*) the only option, seems inefficient? > > I don't understand your problem - if your select doesn't return > anything, the fetch* methods on the cursor will tell you if there is any > data to expect at all. Additionally there is teh rowcount-property that > holds the number of rows the last execute* yielded. This is a simplification of the program c = db.cursor() while 1: c.execute('select ....') smtp = SMTP(MAIL_HOST, 25, 'localhost') for address, subject, body in c: smtp.sendmail(....) smtp.quit() time.sleep(60) now if the select doesn't return any rows, there's no need to connect to the mail server. I'd like to avoid that unnecessary step. c.rowcount will not give me the number of rows selected, it will only give me the number of rows already fetched. -- damjan From fredrik at pythonware.com Thu Nov 24 01:51:55 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Nov 2005 07:51:55 +0100 Subject: Why is dictionary.keys() a list and not a set? References: <1132802380.246858.151330@g44g2000cwa.googlegroups.com><1132803762.570118.253770@o13g2000cwo.googlegroups.com> <86y83ezn3t.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Backwards compatability. The guarantee on the order of keys() and > values() predates items() (and iteritems()). according to the SVN repository, the type originally had "keys" and "has_key" only. "values" and "items" were both added in the same checkin (may 1993). performance is of course another aspect; if you *need* two parallel lists, creating a list full of tuples just to pull them apart and throw them all away isn't exactly the most efficient way to do things. (if performance didn't matter at all, we could get rid most dictionary methods; "iterkeys", "in", and locking should be enough, right?) > Maybe dropping the guarantee should be considered for P3K, on the off > chance that either keys or values could be made faster at some point > in the future. But I don't see it as a big deal. the guarantee only means that the type must use the same algorithm to traverse the dictionary data structure for both "keys" and "values". I'm not aware of any dictionary algorithm that doesn't maintain a link between keys and values, so that's not really much of a restriction... From fredrik at pythonware.com Sat Nov 12 06:14:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Nov 2005 12:14:31 +0100 Subject: about widget construction kit References: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com><1d987df30511111400m19f02d25had206df638c1bc0a@mail.gmail.com><1131753997.446010.167410@f14g2000cwb.googlegroups.com> <1d987df30511111632l350105bbo51e2f9620a156793@mail.gmail.com> Message-ID: Shi Mu wrote: > I tried again and got the follwoing message: > *** cannot find Tcl/Tk headers and library files > change the TCL_ROOT variable in the setup.py file > but i have already installed TCL under python23 hmm. I still think it would be easier if you used a prebuilt version, like everyone else. (if you insist on using an old source release instead of the latest binaries, follow the instructions, and make sure the TCL_ROOT variable points to the location of the Tcl/Tk development libraries (the directory that con- tains Tcl's "include" and "lib" directories, that is)) From jeremyvoros at gmail.com Wed Nov 16 11:51:06 2005 From: jeremyvoros at gmail.com (jeremyvoros at gmail.com) Date: 16 Nov 2005 08:51:06 -0800 Subject: Python, Linux, Desktop Environment Message-ID: <1132159865.965080.150530@z14g2000cwz.googlegroups.com> So, I've written my first GUI app in python. I've turned it into a binary .exe and .app that runs on Windows and Mac respectively, but on my Linux box, where I wrote the thing, I still have to drop to the command line and ./myscript.py. What can I do to make it a "click and run" sort of application in KDE or Gnome on Linux? From james at colannino.org Thu Nov 10 16:32:08 2005 From: james at colannino.org (James Colannino) Date: Thu, 10 Nov 2005 13:32:08 -0800 Subject: Stopping Execution Message-ID: <4373BC58.7050900@colannino.org> Hey everyone. I remember from my C programming that I can either use the exit() or return() functions to end execution of the main code block. My question is, is there a way for me to do this in Python? I know there has to be, but I can't for the life of me figure out what it is. The reason I ask is that I need to conditionally end a script I'm writing at various places. Thanks in advance. James -- My blog: http://www.crazydrclaw.com/ My homepage: http://james.colannino.org/ "A well regulated militia being necessary to the security of a free state, THE RIGHT of the people to keep and bear arms SHALL NOT BE INFRINGED." --United States Constitution, Second Ammendment From jmdeschamps at gmail.com Mon Nov 7 12:52:17 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 7 Nov 2005 09:52:17 -0800 Subject: Python doc problem example: gzip module (reprise) In-Reply-To: References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> <7x4q6q7f6b.fsf@ruckus.brouhaha.com> <86hdaqsfjo.fsf@bhuda.mired.org> <7x3bmafrip.fsf@ruckus.brouhaha.com> <86d5lescfd.fsf@bhuda.mired.org> <7x8xw2ea4e.fsf@ruckus.brouhaha.com> <436dc164.259807483@news.oz.net> <1131280114.971847.125580@g43g2000cwa.googlegroups.com> Message-ID: <1131385937.297238.166850@z14g2000cwz.googlegroups.com> (gulp! red-in-the-face) yes Steve, I meant "gist", sorry if I offended anyone, specially Fredrik since I was referring to the 'substance' of his post...certainly not as if it were a 'joke' . Jean-Marc From jmdeschamps at gmail.com Wed Nov 23 16:52:00 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 23 Nov 2005 13:52:00 -0800 Subject: moving mouse? In-Reply-To: References: Message-ID: <1132782720.106349.84050@g43g2000cwa.googlegroups.com> dado wrote: > dado wrote: > > I'm implementing a "self-tutorial" into my app, > > and wondering if there's a way of moving a mouse > > cursor on command? probably using sys,os modules? > > I also figured this would be useful for making > 'remote desktop' kinda thing... Naturally, you can always implement a simulation of this yourself in most GUI tools you would be using. I guess the complexity, thoroughness of your tutorial may mean that its unfeasable, business wise, but technologically it doesn't seem like rocket science... From jorg at neoplex.org Tue Nov 8 07:33:12 2005 From: jorg at neoplex.org (=?ISO-8859-1?Q?Jorg_R=F8dsj=F8?=) Date: Tue, 08 Nov 2005 13:33:12 +0100 Subject: os.path.getmtime on winXP In-Reply-To: <4370805e.439769895@news.oz.net> References: <43704c83@news.broadpark.no> <43706983.433918702@news.oz.net> <437074e8$1@news.broadpark.no> <4370805e.439769895@news.oz.net> Message-ID: <43709b35$1@news.broadpark.no> Bengt Richter wrote: > By 'getmtime' you mean os.path.getmtime(fer_shure_or_absolute_path_to_file) right? > Doesn't that get you an integer number of seconds? What GUI or win32file is showing you > that integer so you see a 3600 sec difference? Or how are you seeing it? > > Could you paste an example of this difference from an example on your screen? > I don't think I am understanding ;-) ... urk, it's late ;-/ (Btw: thanks for the interest.) Step by step example: [I do of cource not modify the foo.py-file at any time during the testing.] With the system-date set to the 8th of november(no dst) I run the following os.path.getmtime('spam.py'), and get 1045578240 as the result. With the system-date set to the 8th of october(dst) I run the following os.path.getmtime('spam.py'), and get 1045581840 as the result. This is what boggles my mind. These numbers should be the same -- right? Not offsett by 3600. On both dates, calling Windows win32file.GetFileTime (from the Python Win32 Extensions) gives me the time 02/18/03 14:24:00 -- i.e. the same both before and after setting the time. I have not looked at the source to either win32file.GetFileTime or os.path.getmtime, but I should think that they should both call the same underlying Windows-function. I hope this makes it more clear. Any idea why this happens? regards Jorg R?dsj? From __peter__ at web.de Sat Nov 26 03:18:58 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Nov 2005 09:18:58 +0100 Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <1132708265.941224.186550@g44g2000cwa.googlegroups.com> Message-ID: David Isaac wrote: > "Peter Otten" <__peter__ at web.de> wrote in message > news:dm3uj4$kko$02$1 at news.t-online.com... >> I'd rather have a second look whether the test is really needed. > > That's too obscure of a hint. > Can you be a bit more explicit? > Here's an example (below). > You're saying I think that most of it is unnecessary. >From the Zen of Python: "Special cases aren't special enough to break the rules." I think that the test for an empty iterator makes ireduce() unintuitive. Try asking someone who has not followed the discussion what list(ireduce(add, [], 42)) might produce, given that list(ireduce(add, [1], 42)) --> [43] list(ireduce(add, [1, 2], 42)) --> [43, 45] list(ireduce(add, [])) --> [] list(ireduce(add, [1])) --> [1] list(ireduce(add, [1, 2])) --> [1, 3] I suspect that [42] will be a minority vote. Peter From http Tue Nov 8 16:20:48 2005 From: http (Paul Rubin) Date: 08 Nov 2005 13:20:48 -0800 Subject: How to convert a number to hex number? References: <1131442115.025438.326670@g49g2000cwa.googlegroups.com> <1131464101.546746.107110@g47g2000cwa.googlegroups.com> <7xmzkfrum1.fsf@ruckus.brouhaha.com> Message-ID: <7xhdamygy7.fsf@ruckus.brouhaha.com> Steve Holden writes: > > Try hex(33**33). > > You're usually smarter than this, or am I missing some joke? > > >>> hex(33*33) > '0x441' You used only one * (multiplication), I used two *'s (exponentiation). >>> hex(33**33) '0x5857366DCE0162CB5DDCD1BF0FC7C03A6438304421L' From OurLab at gmail.com Tue Nov 1 08:21:55 2005 From: OurLab at gmail.com (Alex) Date: 1 Nov 2005 05:21:55 -0800 Subject: Pickling and unpickling inherited attributes In-Reply-To: References: <1130713951.953157.270130@g14g2000cwa.googlegroups.com> Message-ID: <1130851315.487444.205760@g47g2000cwa.googlegroups.com> Thanks to both Alex Martelli and Steve Holden.. We need __slots__ for other reasons, too long to explain, but basically to prevent assignment of extra attributes. I ended up changing child classes this way: def __getstate__(self): return(Parent.__getstate__(self), self.C) def __setstate__(self, data): Parent.__setstate__(self, data[0]) self.C=data[1:] This seems to work fine. From jorg at neoplex.org Tue Nov 8 04:49:56 2005 From: jorg at neoplex.org (=?ISO-8859-1?Q?Jorg_R=F8dsj=F8?=) Date: Tue, 08 Nov 2005 10:49:56 +0100 Subject: os.path.getmtime on winXP In-Reply-To: <43706983.433918702@news.oz.net> References: <43704c83@news.broadpark.no> <43706983.433918702@news.oz.net> Message-ID: <437074e8$1@news.broadpark.no> Bengt Richter wrote: > How did you format the number you got from os.path.getmtime? I'm not doing any formating at all. I am just looking at the numbers of seconds since epoch. Which is what makes it so strange. > You might want to try some of the above. I'll do that. At the moment I'm looking at the difference between localtime and gmtime to see if my computer is in dst. If it is not, I just add 3600 seconds to the result from os.path.getmtime -- which then should give consistent results. > If you actually created/modified files just before and after the DST change > and saw an extra hour difference instead of the time between the two actions, > then maybe I'd look into whether the OS has some perverse option to use local DST > time to record in the file stat info, but that's hard to believe. More likely someone > is messing with with raw file time setting, like touch. Don't have it handy to see > what DST assumptions it makes if any. The files I am testing with have not been modified for a long time. Windows reports the modified date as being the same, no matter what I do (both through the gui, and through win32file). And they all show the same strange 3600 sec difference with/without dst when I call getmtime on them. -jorg From andipet at gmail.com Wed Nov 16 12:14:46 2005 From: andipet at gmail.com (Andi Petculescu) Date: Wed, 16 Nov 2005 11:14:46 -0600 Subject: numarray / gcc woes on Darwin Message-ID: Hi all, I am a new convert to Mac OSX. I want to start using python under darwin and I need to install numarray. I've downloaded and extracted "numarray-1.4.1" in the python folder, installed gcc 4.0 from the OSX disc. When I run "python setup.py install" i still get an error message saying that gcc cannot be found. If I go to /usr/bin, "gcc" is in there, along with "gcc-4.0". If I query "which gcc" it says that there's no gcc present, but if I query "which gcc-4.0" it finds it right away. Any help is appreciated! Thanks a lot, -Andi -------------- next part -------------- An HTML attachment was scrubbed... URL: From mirandacascade at yahoo.com Sat Nov 19 20:50:43 2005 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 19 Nov 2005 17:50:43 -0800 Subject: PATH environment variable Message-ID: <1132451443.807757.251540@g43g2000cwa.googlegroups.com> O/S: Win2K Vsn of Python:2.4 Based on a search of other posts in this group, it appears as though os.environ['PATH'] is one way to obtain the PATH environment variable. My questions: 1) is it correct that os.environ['PATH'] contains the PATH environment variable? 2) are there other ways to obtain the PATH environment variable? if so, is one way of obtaining the PATH environment variable preferable to another way? From steve at REMOVETHIScyber.com.au Tue Nov 15 17:28:13 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 16 Nov 2005 09:28:13 +1100 Subject: Default method arguments References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a1e7a$0$6131$636a15ce@news.free.fr> Message-ID: On Tue, 15 Nov 2005 18:44:23 +0100, bruno at modulix wrote: > Another solution to this is the use of a 'marker' object and identity test: > > _marker = [] > class A(object): > def __init__(self, n): > self.data =n > def f(self, x = _marker): > if x is _marker: > x = self.data > print x I would like to see _marker put inside the class' scope. That prevents somebody from the outside scope easily passing _marker as an argument to instance.f. It also neatly encapsulates everything A needs within A. class A(object): _marker = [] def __init__(self, n): self.data =n def f(self, x = _marker): if x is self.__class__._marker: # must use "is" and not "==" x = self.data print x Note the gotcha though: in the method definition, you refer to a plain _marker, but in the method code block, you need to qualify it. -- Steven. From apardon at forel.vub.ac.be Fri Nov 25 03:15:16 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Nov 2005 08:15:16 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <86hda2x9ny.fsf@bhuda.mired.org> Message-ID: Op 2005-11-24, Mike Meyer schreef : > Antoon Pardon writes: >>> The usual response is "That's not the Python way." That's not calling >>> someone dumb, just pointing out that they don't yet fully understand >>> the Python way. >> "That is not the Python way", is just saying "Python doesn't have it" >> in other words. So it can't be the answer to why python can't have >> something. > > No, it isn't. At least, it isn't when I use it. A language is more > than just an accumulation of features. Well, a good language is more > than just an accumulation of features - there's a philosophy > underlying the language, that guides what features are added and what > features aren't. Other languages have other philosophies, and wind up > being good for other things. But how this philosophy influences design is not straight forward. The ternary operator was thought of to go against the philosopy, and now seems to be at least compatible with the philosophy. So when someone asks why it is not in python, saying "It is not the python way" still doesn't answer the question, because the person would probably still like to know what in his proposal is against the python philosophy and why. > When I say "That's not the Python way", I mean that such a feature > runs counter to my vision of Python's underlying philosophy. Fine, but it would help if you could support this with arguments or at least give an explanation of why you think this is so. > My vision > isn't perfect - I've changed my mind about things: I used to want real > macros, and I initially disliked list comprehensions. My vision > doesn't agree with the developers - notably including Guido's - a lot > of the time. On the other hand, they haven't done anything that > strikes me as so wrong that I want to spend the time required working > on Python rather than in Python to allow me to get it fixed. I see nothing wrong with that. But I would apreciate it, should you be more open about something being your personal vision. To me something like: "That is not the python way" comes accross as: "You just don't understand about python, if you ask/propose something like that" It gives me the feeling the person is saying something like: "Python is like this, I like it this way, so nobody better suggests this changes". -- Antoon Pardon From fdu.xiaojf at gmail.com Thu Nov 24 01:27:45 2005 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Thu, 24 Nov 2005 14:27:45 +0800 Subject: python2.4.2 test_fpformat and test_locale failed on IRIX6.5 Message-ID: <43855D61.9030002@gmail.com> Hello, I am trying to install python2.4.2 on IRIX6.5, but test_fpformat and test_locale failed when I ran "smake test". The following is the detailed error message: -------------------------------------------------------------------------------------------------------- prompt:\> ./python ./Lib/test/test_fpformat.py test_basic_cases (__main__.FpformatTest) ... ok test_failing_values (__main__.FpformatTest) ... ok test_reasonable_values (__main__.FpformatTest) ... FAIL ====================================================================== FAIL: test_reasonable_values (__main__.FpformatTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_fpformat.py", line 51, in test_reasonable_values self.checkFix(realVal, d) File "./Lib/test/test_fpformat.py", line 28, in checkFix self.assertEquals(result, expected) AssertionError: '-0' != '0' ---------------------------------------------------------------------- Ran 3 tests in 0.005s FAILED (failures=1) Traceback (most recent call last): File "./Lib/test/test_fpformat.py", line 75, in ? test_main() File "./Lib/test/test_fpformat.py", line 71, in test_main run_unittest(FpformatTest) File "/user_data2/jfxiao/local/source/python/python-2.4.2/Python-2.4.2/Lib/test/test_support.py", line 290, in run_unittest run_suite(suite, testclass) File "/user_data2/jfxiao/local/source/python/python-2.4.2/Python-2.4.2/Lib/test/test_support.py", line 275, in run_suite raise TestFailed(err) test.test_support.TestFailed: Traceback (most recent call last): File "./Lib/test/test_fpformat.py", line 51, in test_reasonable_values self.checkFix(realVal, d) File "./Lib/test/test_fpformat.py", line 28, in checkFix self.assertEquals(result, expected) AssertionError: '-0' != '0' prompt:\> ./python ./Lib/test/test_locale.py '%f' % 1024 =? '1,024.000000' ... no '%f' % 1024 == '1024.000000' != '1,024.000000' '%f' % 102 =? '102.000000' ... yes '%f' % -42 =? '-42.000000' ... yes '%+f' % -42 =? '-42.000000' ... yes '%20.f' % -42 =? ' -42' ... yes '%+10.f' % -4200 =? ' -4,200' ... no '%+10.f' % -4200 == ' -4200' != ' -4,200' '%-10.f' % 4200 =? '4,200 ' ... no '%-10.f' % 4200 == '4200 ' != '4,200 ' -------------------------------------------------------------------------------------------------------- Can someone tell me how to fix this ? Thanks in advance. Regrads, xiaojf From pierre.barbier at cirad.fr Sun Nov 13 10:26:32 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sun, 13 Nov 2005 16:26:32 +0100 Subject: Proposal for adding symbols within Python In-Reply-To: References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> Message-ID: <43775b06$0$14331$626a14ce@news.free.fr> Ben Finney a ?crit : > Pierre Barbier de Reuille wrote: > >>Mike Meyer a ?crit : >> >>>Hmm. You know, $symbol$ doesn't seem nearly as bad as $symbol. It >>>tickles TeX, not P***. I could live with that. >> >>Yep, I like this $symbol$ notation ! > > > Gets a big -1 here. > > I've yet to see a convincing argument against simply assigning values > to names, then using those names. > I can see three interests : 1 - ensure values are unique (i.e. a bit like using instances of object) 2 - values are meaningful (i.e. with introspection on the values you get a human-readable value, unlike with instances of object) 3 - getting an *easy* access to those two properties 1 and 2 require a new type, 3 a new syntax (IMO). Here's a try for the symbol class : class symbol(object): def __init__(self, value): self._value = value def _get_value(self): return self._value value = property(_get_value) def __eq__(self, other): return self.value == other.value def __str__(self): return str(self.value) def __repr__(self): return "symbol(%s)" % (repr(self.value),) One thing to do would be to return the same object for symbols with the same value (when possible ...). For example, if we limit symbol to hashable types, we can implement something which can be tested with "is" instead of "==": class symbol(object): _cache = {} def __new__(cls, value): if value in symbol._cache: return symbol._cache[value] self = object.__new__(cls) self._value = value symbol._cache[value] = self return self def _get_value(self): return self._value value = property(_get_value) def __eq__(self, other): return self.value == other.value def __str__(self): return str(self.value) def __repr__(self): return "symbol(%s)" % (repr(self.value),) Then, as I suggested, you can do something like : a = symbol((file, "opened")) But it's less readable than $file.opened$ (or something similar). Pierre From case.nelson at gmail.com Wed Nov 16 13:26:15 2005 From: case.nelson at gmail.com (snoe) Date: 16 Nov 2005 10:26:15 -0800 Subject: Cursor Position. In-Reply-To: <3tf8paFsfgb8U1@uni-berlin.de> References: <3tds08Fsb3p1U1@uni-berlin.de> <3tf8paFsfgb8U1@uni-berlin.de> Message-ID: <1132165574.969101.114340@g49g2000cwa.googlegroups.com> This script should be a good start: from ctypes import * import time PUL = POINTER(c_ulong) class KeyBdInput(Structure): _fields_ = [("wVk", c_ushort), ("wScan", c_ushort), ("dwFlags", c_ulong), ("time", c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(Structure): _fields_ = [("uMsg", c_ulong), ("wParamL", c_short), ("wParamH", c_ushort)] class MouseInput(Structure): _fields_ = [("dx", c_long), ("dy", c_long), ("mouseData", c_ulong), ("dwFlags", c_ulong), ("time",c_ulong), ("dwExtraInfo", PUL)] class Input_I(Union): _fields_ = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(Structure): _fields_ = [("type", c_ulong), ("ii", Input_I)] class POINT(Structure): _fields_ = [("x", c_ulong), ("y", c_ulong)] def Click(x,y): orig = POINT() windll.user32.GetCursorPos(byref(orig)) windll.user32.SetCursorPos(x,y) FInputs = Input * 2 extra = c_ulong(0) ii_ = Input_I() ii_.mi = MouseInput( 0, 0, 0, 2, 0, pointer(extra) ) ii2_ = Input_I() ii2_.mi = MouseInput( 0, 0, 0, 4, 0, pointer(extra) ) x = FInputs( ( 0, ii_ ), ( 0, ii2_ ) ) windll.user32.SendInput(2, pointer(x), sizeof(x[0])) return orig.x, orig.y From enleverlesO.OmcO at OmclaveauO.com Sat Nov 26 01:41:14 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Sat, 26 Nov 2005 07:41:14 +0100 Subject: Any way to change files in a ZIP archive? References: Message-ID: <438803cb$0$6358$626a14ce@news.free.fr> Hi! See http://mclaveau.com/ress/python/zipmci.htm @-salutations Michel Claveau From steve at holdenweb.com Wed Nov 9 12:57:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 09 Nov 2005 17:57:46 +0000 Subject: Lie Hetland book: Beginning Python.. In-Reply-To: <43721FE8.9090704@ghaering.de> References: <43721FE8.9090704@ghaering.de> Message-ID: Gerhard H?ring wrote: > Vittorio wrote: > >>[...] >>Nonetheless, I was unable to find any documentation about such a >>different behaviour between Pysqlite and Pysqlite2; from my beginner >>point of view the Pysqlite (Magnus' version) paramstyle looks a better >>and more pythonic choice and I don't grasp the Pysqlite2 developers' >>intentions deviating from that way. > > > The reason why pysqlite 0.x/1.x used paramstyle "pyformat", based on > Python string substitution for SQL parameters is that at the time > pysqlite was started, SQLite 2.x did not have any support for parameter > binding. So we had to "fake" it in Python, just like the MySQL interface > does (for the same reasons). > > Later SQLite 2.x versions and of course SQLite 3.x supported real bound > parameters and pysqlite2 was developed from scratch to benefit from > them. SQLite 3.x supports both qmark and named paramstyles, so you can > use question marks *or* named parameters: > > >>> from pysqlite2 import dbapi2 as sqlite > >>> con = sqlite.connect(":memory:") > >>> cur = con.cursor() > >>> cur.execute("select 2*?", (14,)) > >>> cur.fetchone() > (28,) > >>> > >>> cur.execute("select 2 * :x", {"x": 14}) > >>> cur.fetchone() > (28,) > >>> > >>> x = 14 > >>> cur.execute("select 2 * :x", locals()) > >>> cur.fetchone() > (28,) > >>> > > I've also once written a wrapper using pysqlite 2.x's hooks that allows [...] > >>I would be very grateful if someone would cast a light over >>Pysqlite/Pysqlite2 discrepancies. > > > I think about the only place I wrote a bit about the differences was in > the pysqlite 2.0 final announcement: > > http://lists.initd.org/pipermail/pysqlite/2005-May/000043.html > Unfortunately this appears to mean that pysqlite2 isn't fully DB API-conformant. >>> import pysqlite2 >>> pysqlite2.paramstyle Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'paramstyle' >>> Of course, given the module's flexibility it's difficult to know what you *would* put in paramstyle. I take it mixing different paramstyles in the same query will fail? 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 samrobertsmith at gmail.com Sat Nov 12 22:27:14 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 19:27:14 -0800 Subject: directory listing In-Reply-To: <43757328.4030105@syr.edu> References: <14cltzqwyklwl.17i7f7qnfnlh0$.dlg@40tude.net> <192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu> <1d987df30511111423o572172eay36870d09220233d7@mail.gmail.com> <1d987df30511111444m1ddfaca2qcf0acc32e49fc108@mail.gmail.com> <1d987df30511111500j57418032p12c5f30b85aaa594@mail.gmail.com> <43757328.4030105@syr.edu> Message-ID: <1d987df30511121927x45b84701ga01a074b31a3292f@mail.gmail.com> thanks a lot! On 11/11/05, Michael Konrad wrote: > > This is what I decided on for a solution. I haven't tested it > cross-platform yet. > > import os > > def dirListing(directory='/Users/mkonrad'): > """Returns a list of directories.""" > #variables > dirs = [] #list of directories > > #list of directories and files > listing = os.listdir(directory) > > #get just the directories > for x in listing: > if os.path.isdir(directory+os.sep+x): > dirs.append(x) > > return dirs > > Fredrik Lundh wrote: > > "Shi Mu" wrote: > > > >> print buildList() gets lots of stuffs from my temp directory(there do > >> exist lots of files). > >> But why "print x' has nothing? > > > > C:\>more script.py > > import os > > > > def buildList( directory='c:\TEMP' ): > > dirs = [ ] > > listing = os.listdir(directory) > > for x in listing: > > x = os.path.join(directory, x) > > print x > > if os.path.isdir(x): > > dirs.append(x) > > return dirs > > > > print buildList() > > > > C:\>dir temp > > ... > > > > 2005-11-12 00:00 . > > 2005-11-12 00:00 .. > > 2005-11-12 00:00 20 bacon.dat > > 2005-11-12 00:00 egg > > 2005-11-12 00:00 20 spam.txt > > 2 fil(er) 40 byte > > 3 katalog(er) 9 818 021 888 byte ledigt > > > > C:\>python script.py > > c:\TEMP\bacon.dat > > c:\TEMP\egg > > c:\TEMP\spam.txt > > ['c:\\TEMP\\egg'] > > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From samrobertsmith at gmail.com Sun Nov 20 05:55:37 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 02:55:37 -0800 Subject: about dictionary Message-ID: <1d987df30511200255n278bbffl684eff25d64a31a8@mail.gmail.com> I have have the following code: >>> a=[3,5,8,0] >>> b={} >>> How I can i assign each item in a as the key in the dictionary b simultaneously? that is, b={3:[],5:[],8:[],0:[]} Thanks! From fccoelho at gmail.com Mon Nov 28 15:58:12 2005 From: fccoelho at gmail.com (Flavio) Date: 28 Nov 2005 12:58:12 -0800 Subject: importing a method In-Reply-To: <1h6q906.wbfwmtxr0zjN%aleax@mail.comcast.net> References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> <1133191986.034689.59090@g14g2000cwa.googlegroups.com> <1h6q906.wbfwmtxr0zjN%aleax@mail.comcast.net> Message-ID: <1133211492.190737.192250@g47g2000cwa.googlegroups.com> > If you have a function f and want to make an instancemethod out of it, > you can simply call f.__get__(theinstance, theclass) and that will build > and return the new instancemethod you require. I think that f.show = MethodType(show,f) is less cryptic than f.__get__(instance, class) Fl?vio From igouy at yahoo.com Tue Nov 29 16:05:07 2005 From: igouy at yahoo.com (igouy at yahoo.com) Date: 29 Nov 2005 13:05:07 -0800 Subject: Computer Language Shootout Message-ID: <1133298307.938958.186070@f14g2000cwb.googlegroups.com> We don't have Python implementations for one program, and a couple of the Python programs we do have show Error. http://shootout.alioth.debian.org/benchmark.php?test=all&lang=python&lang2=python Please contribute missing Python programs or faster more-elegant Python programs. Please follow the FAQ instructions http://shootout.alioth.debian.org/faq.php#contribute best wishes, Isaac From gsakkis at rutgers.edu Wed Nov 9 22:47:40 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Nov 2005 19:47:40 -0800 Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> Message-ID: <1131594460.098689.64140@g43g2000cwa.googlegroups.com> "Alex Martelli" wrote: > bon... at gmail.com wrote: > > > FP functions like dropwhile/takewhile etc. > > No way -- the itertools module is and remains a PRECIOUS resource. > If you want an iterator rather than a list, itertools.ifilter is quite > appropriate here. What about the future of itertools in python 3K ? IIRC, several functions and methods that currently return lists are going to return iterators. Could this imply that itertools.(imap/ifilter/izip) will take the place of map/filter/zip as builtins ? George From samrobertsmith at gmail.com Fri Nov 11 18:00:33 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 11 Nov 2005 15:00:33 -0800 Subject: directory listing In-Reply-To: References: <14cltzqwyklwl.17i7f7qnfnlh0$.dlg@40tude.net> <192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu> <1d987df30511111423o572172eay36870d09220233d7@mail.gmail.com> <1d987df30511111444m1ddfaca2qcf0acc32e49fc108@mail.gmail.com> Message-ID: <1d987df30511111500j57418032p12c5f30b85aaa594@mail.gmail.com> On 11/11/05, Fredrik Lundh wrote: > "Shi Mu" wrote: > > > but i am curious why the line of "print x" does not show > > anything. > > because your c:\temp directory is empty ? > > print buildList() gets lots of stuffs from my temp directory(there do exist lots of files). But why "print x' has nothing? From spiralx at gmail.com Mon Nov 14 12:23:56 2005 From: spiralx at gmail.com (James) Date: Mon, 14 Nov 2005 17:23:56 +0000 Subject: Not enough arguments for format string In-Reply-To: References: Message-ID: <7ee3dcd80511140923u341cdda2j@mail.gmail.com> Missing a comma there :) On 14/11/05, johnnie pittman wrote: > So the line above should be: > > os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export > DISPLAY; echo %s | sudo -S %s; sudo -k' % (password binpath)) > > try that. os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export DISPLAY; echo %s | sudo -S %s; sudo -k' % (password, binpath)) From vagrantbrad at yahoo.com Thu Nov 24 11:42:28 2005 From: vagrantbrad at yahoo.com (vagrantbrad at yahoo.com) Date: 24 Nov 2005 08:42:28 -0800 Subject: Using Cron to run a python program References: <1132791791.548850.186420@o13g2000cwo.googlegroups.com> <20051124014517.M83381@uniqsys.com> Message-ID: <1132850548.326834.200100@o13g2000cwo.googlegroups.com> You were right!! I had a relative path to the update.log file, so I looked in the home path of the cron environment and found the update.log file that the cron job was writing to. I updated my program to point to the absolute path of the update.log file that I wanted the logs written to, and now it works. Thanks, Brad Steve Holden wrote: > Carsten Haese wrote: > > On 23 Nov 2005 16:23:11 -0800, vagrantbrad wrote > > > >>I'm using python 2.4 running on Fedora Core 4. I have written a python > >>program called ipscan.py that checks the external ip address of my > >>cable internet connection, and on change, will update the dns records > >>at my dns provider, zoneedit. So basically, I've setup dynamic dns > >>using python. Once the ip compare and/or update is complete, I log the > >>results to a text file called update.log. When I run the program in > >>a bash shell with the command "python ipscan.py", the program runs fine > >>and the results are appended to update.log. When I run this program > >>as a cron job under the root user with the previously mentioned > >>command, the program runs without errors but does not append an > >>entry to the log. The permissions on the update.log file should not > >>be an issue since I'm running the cron job as root, but I've given > >>root write permissions just to be safe. What would cause the > >>logging to work at a command prompt but fail in cron? I'm not > >>getting any errors in the cron logs or /var/spool/mail/root. > > > > > > You're not giving us much detail about your script, so we can only guess. My > > guess is that your python script is either not invoked at all or it dies > > (raises an exception) before appending to the update.log. > > > > You should keep in mind that cron jobs don't run in a normal login shell, > > don't have the normal environment variables, and are not attached to a tty. > > Any of those factors can conceivably cause a script to fail under cron when it > > works fine from a shell. > > > Since we're guessing, *my* guess would be that the cron-triggered runs > are running in some directory other than the one the manually-triggered > jobs are, and that there is a separate update.log file in that directory. > > The fix, of course, would be to use an absolute path to identify the log > file (if I'm right). > > 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 kent37 at tds.net Fri Nov 25 08:55:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Nov 2005 08:55:28 -0500 Subject: Persist a class (not an instance) Message-ID: <43871516$1_1@newspeer2.tds.net> Is there a way to persist a class definition (not a class instance, the actual class) so it can be restored later? A naive approach using pickle doesn't work: >>> import pickle >>> class Foo(object): ... def show(self): ... print "I'm a Foo" ... >>> p = pickle.dumps(Foo) >>> p 'c__main__\nFoo\np0\n.' Hmm, doesn't look too promising. In a new interpreter: >>> import pickle >>> p='c__main__\nFoo\np0\n.' >>> Foo = pickle.loads(p) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\pickle.py", line 1394, in loads return Unpickler(file).load() File "C:\Python24\lib\pickle.py", line 872, in load dispatch[key](self) File "C:\Python24\lib\pickle.py", line 1104, in load_global klass = self.find_class(module, name) File "C:\Python24\lib\pickle.py", line 1140, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'Foo' The idea is to persist classes that are created and modified at runtime. Thanks, Kent From fccoelho at gmail.com Mon Nov 28 06:21:44 2005 From: fccoelho at gmail.com (Flavio) Date: 28 Nov 2005 03:21:44 -0800 Subject: importing a method In-Reply-To: <1133137958.685179.286140@o13g2000cwo.googlegroups.com> References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> <1133137958.685179.286140@o13g2000cwo.googlegroups.com> Message-ID: <1133176903.976556.287800@z14g2000cwz.googlegroups.com> Because, by the time the user function is imported and attributed to the custom method, soandso has already been instantiated and contains the information tha needs to accessed by the user's function. From claudio.grondi at freenet.de Sun Nov 27 08:56:22 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 27 Nov 2005 13:56:22 -0000 Subject: How to get started in GUI Programming? References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <3utoq5F12ug2dU1@individual.net> schrieb im Newsbeitrag news:1132927360.270239.64670 at f14g2000cwb.googlegroups.com... > I am trying to learn GUI programming in Python, but have to confess I > am finding it difficult. > > I am not an experienced programmer - just someone who from time to > time writes small programs for my use. Over the years I have moved > from GWBASIC to QBASIC to Visual Basic, and now trying to move across > to a Linux platform. Python seems to be the best compromise between > the limitations of command line basic programming and the total > incomprehensibility of C. > > Googling around it seems the best GUI is either Tkinter or PyGtk. I > found a book which recommended PyGtk, as it had a graphical design > option, Glade. Coming from a VB background I latched onto that and > bought the book (Beginning Python, Wrox), but it was a disappointment > (or more accurately a complete waste of money) - there was > insufficient detail in the text. > > I've found the tutorial and reference manual on the PyGtk web site, > but although I've made some progress, I keep reaching points where I > have insufficient background to understand them. Currently I'm stuck > on dialog boxes (the code seems immensely complex for the equivalent of > MsgBox("Do you really want to do this ",vbYesNo) and I haven't > got it to work properly yet) and loading graphical images in anything > other than their original size, but every new step brings another > struggle > > I've seen reference to a Tkinter book - something like 'Python > and Tkinter Programming' but it seems to be out of print and > unavailable. > > Can anyone offer any suggestions as to the least painful way forwards? > >From what you write I conclude, that it is maybe a very good idea to stay with Visual Basic and use it to create the appropriate ActiveX components you need in Python and then register them to use it from Python. This way you can 'marry' what you have already created in Visual Basic easily with Python. >From what I currently know, there is no 100% cross-platform solution for GUI related tasks, because each platform has own specifics which usually are very interesting for use in own programming and that kills as a consequence the cross-platform usage. # For example a Yes/No/Abort dialog box can be achieved using the WSHOM.OCX available in Windows as follows: import win32com.client axWshShell = win32com.client.Dispatch("WScript.Shell") # WSHOM.OCX axWshShell_Popup_Icon_Critical = 16 axWshShell_Popup_Button_AbortRetryIgnore = 2 axWshShell_Popup_NoAutoclose = 0 intRetVal = axWshShell.Popup( ### Raise a message box: " The Popup() Text" + "\n" + "", axWshShell_Popup_NoAutoclose, " The Popup() Title:", axWshShell_Popup_Icon_Critical + axWshShell_Popup_Button_AbortRetryIgnore ) axWshShell_Popup_Clicked_Abort = 3 # [Abort] button axWshShell_Popup_Clicked_Retry = 4 # [Retry] button axWshShell_Popup_Clicked_Ignore = 5 # [Ignore] button if(intRetVal == axWshShell_Popup_Clicked_Abort): print 'Abort clicked, return value = %i'%(intRetVal,) if(intRetVal == axWshShell_Popup_Clicked_Retry): print 'Retry clicked, return value = %i'%(intRetVal,) if(intRetVal == axWshShell_Popup_Clicked_Ignore): print 'Ignore clicked, return value = %i'%(intRetVal,) Hope this is what are you looking for, isn't it? Claudio From pwatson at redlinepy.com Fri Nov 18 14:14:19 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 18 Nov 2005 13:14:19 -0600 Subject: Web-based client code execution Message-ID: <3u6ngeFvh3v1U1@individual.net> What are the options? The user to hits a web page, downloads code (Python I hope), execute it, and be able to return the results. It needs to be able to go through standard HTTP so that it could be run from behind a corporate firewall without any other ports being opened. Am I stuck doing an ActiveX control? Yes, I know that downloading code and executing on the client machine is a security risk. This will be for the employee's computers to connect. This will not be a publicly available web page. I have read some about AJAX. Is there an APAX coming for Python? From apardon at forel.vub.ac.be Mon Nov 28 09:39:25 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2005 14:39:25 GMT Subject: General question about Python design goals References: Message-ID: Op 2005-11-28, Duncan Booth schreef : > Antoon Pardon wrote: > >> I'm sure I could come up with an other example where I would like >> to have both some list method and use it as a dictionary key and >> again people could start about that implementation having some >> flaws and give better implementations. >> >> I'm just illustrating that some list-like methods with tuples >> could be usefull. >> > But you aren't illustrating that at all. You came up with an example which > showed, at least to me, a good argument why tuples should *not* have list > methods. No I gave an example, you would implement differently. But even if you think my example is bad, that would make it a bad argument for tuples having list methods. That is not the same as being a good argument against tuples having list methods. The trouble is to really convince would probably require a complete worked out module, but then I don't have the time to come up with a complete worked out module just to illustrate something. So I come up with just a skeleton of something to get the idea across and what happens is that the attention goes to how the skeleton could be approved in other ways, instead of trying to understand what ideas are trying to be communicated. -- Antoon Pardon From francois.jacq at irsn.fr Mon Nov 21 10:42:16 2005 From: francois.jacq at irsn.fr (fj) Date: 21 Nov 2005 07:42:16 -0800 Subject: writing a generic method In-Reply-To: References: <1132566891.016382.116540@g43g2000cwa.googlegroups.com> Message-ID: <1132587736.499443.97900@g44g2000cwa.googlegroups.com> Nice ! Thank you very much : it works well with "s#s#O" And also thank you for your advice to insert PyErr_Clear() when several calls to PyArgParseTuple are performed in the same method. bye FJ From usenet.20.evilspam at spamgourmet.com Thu Nov 10 21:05:16 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Fri, 11 Nov 2005 02:05:16 GMT Subject: Recompile AST? In-Reply-To: References: <1131657716.197347.167740@g47g2000cwa.googlegroups.com> Message-ID: Leif K-Brooks wrote: > chrisspen at gmail.com wrote: > >>Is it possible to recompile the AST generated by compiler.parse, back >>into code or an executable code object? > > > Into a bytecode object: > > >>> from compiler.pycodegen import ModuleCodeGenerator > >>> from compiler.misc import set_filename > >>> from compiler import parse > >>> > >>> tree = parse('foo = 42') > >>> set_filename('', tree) > >>> code = ModuleCodeGenerator(tree).getCode() > >>> exec code > >>> foo > 42 > > Into Python source code: . Thanks, that's exactly what I was looking for. I had almost figured that out, but I had overlooked the need for set_filename. Chris From niemand.leermann at thomas-guettler.de Tue Nov 8 11:29:09 2005 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Tue, 08 Nov 2005 17:29:09 +0100 Subject: which feature of python do you like most? References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: Am Tue, 08 Nov 2005 04:21:52 -0800 schrieb zelzel.zsu at gmail.com: > which feature of python do you like most? > > I've heard from people that python is very useful. > Many people switch from perl to python because they like it more. It gives you a stacktrace if something is wrong. Exceptions are built-in. Example: Perl: open FD "myfile.txt" || or die "Can't open file $!"; Python: fd=open("myfile.txt") If the file can't be opened, then you get a nice traceback. If you are programming/debugging cgi with cgitb you can even get a HTML page full of important information. Example: http://www.thomas-guettler.de/vortraege/python/cgitb.html I have a page why I switched from perl to python, but it is in german: http://www.thomas-guettler.de/vortraege/programmierung/einfuehrung.html#link_5 Objectoriented Programming in Perl is no fun. I switched from perl to python because the emacs-perl mode was not able to understand all those backslashed anymore (the code was correct). Regards, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From jeff at schwabcenter.com Tue Nov 1 15:01:25 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Tue, 01 Nov 2005 20:01:25 GMT Subject: extracting numbers from a file, excluding words In-Reply-To: References: <1130865585.189485.249820@f14g2000cwb.googlegroups.com> Message-ID: Steve Horsley wrote: > Kristina Kudria?ova wrote: > >> 1 Nov 2005 09:19:45 -0800, dawenliu at gmail.com : >> >>> Hi, I have a file with this content: >>> >>> zzzz zzzzz zzz zzzzz >>> ... >>> xxxxxxx xxxxxxxxxx xxxxx 34.215 >>> zzzzzzz zz zzzz >>> ... >>> >> >> Hi, >> >> I'd suggest doing this: >> >> f = file('...') >> for line in f: >> if 'xxxxxxx xxxxxxxxxx xxxxx' in line: >> var = float(line[len('xxxxxxx xxxxxxxxxx xxxxx'):].strip()) >> f.close() > > > I think I prefer "if line.startswith('xxxxxxx xxxxxxxxxx xxxxx'):" . > Feels cleaner to me. Especially if any "z" lines might include the magic pattern. From bretthoerner at gmail.com Tue Nov 15 15:15:47 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 15 Nov 2005 12:15:47 -0800 Subject: newbie - How do I import automatically? In-Reply-To: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> Message-ID: <1132085747.656111.172270@o13g2000cwo.googlegroups.com> > I have written some functions in a file called btools.py. I would like > to import them automatically when I start up Python shell. Today I must > do it by hand like this > > >>> from btools import * > >>> dir() > ['__builtins__', '__doc__', '__name__', 'func1', 'func2', 'func3'] > >>> > > Is there a way to do this automatically so that I always have 'func1', > 'func2' and so on available, without me having to do it by hand? This isn't _exactly_ what you wanted, but you might want to try using IPython, a much improved Python shell, http://ipython.scipy.org/ You can easily configure it to automatically import whatever kind of modules you want on start, etc... and it has many other features, I just can't picture touching the normal Python shell anymore. From godoy at ieee.org Thu Nov 24 08:19:31 2005 From: godoy at ieee.org (Jorge Godoy) Date: 24 Nov 2005 11:19:31 -0200 Subject: wxPython Licence vs GPL References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> <86hda2zcli.fsf@bhuda.mired.org> <1132820796.119386.309160@o13g2000cwo.googlegroups.com> <1132836746.625340.17850@g49g2000cwa.googlegroups.com> Message-ID: <87d5kqtc7w.fsf@jupiter.g2ctech> "bonono at gmail.com" writes: > I meant the SCO saga, don't know if you are referring the same thing. Probably. MS bought some shares from SCO to help financing the lawsuit. Anyway, I don't see much people worrying about it and in fact, I see more people laughing about SCO's mistakes and wrong information / facts... -- Jorge Godoy From steve at REMOVETHIScyber.com.au Tue Nov 22 17:02:56 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 23 Nov 2005 09:02:56 +1100 Subject: wxPython Licence vs GPL References: <43838497$1@nntp0.pdx.net> Message-ID: On Tue, 22 Nov 2005 12:57:12 -0800, Scott David Daniels wrote: > I would, at the very least, acknowledge the wxPython origin of the code > whether any remains or not (credit is appreciated and cheap to give). Ha ha, don't ask movie director James Cameron about *that*. On the basis of a throw-away line that he "got the idea" for Terminator from a couple of Harlan Ellison stories, he and the studio were sued by Ellison, who ultimately won and was awarded millions. In this world where ideas are thought to be property (if only I could own the idea that ideas can be owned) the safest position is to claim you've never read a book, seen a line of code, been to the movies or heard a song in your life. (Only half joking.) -- Steven. From schwehr at gmail.com Sun Nov 27 12:28:42 2005 From: schwehr at gmail.com (schwehr at gmail.com) Date: 27 Nov 2005 09:28:42 -0800 Subject: passing artibrary strings into a database In-Reply-To: <3uu728F13cahqU1@uni-berlin.de> References: <1133109304.575556.284190@g47g2000cwa.googlegroups.com> <3uu728F13cahqU1@uni-berlin.de> Message-ID: <1133112522.797183.322000@o13g2000cwo.googlegroups.com> Thanks! Looks like I need to get a newer version of pysqlite into the fink package tree since pysqlite 1.0.1 does not appear support that From zem.mattress at gmail.com Tue Nov 22 14:02:07 2005 From: zem.mattress at gmail.com (Zem) Date: 22 Nov 2005 11:02:07 -0800 Subject: interact with application installer prompts using Python References: <1132685521.105678.126700@g44g2000cwa.googlegroups.com> Message-ID: <1132686127.607915.190610@g47g2000cwa.googlegroups.com> Some applications installers written with Installshield allow you to do silent installs. This requires that you create a response file to store all of your default answers. Check this link out, maybe it'll work for you. http://documentation.installshield.com/robo/projects/helplib/IHelpSetup_EXECmdLine.htm#rParam As far as other installer types, you'll have to check their respective documentations to see if they provide any kind of silent install mechanisms. From simon.brunning at gmail.com Fri Nov 11 10:35:13 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 11 Nov 2005 15:35:13 +0000 Subject: Is there a built-in method for transforming (1, None, "Hello!") to 1, None, "Hello!"? In-Reply-To: <1131722506.604482.323720@f14g2000cwb.googlegroups.com> References: <1131722506.604482.323720@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c60511110735kcf1c28ap@mail.gmail.com> On 11 Nov 2005 07:21:46 -0800, Daniel Crespo wrote: > Is there a built-in method for transforming (1,None,"Hello!") to > 1,None,"Hello!"? There's no conversion to do: >>> (1,None,"Hello!") (1, None, 'Hello!') >>> 1,None,"Hello!" (1, None, 'Hello!') They are both tuples contining identicle elements. What is it that you want to do? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From robert.kern at gmail.com Sat Nov 26 17:04:07 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 26 Nov 2005 14:04:07 -0800 Subject: Which License Should I Use? In-Reply-To: <1133041306.601950.213710@g43g2000cwa.googlegroups.com> References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> <1133041306.601950.213710@g43g2000cwa.googlegroups.com> Message-ID: mojosam wrote: > I would have to talk to a lawyer to be sure, but right now, I think I > can argue that anything I do on my own time belongs to me. I'm > technically a consultant right now (even though I'm spending 40 > hours/week with the one "client"). I can take on other clients, as > long as they don't directly compete. This means they're hiring my > expertise. If I bring my own tools, that's part of my expertise. I do > recall there was a clause in the contract that anything I did on their > time belonged to them. For my next client, I should definitely include > a clause about rereleasing open source changes. You're in something of a gray area, but one that has seen a lot of litigation. Although you are "technically" a consultant, you are probably considered an employee with regards to the "work made for hire" doctrine. You should probably have a chat with a lawyer soon (I am not one! TINLA!). As Steve Holden said, being open with your client and putting an agreement in your contract is probably the best way to ensure that your work will belong to you or, failing that, continue to be available to you under an open source license. -- 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 larry.bates at websafe.com Thu Nov 17 17:38:55 2005 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 17 Nov 2005 16:38:55 -0600 Subject: Stretching a bitmap In-Reply-To: <1132262655.753062.210080@g14g2000cwa.googlegroups.com> References: <1132262655.753062.210080@g14g2000cwa.googlegroups.com> Message-ID: <437D067F.3020703@websafe.com> Python Imaging Library (PIL) can size bitmaps. I use it to create thumbnails or to size bitmaps quite often. There may be a "wxPython" built-in for this also, but I don't know what it would be. -Larry Bates David Poundall wrote: > Is it possible to import a bitmap and stretch it to fit a defined area > with wxPython? If so, could someone point me to any relevent web > reference on the subject? > > Thanks in advance > > David > From bignose+hates-spam at benfinney.id.au Thu Nov 3 16:04:49 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 4 Nov 2005 08:04:49 +1100 (EST) Subject: computer programming References: <1130944817.168134.124690@g14g2000cwa.googlegroups.com> <1130978408_1503@spool6-east.superfeed.net> Message-ID: Brandon K wrote: > what is .tk? Turkmenistan? or is it just some arbitrary suffix. The country top-level domains are the ISO 3166 two-letter country codes. -- \ "Nothing in life is so exhilarating as to be shot at without | `\ result." -- Winston Churchill | _o__) | Ben Finney From bonono at gmail.com Wed Nov 23 13:55:42 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 10:55:42 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: References: <1132764821.340622.321850@g47g2000cwa.googlegroups.com> Message-ID: <1132772142.500020.16360@g44g2000cwa.googlegroups.com> Fredrik Lundh wrote: > maybe it's time to change "equivalent to" to "similar to", to avoid > messing things up for people who reads the mostly informal library > reference as if it were an ISO specification. That is their fault as the library reference is supposed to be "(keep this under your pillow)", not for reading. From steve at REMOVETHIScyber.com.au Thu Nov 3 11:02:24 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 03:02:24 +1100 Subject: OT - Re: Microsoft Hatred FAQ References: Message-ID: On Thu, 03 Nov 2005 13:29:26 +0100, Jerzy Karczmarczuk wrote: > Now, tell me: is the polluting of a newsgroup with off-topic postings, > a crime, Not in any nation that values personal freedom over petty laws controlling people's behaviour for no good purpose. -- Steven. From qwweeeit at yahoo.it Fri Nov 4 15:01:37 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 4 Nov 2005 12:01:37 -0800 Subject: Web automation with twill References: <1130934838.388039.297650@o13g2000cwo.googlegroups.com> <1130945598.627911.264390@g49g2000cwa.googlegroups.com> <1130966536.697459.250700@g49g2000cwa.googlegroups.com> <1131092795.953963.297990@g14g2000cwa.googlegroups.com> <1131117665.999523.176780@g43g2000cwa.googlegroups.com> <1131118403.944127.255730@f14g2000cwb.googlegroups.com> Message-ID: <1131134497.052873.208180@o13g2000cwo.googlegroups.com> Hi Michele, I only made the observation about Zope, because I hoped to hear a different point of view as you are/were involved in web development using Zope/Plone (as referred in your article...). Besides that, at a Linux Day, I followed a presentation of Zope/Plone framework, which stroke me a lot. Bye. From peter at engcorp.com Mon Nov 21 09:12:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Nov 2005 09:12:05 -0500 Subject: Numeric array in unittest problem In-Reply-To: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> References: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > hello, > > I found that if I use Numeric.array into unittest it is not > consistance, > Is that normal ? > > import Numeric > class myTest(unittest.TestCase): > def runTest(self): > a = Numeric.array([1,2]) > b = Numeric.array([1,33]) > self.assertEqual(a, b) > pass > > > This will not raise any error ??? Code that doesn't execute at all generally raises no errors... -Peter From yongsheng.yang at gmail.com Wed Nov 9 21:03:39 2005 From: yongsheng.yang at gmail.com (david) Date: 9 Nov 2005 18:03:39 -0800 Subject: Looking Python script to compare two files In-Reply-To: <1131587940.702181.314750@g44g2000cwa.googlegroups.com> References: <1131587940.702181.314750@g44g2000cwa.googlegroups.com> Message-ID: <1131588219.032247.146820@g14g2000cwa.googlegroups.com> Hello Tim: One more thing: There some Python scripts that can extract text from PDF or WORD file? Thx From steve.morin at gmail.com Fri Nov 18 14:41:50 2005 From: steve.morin at gmail.com (Steve) Date: 18 Nov 2005 11:41:50 -0800 Subject: Web-based client code execution In-Reply-To: <3u6ngeFvh3v1U1@individual.net> References: <3u6ngeFvh3v1U1@individual.net> Message-ID: <1132342910.799932.58720@g44g2000cwa.googlegroups.com> AJAX works because browsers can execute javascript. I don't know of a browser that can execute python. Basically your stuck with java or javascript because everything else really isn't cross platform. From aleax at mail.comcast.net Fri Nov 25 23:17:15 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 25 Nov 2005 20:17:15 -0800 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> Message-ID: <1h6lmts.1fr63yddwj4y4N%aleax@mail.comcast.net> Steven D'Aprano wrote: > On Thu, 24 Nov 2005 17:43:22 +0100, Martin P. Hellwig wrote: > > > if I owned a company > > making profit on software sales (sale =! support) you sign a death wish > > for using GPL > > Apart from Microsoft, and possibly Quark (makers of Quark Express desktop > packaging software), and perhaps a few console game developers, is there > any company making a profit on software sales? I believe Oracle is doing fine (and they appear to be trying to buy up most everybody else -- other companies which used to make profits from software sales before they got gobbled up). I think SAP and Adobe aren't doing badly, either, but I haven't checked up on them in a while. I'd be surprised if there weren't many relative minnows that I didn't think of, beyond the few "obvious" big fishes above listed. Alex From skip at pobox.com Thu Nov 17 13:10:04 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 17 Nov 2005 12:10:04 -0600 Subject: test_locale & test_pty fail for 2.4 SVN on Solaris 8/10 Message-ID: <17276.51068.588557.526912@montanaro.dyndns.org> We are getting a couple test failures at work when building Python 2.4.2 or the 2.4 Subversion branch on Solaris 8 and Solaris 10 (both on PC hardware). test_pty fails and test_locale is unexpectedly skipped. The locale environment is LC_ALL=C LC_CTYPE=iso_8859_1 I also tried test_locale with no LC_* environment variables set. Should my LC_* settings be different? Can anyone else confirm these problems? Thx, Skip From wahn at acm.org Tue Nov 22 13:48:33 2005 From: wahn at acm.org (wahn at acm.org) Date: 22 Nov 2005 10:48:33 -0800 Subject: Embedded Python interpreter and sockets References: <1132366056.922805.122480@g14g2000cwa.googlegroups.com> <1132373753.139661.124560@g44g2000cwa.googlegroups.com> Message-ID: <1132685313.853752.200050@z14g2000cwz.googlegroups.com> Hi Chris, Thanks for your help. I'll try that ... Cheers, Jan From martin at v.loewis.de Fri Nov 25 17:46:53 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 25 Nov 2005 23:46:53 +0100 Subject: Which License Should I Use? In-Reply-To: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: <4387945D.20103@v.loewis.de> mojosam wrote: > How do I decide on a license? If you want to look at this from a legal point of view, I highly recommend reading Larry Rosen's book, Open Source Licensing. It covers issue you would never have thought of without studying law, and gives good advice (IMHO). Regards, Martin From jgardner at jonathangardner.net Sat Nov 26 13:16:49 2005 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 26 Nov 2005 10:16:49 -0800 Subject: How to get started in GUI Programming? References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1133029009.064832.101810@g14g2000cwa.googlegroups.com> I would argue with your assertion that either TKinter of PyGTK are the best. There are several other good alternatives, including wxPython and PyQt, which are very comparable, if not better. I would strongly suggest starting with PyQt. It's my personal favorite. I wrote a short tutorial on the Python Wiki. http://wiki.python.org/moin/JonathanGardnerPyQtTutorial I find that the Qt API is a lot simpler than the alternatives. Plus, it has great documentation. From aleax at mail.comcast.net Wed Nov 9 22:53:21 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 9 Nov 2005 19:53:21 -0800 Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> Message-ID: <1h5rz50.hngir9no5aocN%aleax@mail.comcast.net> bonono at gmail.com wrote: > Alex Martelli wrote: > > This becomes a valid list comprehension by writing 'if' instead of > > 'when'. > valid, yes. efficient, I am not sure. > > [ x for x in xrange(10000000) if p(x) ] > > means I need to go through the whole range even if p = lambda x: x < 2. Of course, barring semantically-very-deep optimizations (ones no production implementation I know of ANY language would even try). And, your POINT would be...? Alex From steve at REMOVETHIScyber.com.au Thu Nov 3 17:26:09 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 09:26:09 +1100 Subject: when and how do you use Self? References: <4369d4f0$0$18073$626a14ce@news.free.fr> <436a62a7$0$11127$626a14ce@news.free.fr> Message-ID: On Thu, 03 Nov 2005 20:19:03 +0100, bruno at modulix wrote: > Steven D'Aprano wrote: >> On Thu, 03 Nov 2005 10:14:23 +0100, bruno at modulix wrote: >> >> >>>Tieche Bruce A MSgt USMTM/AFD wrote: >>> >>>>I am new to python, >>>> >>>> >>>> >>>>Could someone explain (in English) how and when to use self? >>>> >>> >>>Don't use self. Use other. >> >> >> Are you serious? > > Are you seriously wondering if I am serious ? Well, you are either serious, or you're guilty of giving extremely bad advice to a newbie who will probably have even less ability to recognise an in-joke than I do. -- Steven. From fuzzyman at gmail.com Wed Nov 16 07:04:17 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Nov 2005 04:04:17 -0800 Subject: Reinvent no more forever In-Reply-To: References: Message-ID: <1132142657.163928.16460@f14g2000cwb.googlegroups.com> Ben Finney wrote: > Howdy all, > Hello, > On dirtSimple.org[0], PJE wrote: > > "Why is Python "blessed" with so much reinvention? Because it's > often cheaper to rewrite than to reuse. Python code is easy to > write, but hard to depend on. You pretty much have to: > > 1. limit yourself to platforms with a suitable packaging > system, > 2. bundle all your dependencies into your distribution, or For pure python modules I don't find this to be a big problem. > 3. make your users do all the work themselves > > Ouch. No wonder rewriting looks easier." > [snip..] > I now have a setuptools package of my Enum implementation. Should I > submit it to PyPI? > > Advantages: > > - I can declare a dependency on that package for all my other > packages that need such functionality, instead of bundling it > every time. > > - Others can benefit from my code, instead of yet again including an > Enum implementation (home-grown, or picked from a cookbook) by a > simple dependency declaration. > > - The code hopefully gets improved and generalised and all the other > benefits that accrue to software with many users. > These are all very compelling reasons. > Disadvantages: > > - Proliferation. What's the protocol when[1] someone else puts an > (incompatible, differently-specified) Enum implementation into > PyPI? > That shouldn't be any more of a problem than the current situation. In fact as the setuptools system becomes more established then it should be easier for people to discover that an existing package does what they want - rather than creating their own. > - Naming. How many ways can a package providing an Enum be named? > I'd prefer mine to be named "Enum" or "enum", but why should mine > be the one that claims that name? > I think "first come - first served" is the only possible way this can work. > - It's just a pretty simple type, with unit tests. Does this really > justify a PyPI package? > If it solves a common problem in an elegant way, then it's better shared. :-) > This is common to any repository of code. But the "automatic > dependency" problem means that all those packages, and many more > outside that repository, need to know how those problems are resolved. > > Operating system distributors have policies (to greater or lesser > degrees of strictness) to ensure this kind of quality control. My > understanding of PyPI is that there's no such policy. > > I'd love to follow the mantra PJE espouses, but if it's good for one > person it's probably good for countless others. How do we deal with > that? What actions can we take in advance to prevent problems in > future? > Isn't setuptools *the system* that addresses these issues ? It provides a way to track and auto-install dependencies - so long as you have the right kind of netowrk connection [1] and the packager of the dependencies provides them in a way compatible with setuptools. All the best, Fuzzy http://www.voidspace.org.uk/python/index.shtml [1] setuptools uses python code to access the internet and install dependencies. Python code can't fetch https URLs through a proxy and can't use a SOCKS proxy at all. That means with some kinds of internet conenctions (e.g. behind company firewalls) it doesn't work. Building optional support for pycurl into setuptools could possibly resolve this. > > [0] > > [1] Of course, someone already has. I prefer mine to theirs, hence the > question. > > -- > \ "I planted some bird seed. A bird came up. Now I don't know | > `\ what to feed it." -- Steven Wright | > _o__) | > Ben Finney From steve at REMOVETHIScyber.com.au Thu Nov 3 11:23:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 03:23:59 +1100 Subject: reading internet data to generate random numbers. References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> <11mj21gr6rjgc65@corp.supernews.com> <86ll06jr79.fsf@bhuda.mired.org> <4369B2CF.70201@REMOVEMEcyber.com.au> <11mkcg2l9d89qff@corp.supernews.com> Message-ID: On Thu, 03 Nov 2005 15:51:30 +0000, Grant Edwards wrote: >> I have no idea what distribution data from the Internet would >> have, I would imagine it is *extremely* non-uniform and *very* >> biased towards certain values (lots of "<" and ">" I bet, and >> relatively few "\x03"). > > I've never heard of anybody using the data as source of > entropy. All the entropy gathering I've read about used the > timing of network events, not the user-data associated with > those events. Me neither, but the original poster did ask how to read every nth byte of "the Internet stream", so I assumed he had something like that in mind. -- Steven. From simon.brunning at gmail.com Tue Nov 8 05:58:44 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 8 Nov 2005 10:58:44 +0000 Subject: any python module to calculate sin, cos, arctan? In-Reply-To: <1d987df30511080240x6e02b542x101442299322805f@mail.gmail.com> References: <1d987df30511080240x6e02b542x101442299322805f@mail.gmail.com> Message-ID: <8c7f10c60511080258g62016c14x@mail.gmail.com> On 08/11/05, Shi Mu wrote: > any python module to calculate sin, cos, arctan? I seem to be posting loads of links to the docs today... -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ChuckDubya at gmail.com Mon Nov 7 21:41:39 2005 From: ChuckDubya at gmail.com (ChuckDubya at gmail.com) Date: 7 Nov 2005 18:41:39 -0800 Subject: Text Auto-fill Message-ID: <1131417699.631271.156480@g49g2000cwa.googlegroups.com> It's common in web browsers to have a text auto-fill function for personal information or passwords or whatnot. The flavor that I'm referring to is the kind that pops up as you're typing the word, not the kind that fills text fields before typing has started. Well I want to know how to do that in Python. I'm looking to edit IDLE so that it doesn't take me forever to code four lines. Eventually, I want to create a Visual Basic-type environment for myself. I'm a moron, and I need all the coding help I can get. From cs at totallybogus.com.invalid Thu Nov 17 06:21:54 2005 From: cs at totallybogus.com.invalid (Cousin Stanley) Date: Thu, 17 Nov 2005 05:21:54 -0600 Subject: python-mysqldb__debian_to_freebsd References: <1132181273_661@spool6-east.superfeed.net> <8664qropch.fsf@bhuda.mired.org> Message-ID: <1132226514_2071@spool6-east.superfeed.net> > .... > For the interested, the OP (Stanley Kitching), wants to use a > python-mysqldb module on his web host running FreeBSD. They don't have > the that installed, so he tried getting the Debian binary distrubtion > of the library to work, and failed. He's wondering if this is at all > possible. > > Answer: yes, it might (key word - might) be made to work. Linux shared > libraries have been made to work with native applications on FreeBSD > before. I don't have the details, but would expect you'd have to > install large chunks of a Debian system to make this work. If you > really want to do this, let me know and I'll chase the details down > for you. > > However, that's the wrong way to do this. First step - ask your > hosting service to install databases/py-MySQLdb. That's the Python > MySQLdb port in the FreeBSD ports tree. > .... Mike .... Although I've never done it personally, I have seen a few newsgroup references that some Debian/FreeBSD packages are interchangeable so thought the minimal effort required for uploading the Debian MySQLdb package I have might be worth the long shot .... > However, that's the wrong way to do this. First step - ask your > hosting service to install databases/py-MySQLdb. > > That's the Python MySQLdb port in the FreeBSD ports tree. > Installing it should be trivial. > .... I did a bit more google-izing last night and found that a FreeBSD/MySQLdb install should indeed be a trivial matter to install via FreePorts .... I'll go ahead and petition the host for an install .... Thanks very much for taking the time to provide a detailed explanation and your kind offer for further assistance .... Both are greatly appreciated .... -- 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 ale.of.ginger at gmail.com Tue Nov 1 18:05:19 2005 From: ale.of.ginger at gmail.com (ale.of.ginger at gmail.com) Date: 1 Nov 2005 15:05:19 -0800 Subject: If Statement Error (Tic Tac Toe) In-Reply-To: <86oe54yovn.fsf@bhuda.mired.org> References: <1130878530.389205.179640@g43g2000cwa.googlegroups.com> <86wtjsyrcy.fsf@bhuda.mired.org> <1130882880.696770.8600@g47g2000cwa.googlegroups.com> <86oe54yovn.fsf@bhuda.mired.org> Message-ID: <1130886319.788657.291850@g49g2000cwa.googlegroups.com> So is there a way I have to set up the string OX in the beginning? Is this where it houses the location of the Xs and Os to determine whether or not a letter is already there? From bonono at gmail.com Thu Nov 10 05:22:39 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 02:22:39 -0800 Subject: append to non-existing list In-Reply-To: References: <4371fb5a$0$18086$626a14ce@news.free.fr> <437251f4$0$25824$626a14ce@news.free.fr> <1131616482.442597.308320@g43g2000cwa.googlegroups.com> Message-ID: <1131618159.266735.76560@g43g2000cwa.googlegroups.com> Yves Glodt wrote: > I need this (invalid example-html follows): > > >

title of page

> > > import time > > print "

Hello, today is: %s

" % (time.ctime()) > > ?> > > Cheetah template ? But I like Kid better as I don't want python in HTML, Kid IMO strikes the balance between python feature and XHTML so the template is still readable by any XHTML editors. From timr at probo.com Sun Nov 13 03:33:13 2005 From: timr at probo.com (Tim Roberts) Date: Sun, 13 Nov 2005 08:33:13 GMT Subject: os.chown() References: Message-ID: James Colannino wrote: > >Hey everyone. I tried to use os.chown() in the following manner: > >os.chown('filename', 'username', 'groupname') > >I got an error, and when I googled for this function I realized that I >must pass the numerical uid and gid. My question is, is there a way for >me to change ownership based on the name instead of the number? Perhaps >there's a function that will let me lookup the uid from the username, >and the gid from the groupname? One way is: os.system( 'chown username:groupname filename') Are you doing this as root? The chown function is usually restricted to root. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From lycka at carmen.se Tue Nov 1 07:18:49 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 01 Nov 2005 13:18:49 +0100 Subject: Need Python Pro for Help!! Plzz In-Reply-To: References: <5uSdnSSK7vYrTfneRVn-pQ@giganews.com> Message-ID: Alex Hunsley wrote: > My apologies to the OP for assuming he was wanting to have a private one > on one email discussion. There are certainly times when it's appropriate to request private assistance, and I personally think it's ok to make such a request available in this forum, but maybe I'm not representative for the community. It didn't look like a serious RFQ though. ;^) > Setting up a community is a more commendable thign to do. On the other hand, joining one that already exists and seems to cover the same subject is probably more practical. I guess the tutor mailing list has a non-obvious name, but it seems to be just what the doctor ordered in this case. I think additional fora like this google group do more harm than good. It's one thing if it covers a need that isn't well covered elsewhere, for instance Python discussion in some other language than English (Essemessese?) or some particular aspect of Python programming, but last time I looked, tutor was an excellent newbie resource. As on comp.lang.python, the python-tutor sub-culture seems to favour spelled-out words in English in contrast to e.g. SMS style though. I guess the general idea is to make it as easy as possible for those who are to read and answer the questions. They do enough unpaid work anyway. From samrobertsmith at gmail.com Fri Nov 11 17:23:30 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 11 Nov 2005 14:23:30 -0800 Subject: directory listing In-Reply-To: <192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu> References: <14cltzqwyklwl.17i7f7qnfnlh0$.dlg@40tude.net> <192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu> Message-ID: <1d987df30511111423o572172eay36870d09220233d7@mail.gmail.com> On 11 Nov 2005 22:00:04 GMT, Michael Konrad wrote: > Richard Townsend wrote: > > > On 11 Nov 2005 21:20:33 GMT, SU News Server wrote: > > > > Try passing the full pathname of each item to os.path.isdir() > > > > You can create the pathname using os.path.join(directory, x) > > > > > > > > I wonder if I can join ./, so I don't have the full path in each > entry? > > Thank you for responding. > _Michael > > > -- > http://mail.python.org/mailman/listinfo/python-list > I tried this and no error reported but nothing appear on the console, why? import os def buildList( directory='c:\TEMP' ): dirs = [ ] listing = os.listdir(directory) for x in listing: x = os.path.join(directory, x) print x if os.path.isdir(x): dirs.append(x) return dirs From zanesdad at bellsouth.net Thu Nov 3 13:16:02 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 03 Nov 2005 13:16:02 -0500 Subject: publicity for Python-related projects Message-ID: <1131041762.14134.13.camel@localhost.localdomain> If anyone has a project written in Python or usable to Python programmers, I'd like to blog about new releases (or other news) of your project. I'd really like to focus on open source projects, but I would love to mention non-open source projects if I feel there is sufficient benefit to the community. This is something I'm planning on an ongoing basis and not just a one-time thing. Whenever you have news (a release, corporate funding, new developer joining the team, etc.) just email me at zanesdad at bellsouth dot net with the name of the project, a link to the project's homepage, the release (or news) information, and what the project is about. I'm planning on posting nightly at around 5PM GMT +5 (10PM Eastern time in the states), so email that I receive before that time should be posted the same day. Jeremy Jones From venkatasubramanian at gmail.com Tue Nov 8 07:59:46 2005 From: venkatasubramanian at gmail.com (venk) Date: 8 Nov 2005 04:59:46 -0800 Subject: Diff. between Class types and classic classes Message-ID: <1131454786.272355.314740@z14g2000cwz.googlegroups.com> Hi, can some one properly explain the differences between class types and classic classes? ... Still face problems in identifying what is what. From fredrik at pythonware.com Tue Nov 1 13:18:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 1 Nov 2005 19:18:38 +0100 Subject: Python's website does a great disservice to the language References: Message-ID: "CppNewB" wrote: > I was trying to advocate using Python for an upcoming prototype, so my boss > went out to take a look at the documentation and try and get a feel for what > the language is all about. > > First comment; "I hope the language is designed better than the site." so your boss is a troll, and you cannot use a search engine. I hope you're company is more competent than it appears ;-) (hint: a redesign is in progress, sponsored by the PSF. google for "python.org redesign 2005" for more info. bte, the current design was created by people who've won more design awards than most web firms; the design is old (1998), not unusable...) From enleverlesO.OmcO at OmclaveauO.com Thu Nov 17 16:23:51 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Thu, 17 Nov 2005 22:23:51 +0100 Subject: searching for files on Windows with Python References: <20051117133525.21047.qmail@server285.com> Message-ID: <437cf6e6$0$7356$636a55ce@news.free.fr> Hi! But fnmatch (or glob) is unix-like. With few error in windows (sample ? trye '*.' ) Test this code rather: import os l=os.popen4('dir c:\\python\\*.pyw /S /B')[1].readlines() print ''.join(l) @-salutations -- Michel Claveau From mwm at mired.org Thu Nov 10 16:28:44 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 16:28:44 -0500 Subject: how to modify code while debugging it without having to stop and then restart debugger References: <86oe4t8tc7.fsf@bhuda.mired.org> Message-ID: <86r79o5h0z.fsf@bhuda.mired.org> Magnus Lycka writes: > Mike Meyer wrote: >> In that case, you're using the wrong IDE. I run the Python interpeter >> inside of Emacs. I edit my code in another buffer. In the source code >> buffer, I hit M-C-x, and the current version of the function I'm >> currently editing gets sent to the interpreter. Reload is pretty easy >> as well - C-c RETURN, and the module I'm editing gets reloaded. > > As far as I understand, the OP wanted to do this while single-stepping > through the program he's editing. While this might work as a kind of > exploration, it's probably not an optimal development strategy. It > might be difficult to predict how the program will run the next time > if you manipulate it during execution. Yes, that's what he wanted. I was pointing out that there are alternatives between "changing the function while you're debugging it" and "retyping the function completely at the interactive prompt." > I think test-driven development as described e.g. in my EPC presentation > last year is more rewarding: http://www.thinkware.se/epc2004test/ > (See e.g. the log.html) Depends on what you're doiing. If you know the subject area well enough that you casn design all the objects and methods in advance so you can write your unit tests, then this is indeed very rewarding. If, on the other hand, you are doing something where you don't have a clear understanding of what all the components are, and how they interact, then it's more important to try things out to gain that understanding than it is to have tests for components or methods that you may well discard or morph beyond recognition tomorrow. The dynamic nature of Python, coupled with the bundled interactive interpreter, makes it particularly good for this type of programming. > I guess it's a bit like driving an old crappy car, and then getting > into a new Toyota. I can understand that it seems strange not to > have the trunk filled with tools if you're about to take a long trip, > but it's probably a mistake to think that this will make the journey > with the Toyota more problematic than the trip would have been with > a car that you need to repair every now and then. Nice analogy. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From eurleif at ecritters.biz Tue Nov 8 03:13:02 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 08 Nov 2005 08:13:02 GMT Subject: how to stop a loop with ESC key? [newbie] In-Reply-To: References: Message-ID: mo wrote: > Can somebody explain how to stop a WHILE loop in running program by pressing > ESC key? On Unix-like systems try: import termios, fcntl, sys, os fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) i = 0 try: while 1: print i i += 1 try: char = sys.stdin.read(1) if char == '\x1b': print "Bye!" break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) From bokr at oz.net Mon Nov 21 18:31:59 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 21 Nov 2005 23:31:59 GMT Subject: Why are there no ordered dictionaries? References: <43814eaa.343166777@news.oz.net> <1132549972.254320.287490@g44g2000cwa.googlegroups.com> Message-ID: <438258df.411315550@news.oz.net> On 20 Nov 2005 21:12:52 -0800, "bonono at gmail.com" wrote: > >Bengt Richter wrote: >> On Sun, 20 Nov 2005 22:03:34 +0100, Christoph Zwerschke wrote: >> >> Ordering the keys isn't the normal case, and can be done easily when >> >> needed. >> > >> >That depends. Maybe I do not want the keys to be sorted alphabetically, >> >but according to some criteria which cannot be derived from the keys >> >themselves. >> You mean involving also the values? What's wrong with >> sorted(plaindict.items(), key=your_ordering_function) ? >> >Not according to the content of the data, not just the "key". Or in >other words, some other metadata that is not present in the data. A >typical thing, like order of creation. Or some arbitary order. For >example : > >I present a data grid/table in a HTML form and the user just drag and >drop and rearrange the columns order. ^^[1] [1] implies known info of before and after rearrangement. Where do these come from, and are the two states expressed as ordered sets of keys generated and stored somewhere? The point is, to re-order, you need a mapping from unordered data dict keys to values which the sorted builtin function will order in the way you want. (BTW, if you use DSU, make sure the data is not modifying your sort in an undesired way. Passing a key function to sorted makes it easy to exclude unwanted data from the sort). If you have data that determines a new ordering of keys, it has to be accessed somehow, so you just need to make it accessible to a handy helper that will generate your key function. E.g, with before and after lists of keys expressing e.g. drag-drop before and after orderings, lambda can do the job of getting you dict items in the new order, e.g., where bef and aft are lists that define the desired orderings before and after in the sense of sort_precedence = bef.index[key_in_bef] and same for aft. sorted(thedict.items(),key=lambda t:dict(zip(bef,((k in aft and aft.index(k) or len(aft)+bef.index(k)) for k in bef))[t[0]]) Ok, that one-liner grew a bit ;-) > >Of course, you may say, just put another column that represent >this(some reporting programs I have seen do it this way) and that is an >option but not the only option. > Maybe you could keep the rearranged_keys vector in a per-user cookie, if it's a web app and amounts to a user personalization? ( posting delayed >12 hrs due to news server prob ;-/ ) Regards, Bengt Richter From hancock at anansispaceworks.com Mon Nov 21 09:52:42 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 21 Nov 2005 08:52:42 -0600 Subject: Any royal road to Bezier curves...? In-Reply-To: References: Message-ID: <20051121085242.32e1a591@samwise.anansi> On Sun, 20 Nov 2005 23:33:36 -0500 "Warren Francis" wrote: > I'm fairly new to Python (2-3 months) and I'm trying to > figure out a simple way to implement Bezier curves... So > far I've tried the following: > > http://runten.tripod.com/NURBS/ > ...which won't work because the only compiled binaries are > for Windows 2000, python 2.1. I'm on Windows XP (for > now), using Python 2.4. I downloaded the source > distribution, but the header files aren't included, so I'm > not sure how to compile it. NURBS are not actually Bezier curves, AFAIK, they are a superset of some kind (which means they're probably better to use, but harder to implement). > It appears there's some bezier functionality in the python > that comes Blender... but I'm not savvy enough yet to try > and extract whatever makes beziers work there, to make it > work in my general-purpose Python programs. Not a specific recommendation, and I don't know if it's any more comprehensible, but you will find that Skencil also implements Bezier curves (in 2D). Skencil is mostly in Python, but uses a lot of C, so I don't know if it handles beziers in Python or C (I'm still learning my way around the code, myself). Inkscape, of course, does too, but in C. http://www.inkscape.org > Basically, I'd like to specify a curved path of an object > through space. 3D space would be wonderful, but I could > jimmy-rig something if I could just get 2D... Are bezier > curves really what I want after all? Or NURBS, yeah, probably. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From jeremy+complangpython at jeremysanders.net Tue Nov 8 05:20:18 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 08 Nov 2005 10:20:18 +0000 Subject: PyFLTK - an underrated gem for GUI projects References: <87acgg3e8n.fsf@jupiter.g2ctech> Message-ID: aum wrote: > But for smaller gui programs not needing the power of wx, I find I get > the job done much more quickly and effortlessly with PyFLTK. Interesting. I've found PyQt very easy to use too. I wonder how they compare (providing you can GPL your app, of course). -- Jeremy Sanders http://www.jeremysanders.net/ From steve at holdenweb.com Tue Nov 1 07:20:12 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Nov 2005 12:20:12 +0000 Subject: looking for a good python module for MS SQL server In-Reply-To: References: Message-ID: Jarek Zgoda wrote: > Steve Holden napisa?(a): > > >>>>>>Does anyone know a good python mudule that works with MS SQL server? >>>>> >>>>>Google will yield something, but I prefer adodbapi over specialized >>>>>modules. Works good with SQLServer using SSPI auth (others rather not). >>>> >>>>Though it does have problems with stored procedures. >>> >>>Didn't discover any of these. >>> >> >>Maybe things have changes since I last used adodbapi - can you actually >>run stored procedures now? > > > Things didn't change, as last update to adodbapi was long time ago... I > had no problems with stored procedures accessed using cursor's execute() > method (i.e. execute('exec sp_someproc, param')), but I never tried to > get any results, just call sp and commit or rollback. > Thanks. The situation does remain unchanged, then. 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 jzgoda at o2.usun.pl Tue Nov 1 05:47:22 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 01 Nov 2005 11:47:22 +0100 Subject: looking for a good python module for MS SQL server In-Reply-To: References: Message-ID: Steve Holden napisa?(a): >>> Does anyone know a good python mudule that works with MS SQL server? >> >> Google will yield something, but I prefer adodbapi over specialized >> modules. Works good with SQLServer using SSPI auth (others rather not). >> > Though it does have problems with stored procedures. Didn't discover any of these. -- Jarek Zgoda http://jpa.berlios.de/ From blahman Fri Nov 4 00:14:22 2005 From: blahman (blah@blah.blah) Date: Thu, 03 Nov 2005 23:14:22 -0600 Subject: Can Anyone Help me on this References: Message-ID: Thanks Guys, Wow, i didnt knew that there was alist reverse function. thx. also. i need a good documentation of the os and sys modules as well as builtin functions of python. the standard python documentation doesnt work for me. can u recommend something? -- * Posted with NewsLeecher v3.0 Beta 7 * http://www.newsleecher.com/?usenet From metiu.uitem at gmail.com Tue Nov 22 05:57:14 2005 From: metiu.uitem at gmail.com (metiu uitem) Date: 22 Nov 2005 02:57:14 -0800 Subject: Converting a flat list to a list of tuples Message-ID: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> Say you have a flat list: ['a', 1, 'b', 2, 'c', 3] How do you efficiently get [['a', 1], ['b', 2], ['c', 3]] I was thinking of something along the lines of: for (key,number) in list: print key, number but it's not working... Thank you From fuzzyman at gmail.com Thu Nov 24 05:36:24 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Nov 2005 02:36:24 -0800 Subject: Opening for Python Programmers at Japan In-Reply-To: References: Message-ID: <1132828584.946747.197840@g49g2000cwa.googlegroups.com> I'll do the job from the UK for you. ;-) Fuzzyman http://www.voidspace.org.uk/python/index.shtml From igouy at yahoo.com Wed Nov 30 02:59:23 2005 From: igouy at yahoo.com (igouy at yahoo.com) Date: 29 Nov 2005 23:59:23 -0800 Subject: Computer Language Shootout In-Reply-To: <1133318074.428631.320870@g14g2000cwa.googlegroups.com> References: <1133298307.938958.186070@f14g2000cwb.googlegroups.com> <1133299669.010298.283100@g14g2000cwa.googlegroups.com> <1133302092.368063.235410@o13g2000cwo.googlegroups.com> <438d040d.265637266@news.oz.net> <1133318074.428631.320870@g14g2000cwa.googlegroups.com> Message-ID: <1133337563.508863.198860@z14g2000cwz.googlegroups.com> bonono at gmail.com wrote: > Bengt Richter wrote: > > On 29 Nov 2005 14:08:12 -0800, igouy at yahoo.com wrote: > > > > >We don't scrape programs from news-groups, if you'd like the program to > > >be shown on the shootout then please attach the source code to a > > >tracker item. > > You asked for something, got a response, and then you haughtily[1] declare > > that it's not being served on a special platter from your cupboard, > > and you won't deign to "scrape" the serving onto your own platter. > > Pfui. Your apparent[1] attitude turns me off, not to mention your top-posting. > > > I don't see it as an attitude issue but wording. It is blunt but I can > see his point. He was asking people if it is possible to > submit(contribute) some code to the test. And based on what I saw on > his site, it is inappropriate for him to just take code from ML/usenet > as all codes there need proper author(beyond courtesy, there may be > copyright issue). That is my reading anyway. That is correct, we publish an author's work under Revised BSD - we can't just take a program from a newsgroup. > > If it was nicely explained why it needs to be done this way upfront(or > in the response), I believe you may not feel it this way. > > Interestingly, I find this response quite compatible with the > personality of this group. From peter at engcorp.com Thu Nov 24 07:55:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Nov 2005 07:55:11 -0500 Subject: return in loop for ? In-Reply-To: References: <4384F705.31CEC951@valid.org><86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > >>sepcifications > > did you mean: sceptifications ? > > (otoh, with 11,100 google hits, "sepcifications" should probably be > considered as a fully acceptable alternate spelling ;-) Not if they're all in pages at site:holdenweb.com ! From onurb at xiludom.gro Wed Nov 9 08:36:25 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 09 Nov 2005 14:36:25 +0100 Subject: append to non-existing list In-Reply-To: References: Message-ID: <4371fb5a$0$18086$626a14ce@news.free.fr> Yves Glodt wrote: > Hello, > > if I do this: > > for row in sqlsth: > ________pkcolumns.append(row[0].strip()) > ________etc > > > without a prior: > > pkcolumns = []; > > > I get this error on first iteration: > UnboundLocalError: local variable 'pkcolums' referenced before assignment > > > > I guess that's normal as it's the way python works...?!? yes sir. > My question is: Is there no way to append to a non existing list? No. Definitively. And that's a Good Thing(tm). How would you use something that doesn't exist ??? > I am lazy for declaring it first, s/declaring/instantiating/ If you were to use your own class Toto, would you ever hope that the following code would work : for v in some_seq: toto.dothis(v) without instantiating Toto and binding it to the name 'toto' before ? Well, in Python, a list is an instance of class list. There are syntactic sugar to instanciate a list (or a tuple or a string or a dict etc), but this: my_list = [] is strictly equivalent to this: my_list = list() Now let's try something else: class Machin(object): def append(self, value): pass class Bidule(object): def append(self, value): pass for i in range(10): m.append(i) How should Python interpret this ? Should it create a list, or a Machin, or a Bidule, or an instance of whatever imported class having a append() method ? > IMHO it bloats the code, run your python interpreter and type: import this Then read carefully. Now if being explicit still hurts your personal convictions, there's this other language with a name starting with p... !-) > and (don't > know if it's good to say that here) where I come from (php) I was used > to not-needing it... Not creating an Array before using it is Bad Style in PHP (and generate a Warning BTW). There are warts in Python (as in any other languages), and there are things that sometimes bore me but are not really warts. But having to explicitely instanciate objects can't be seen as a wart in any language IMHO !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From peter at engcorp.com Thu Nov 17 23:02:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Nov 2005 23:02:01 -0500 Subject: searching for files on Windows with Python In-Reply-To: <437cef1b$1_2@newspeer2.tds.net> References: <437cef1b$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > I always use Jason Orendorff's path module for this kind of stuff. It's > way easier to use than os.whatever: > > import path > files = path.path(pathToSearch).walkfiles(filename) A minor enhancement (IMHO) (though I certainly agree with Kent's recommendation here): since there is nothing else of interest in the "path" module, it seems to be a fairly common idiom to do "from path import path" and skip the doubled "path.path" bit. -Peter From dcrespo at gmail.com Wed Nov 9 08:09:17 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 9 Nov 2005 05:09:17 -0800 Subject: Application monitor In-Reply-To: References: <1131399761.209133.19690@g49g2000cwa.googlegroups.com> Message-ID: <1131541757.708350.72750@g14g2000cwa.googlegroups.com> Many thanks for your answers. Respect Init, I need a cross platform solution. Most of times my system will run in Win98 and XP (more on XP than 98) Respect Twisted... Mmm... I already started with another networking library (TCPServer and SimpleXMLRPCServer), and I wouldn't like to mix things because I don't know so much about those libraries. I know that Twisted can do what I already have. But replacing it can be a hard task. So I would like to have a function like FindPID(exename) --> PID, or something more generic that could tell me the PID of a running program, and kill him in a certain moment. Daniel From grflanagan at yahoo.co.uk Tue Nov 22 11:03:37 2005 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 22 Nov 2005 08:03:37 -0800 Subject: help with using temporary files Message-ID: <1132675417.303025.105490@f14g2000cwb.googlegroups.com> Hello I'm sure its basic but I'm confused about the error I get with the following code. Any help on basic tempfile usage? ActivePython 2.4.1 Build 247 (ActiveState Corp.) based on Python 2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from tempfile import NamedTemporaryFile >>> >>> tmp = NamedTemporaryFile() >>> tmp.write("Hello") >>> tmp.close() >>> >>> print tmp.name c:\docume~1\gerard\locals~1\temp\tmpxqn4yl >>> >>> f = open(tmp.name) Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\docume~1\\gerard\\locals~1\\temp\\tmpxqn4yl' Thanks Gerard From y.glodt at sitasoftware.lu Thu Nov 10 04:46:46 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Thu, 10 Nov 2005 10:46:46 +0100 Subject: append to non-existing list In-Reply-To: <437251f4$0$25824$626a14ce@news.free.fr> References: <4371fb5a$0$18086$626a14ce@news.free.fr> <437251f4$0$25824$626a14ce@news.free.fr> Message-ID: <43731706.2010506@sitasoftware.lu> bruno at modulix wrote: > Yves Glodt wrote: > (snip) >> ok I see your point, and python's... >> >> (just FYI, and not to start a flamewar ;-): >> In php, the [] means "append to an array object". > > yes, I know this. > >> If the array does not exist yet, it's created. > > Which is what I don't like. It should crash. > >> [] *is* explicit for >> arrays, > > IIRC, you can also use it to sbscript strings, but I wouldn't bet my > life on this. > >> thus for php it's clear what you want.) > > Nope. You may be in the case where you think the array already exists, > and then you (well, I at least...) would prefer that PHP don't try to > second-guess you... If and when I want to create an object, I tell it. > If I dont tell "create me an array", I don't want one to come in existence. > (snip) >> an "undefined" notice, yes, not a warning... ;-) >> > (snip) >> Ok... I thank you for all the explanations. >> >> It helps me to see more far. I (and will continue to) use php for web, >> and wanna standardize on python for all non-web stuff we are doing, > > You might discover that Python is just great for web programming too !-) Which raises another question... :-) Is there a possibility to bring together apache and python in a way that I can embed python into html? Or even, write a smallish webserver in python (using twisted maybe) whose only purpose is to serve pages and execute the embedded code...? >> so I >> might be a frequent guest on this list... > > You're welcome !-) > And if you're a french speaker, there's also french-speaking mailing > list and newsgroups. Merci pour l'info, I am, but for now the volume of this list is enough for me ... :-) From simon.brunning at gmail.com Tue Nov 8 05:01:29 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 8 Nov 2005 10:01:29 +0000 Subject: Addressing the last element of a list In-Reply-To: <1131443023.638868.212340@f14g2000cwb.googlegroups.com> References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c60511080201w4d9e9076i@mail.gmail.com> On 8 Nov 2005 01:43:43 -0800, pinkfloydhomer at gmail.com wrote: > But if lst[42]["pos"] happens to hold an integer value, then > > a = lst[42]["pos"] > > will _copy_ that integer value into 'a', right? Nope. It will bind the name 'a' to the integer object. > Changing 'a' will not > change the value at lst[42]["pos"] Integers are immutable - they can't be modified. So, "Changing 'a'" means binding the name 'a' to a different object. This will have no effect on other references to the original object. Reset your brain - . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From jparlar at cogeco.ca Thu Nov 10 01:38:47 2005 From: jparlar at cogeco.ca (Jay Parlar) Date: Wed, 9 Nov 2005 22:38:47 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: References: Message-ID: <7f51190b4b9255363b40b8f25c2db79b@cogeco.ca> On Nov 9, 2005, at 7:30 PM, Alex Martelli wrote: > No way -- the itertools module is and remains a PRECIOUS resource. If > you want an iterator rather than a list, itertools.ifilter is quite > appropriate here. Or if you're on 2.4 and want an iterator: (x for x in xrange(10) if p(x)) Jay P. From has.temp2 at virgin.net Sat Nov 19 19:38:45 2005 From: has.temp2 at virgin.net (has) Date: 19 Nov 2005 16:38:45 -0800 Subject: HTML generation vs PSP vs Templating Engines In-Reply-To: <1132435860.231522.29450@g14g2000cwa.googlegroups.com> References: <1132158690.299954.90920@g14g2000cwa.googlegroups.com> <1132225003.654019.309170@z14g2000cwz.googlegroups.com> <1132435860.231522.29450@g14g2000cwa.googlegroups.com> Message-ID: <1132447125.205918.53790@o13g2000cwo.googlegroups.com> riplin at Azonic.co.nz wrote: > I dislike embedding code or html in each other, apart from the > 'impurity' of mixing code and user interface it makes them inseparable. > > Using templates means that the code can work with different templates, > and this should be seamless, it also means that different code can be > used with the templates, for example if different languages are used. This seems to contradict your statement that you dislike 'embedding code or html in each other', since the scenarios you describe still involve embedding presentation logic in markup. (The only templating systems that *completely* separate logic from markup are the DOM-style ones.) I assume what you really meant is that you don't like embedding *model* logic in markup, which is generally good design practice. However, templating systems that use Python for presentation logic (Karrigell, PSP, Nevow, HTMLTemplate, etc) certainly don't force you to put model logic into the template; you are quite entitled to keep that separate as per MVC. They just don't *enforce* the model logic/presentation logic separation as some authoritarian custom language-based systems do. HTH From nnorwitz at gmail.com Tue Nov 22 02:10:08 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 21 Nov 2005 23:10:08 -0800 Subject: Any college offering Python short term course? In-Reply-To: References: Message-ID: <1132643408.884816.107480@z14g2000cwz.googlegroups.com> There is the BayPiggies user group: baypiggies at python.org. It meets monthly alternating between Mt. VIew (Google) and San Bruno (IronPort). n -- bruce wrote: > hey... > > i'm looking for classes (advanced) in python/php in the bay area as well... > actually i'm looking for the students/teachers/profs of these classes... any > idea as to how to find them. calling the various schools hasn't really been > that helpful. The schools/institutions haven't had a good/large selection... > it appears that some of the classes are taught by adjunct/part-time faculty, > and they're not that easy to get to... > > if anybody knows of user-groups that also have this kind of talent, i'd > appreciate it as well... > > send responses to the list as well!!! > > thanks > > -bruce > > > -----Original Message----- > From: python-list-bounces+bedouglas=earthlink.net at python.org > [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf > Of arches73 > Sent: Sunday, November 20, 2005 4:04 PM > To: python-list at python.org > Subject: Any college offering Python short term course? > > > Hi, > > I want to learn Python. I appreciate if someone point me to the > colleges / institutions offering any type of course in Python > programming in the Bay area CA. Please send me the links to my email. > > Thanks, > Arches > > > > -- > http://mail.python.org/mailman/listinfo/python-list From twic at urchin.earth.li Mon Nov 21 18:25:58 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 21 Nov 2005 23:25:58 +0000 Subject: Any royal road to Bezier curves...? In-Reply-To: References: Message-ID: On Mon, 21 Nov 2005, Tom Anderson wrote: > On Sun, 20 Nov 2005, Warren Francis wrote: > >> Basically, I'd like to specify a curved path of an object through space. 3D >> space would be wonderful, but I could jimmy-rig something if I could just >> get 2D... Are bezier curves really what I want after all? > > No. You want a natural cubic spline: In a fit of code fury (a short fit - this is python, so it didn't take long), i ported my old java code to python, and tidied it up a bit in the process: http://urchin.earth.li/~twic/splines.py That gives you a natural cubic spline, plus my blended quadratic spline, and a framework for implementing other kinds of splines. tom -- Gin makes a man mean; let's booze up and riot! From kdahlhaus at yahoo.com Tue Nov 29 10:17:22 2005 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 29 Nov 2005 07:17:22 -0800 Subject: Book: Cross-Platform GUI Programming with wxWidgets? In-Reply-To: <0sedndMNedzu4xbenZ2dnUVZ_tudnZ2d@comcast.com> References: <1133191147.864680.235820@g47g2000cwa.googlegroups.com> <0sedndMNedzu4xbenZ2dnUVZ_tudnZ2d@comcast.com> Message-ID: <1133277442.468741.60510@g49g2000cwa.googlegroups.com> Thanks. Did not know about that book. From arkanes at gmail.com Fri Nov 18 18:15:00 2005 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Nov 2005 17:15:00 -0600 Subject: Confused about namespaces In-Reply-To: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> References: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> Message-ID: <4866bea60511181515x79e1ce3ekc8c93b24c63e9a37@mail.gmail.com> On 18 Nov 2005 15:04:23 -0800, KvS wrote: > Hi all, > > to start with, excuse me, I'm still learning programming alltogether, > probably I'm making some fundamental mistake here... > > I have the files settings.py, GUIclasses.py and main.py in the same > directory. In the file main.py are the statements: > > import settings > from GUIclasses import * > > class Toepassing(wx.App): > def OnInit(self): > window = KFrame(None, "Testerdetest", (1000,900)) > self.SetTopWindow(window) > window.Show(True) > return True > > app = Toepassing(None) > app.MainLoop() > > In the file GUIclasses.py I have the statements: > > import wx > import wx.lib.mixins.listctrl as listmix > > class KFrame(wx.Frame): > def __init__(self, parent, title, Size): > ...some code... > self.lst = settings.attrLijst > ....some more code...... > > Now if I run the main.py file I get the error: > > File "G:\Programmeren\Codes contactenlijst\GUIclasses.py", line 40, > in __init_ > _ > self.lst = settings.attrLijst > NameError: name 'settings' is not defined > > Why is this? Since "from GUIclasses import *" this KFrame is now at > "the lowest" namespace and should therefore be able to make use of any > variables living there, including "settings.*", no? > import is not like a C/C++ #include - the code in the imported module is evaluated in it's own namespace, not in the namespace of the importing file. So no, this is expected behavior, and should be solved by importing settings in GUIclasses.py as well. You don't need to worry about multiple or redundent imports. > Thanks in advance! > > - Kees > > -- > http://mail.python.org/mailman/listinfo/python-list > From smcg4191zz at friizz.RimoovAllZZs.com Tue Nov 22 11:29:25 2005 From: smcg4191zz at friizz.RimoovAllZZs.com (Stuart McGraw) Date: Tue, 22 Nov 2005 09:29:25 -0700 Subject: Why are there no ordered dictionaries? References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> <1132652504.327803.154790@g49g2000cwa.googlegroups.com> <9smdnVdh0oNCkh7eRVn-uw@speakeasy.net> Message-ID: <11o6hr7s4886720@corp.supernews.com> "A.M. Kuchling" wrote in message news:9smdnVdh0oNCkh7eRVn-uw at speakeasy.net... [...] > What would improve the Cheese Shop's interface for you? Getting rid of those damn top level links to old versions. Seeing a long list of old versions, when 99% of visitors are only interested in the current version, is just visual noise, and really lame. Move the old version links onto the page describing the software. From geskerrett at hotmail.com Fri Nov 11 10:59:11 2005 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 11 Nov 2005 07:59:11 -0800 Subject: Inserting Records into SQL Server - is there a faster interface than ADO Message-ID: <1131724751.606322.162110@g44g2000cwa.googlegroups.com> I have a program that reads records from a binary file and loads them into an MS-SQL Server database. It is using a stored proc, passing the parameters. I am using pywin32 to create a connection object. Once the connection is open I simple pass the SQL formatted commands using cnx.Execute(sqlstring). My test examples; 20,000 records using the ADO connection: 0:04:45:45 If I setup the program to not send the record to the database - so all other variables and processes are constant, it simply just skips the cnx.Execute(sqlstring) step, then it takes only 0:00:25:78 to process thru the same number of trx. Obviously the times in my test are that , but I have a client that woud like to use this and has several million transactions to content with. So my questions is .... Is there a "faster" method I can use to connect to the SQL server ? Or does anyone have any "optimization" tips the can offer ? From dcrespo at gmail.com Wed Nov 9 11:16:48 2005 From: dcrespo at gmail.com (Daniel Crespo) Date: 9 Nov 2005 08:16:48 -0800 Subject: Make an exe file as a Windows Service Message-ID: <1131553008.253205.76110@g14g2000cwa.googlegroups.com> Hi to all, How can I install an exe file as a service through Python? Thanks From bonono at gmail.com Wed Nov 30 23:11:58 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 30 Nov 2005 20:11:58 -0800 Subject: Making immutable instances In-Reply-To: <86fypdmpi5.fsf@bhuda.mired.org> References: <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> <86u0duodzl.fsf@bhuda.mired.org> <1133333467.677454.134110@g49g2000cwa.googlegroups.com> <86acfloox6.fsf@bhuda.mired.org> <1133402729.430608.21400@g43g2000cwa.googlegroups.com> <86fypdmpi5.fsf@bhuda.mired.org> Message-ID: <1133410318.274544.326740@g47g2000cwa.googlegroups.com> Mike Meyer wrote: > Built-in types don't have a real dictionary. They have a C struct that > holds the various methods. The entries in the struct are called > "slots", hence the __slots__ magic attribute. That __slots__ makes it > impossible to add an attribute is documented as an implementation > detail. This makes me think that the same restriction on the builtin > types is the same. > > FWIW, dir returns a list built from a number of source. But if you > look at, for example, list.__dict__, you'll notice that it's not a > dict. > Well, in this case, would it be simple for the OP that if he wants to disallow this attaching additional things, just use __slot__. What I wan to say though is, if we can live with the inability of not able to attach to built-in types, why is it so difficult for other user defined class ? If the authors go to the length of not allowing it, so be it. They are afterall define it for their use and how someone else will use it don't matter. From gdamjan at gmail.com Mon Nov 14 07:57:40 2005 From: gdamjan at gmail.com (Damjan) Date: Mon, 14 Nov 2005 13:57:40 +0100 Subject: mod_python web-dav management system References: <2rCdnRspu_xWc-nenZ2dnUVZ_s6dnZ2d@comcast.com> Message-ID: > Zope has WebDAV support and is written in Python. You could > use Zope or perhaps use "parts" of it (since it is open source). I wouldn't use Zope as file storage. The ZODB is inefficient for storing big files. -- damjan From bonono at gmail.com Fri Nov 11 02:23:03 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 23:23:03 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <4373bcbc.150778327@news.oz.net> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131627394.890394.200070@g44g2000cwa.googlegroups.com> <4373bcbc.150778327@news.oz.net> Message-ID: <1131693783.437221.172430@z14g2000cwz.googlegroups.com> Bengt Richter wrote: > IOW, your "when condition(x)" (IIUIC) can be spelled "if condition(x) or stop()" neat trick. From aleax at mail.comcast.net Tue Nov 15 11:48:25 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 15 Nov 2005 08:48:25 -0800 Subject: best way to discover this process's current memory usage, cross-platform? References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132034089.402313.67290@o13g2000cwo.googlegroups.com> Message-ID: <1h625up.1o1rhfqu6dqwaN%aleax@mail.comcast.net> Neal Norwitz wrote: > Alex Martelli wrote: > > > > So, I thought I'd turn to the "wisdom of crowds"... how would YOU guys > > go about adding to your automated regression tests one that checks that > > a certain memory leak has not recurred, as cross-platform as feasible? > > In particular, how would you code _memsize() "cross-platformly"? (I can > > easily use C rather than Python if needed, adding it as an auxiliary > > function for testing purposes to my existing extension). > > If you are doing Unix, can you use getrusage(2)? On Unix, I could; on Linux, nope. According to man getrusage on Linux, """ The above struct was taken from BSD 4.3 Reno. Not all fields are meaningful under Linux. Right now (Linux 2.4, 2.6) only the fields ru_utime, ru_stime, ru_minflt, ru_majflt, and ru_nswap are maintained. """ and indeed the memory-usage parts are zero. > >>> import resource > >>> r = resource.getrusage(resource.RUSAGE_SELF) > >>> print r[2:5] > > I get zeroes on my gentoo amd64 box. Not sure why. I thought maybe it > was Python, but C gives the same results. Yep -- at least, on Linux, this misbehavior is clearly documented in the manpage; on Darwin, aka MacOSX, you _also_ get zeros but there is no indication in the manpage leading you to expect that. Unfortunately I don't have any "real Unix" box around -- only Linux and Darwin... I could try booting up OpenBSD again to check that it works there, but given that I know it doesn't work under the most widespread unixoid systems, it wouldn't be much use anyway, sigh. > Another possibiity is to call sbrk(0) which should return the top of > the heap. You could then return this value and check it. It requires > a tiny C module, but should be easy and work on most unixes. You can As I said, I'm looking for leaks in a C-coded module, so it's no problem to add some auxiliary C code to that module to help test it -- unfortunately, this approach doesn't work, see below... > determine direction heap grows by comparing it with id(0) which should > have been allocated early in the interpreters life. > > I realize this isn't perfect as memory becomes fragmented, but might > work. Since 2.3 and beyond use pymalloc, fragmentation may not be much > of an issue. As memory is allocated in a big hunk, then doled out as > necessary. But exactly because of that, sbrk(0) doesn't mean much. Consider the tiny extension which I've just uploaded to http://www.aleax.it/Python/memtry.c -- it essentially exposes a type that does malloc when constructed and free when freed, and a function sbrk0 which returns sbrk(0). What I see on my MacOSX 10.4, Python 2.4.1, gcc 4.1, is (with a little auxiliary memi.py module that does from memtry import * import os def memsiz(): return int(os.popen('ps -p %d -o vsz|tail -1' % os.getpid()).read()) )...: Helen:~/memtry alex$ python -ic 'import memi' >>> memi.memsiz() 35824 >>> memi.sbrk0() 16809984 >>> a=memi.mem(999999) >>> memi.sbrk0() 16809984 >>> memi.memsiz() 40900 See? While the process's memory size grows as expected (by 500+ "units" when allocating one meg, confirming the hypothesis that a unit is 2Kbyte), sbrk(0) just doesn't budge. As the MacOSX "man sbrk" says, """ The brk and sbrk functions are historical curiosities left over from earlier days before the advent of virtual memory management. """ and apparently it's now quite hard to make any USE of those quaint oddities, in presence of any attempt, anywhere in any library linked with the process, to do some "smart" memory allocation &c. > These techniques could apply to Windows with some caveats. If you are > interested in Windows, see: > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/ht > ml/UCMGch09.asp > > Can't think of anything fool-proof though. Fool-proof is way beyond what I'm looking for now -- I'd settle for "reasonably clean, works in Linux, Mac and Windows over 90% of the time, and I can detect somehow when it isn't working";-) Since people DO need to keep an eye on their code's memory consumption, I'm getting convinced that the major functional lack in today's Python standard library is some minimal set of tools to help with that task. PySizer appears to be a start in the right direction (although it may be at too early a stage to make sense for the standard library of Python 2.5), but (unless I'm missing something about it) it won't help with memory leaks not directly related to Python. Maybe we SHOULD have some function in sys to return the best guess at current memory consumption of the whole process, implemented by appropriate techniques on each platform -- right now, though, I'm trying to find out which these appropriate techniques are on today's most widespread unixoid systems, Linux and MacOSX. (As I used to be a Win32 API guru in a previous life, I'm confident that I can find out about _that_ platform by sweating enough blood on MSDN -- problem here is I don't have any Windows machine with the appropriate development system to build Python, so testing would be pretty hard, but maybe I can interest somebody who DOES have such a setup...;-) Alex From fredrik at pythonware.com Fri Nov 11 03:17:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 09:17:22 +0100 Subject: Good python reference? References: <1131693916.660356.75310@g44g2000cwa.googlegroups.com> Message-ID: "derek" wrote: > Hello! I'm new to the group and am looking for a decent reference for > information about the history / evolution of the Python language and > its features. Typing, scoping, etc... I'd appreciate any good links. $ tar xvfz Python-2.4.2.tgz $ cd Python-2.4.2 $ more Misc/HISTORY From steve at REMOVETHIScyber.com.au Fri Nov 4 22:09:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 14:09:07 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> <7xk6fovb1t.fsf@ruckus.brouhaha.com> <7xpspgvtyi.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 04 Nov 2005 16:06:45 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> A basic usage case: >> >> class Paper: >> size = A4 >> def __init__(self, contents): >> # it makes no sense to have class contents, >> # so contents go straight into the instance >> self.contents = contents > > So add: > > self.size = Paper.size > > and you've removed the weirdness. What do you gain here by inheriting? Documents which don't care what paper size they are will automatically use the default paper size on whatever system they are opened under. Send them to somebody in the US, and they will use USLetter. Send to someone in Australia, and they will use A4. In any case, even if you conclude that there is little benefit to inheritance in this particular example, the principle is sound: sometimes you gain benefit by inheriting state. -- Steven. From claudio.grondi at freenet.de Thu Nov 17 05:35:44 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 17 Nov 2005 10:35:44 -0000 Subject: IDLE question References: <1132217965.434209.122200@f14g2000cwb.googlegroups.com> Message-ID: <3u3186FvbckvU1@individual.net> schrieb im Newsbeitrag news:1132217965.434209.122200 at f14g2000cwb.googlegroups.com... > IDLE doesn't seem to honor PYTHONSTARTUP environment variable nor > sitecustomize.py > > How do you then customize in IDLE? > > (basically I want to execute the statement > from btools import * > each time I restart IDLEs Python Shell) > Following works for me: C:\Python24\pythonw.exe E:\Python24\Lib\idlelib\idle.py -r E:\Python24\sitecustomize.py or C:\Python24\pythonw.exe E:\Python24\Lib\idlelib\idle.py -c "import os; from path import path" content of my sitecustomize.py is: " import os from path import path " and both ways of invoking IDLE have the same effect (apparently of faking execution of not shown input line) of making the modules os and the class path available at start of IDLE. My question in this context: Can the PyShell.py file in C:\Python24\Lib\idlelib directory be edited somehow to achieve same effect? Claudio From steve at REMOVETHIScyber.com.au Mon Nov 28 08:44:05 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 29 Nov 2005 00:44:05 +1100 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: On Mon, 28 Nov 2005 08:44:04 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> Since real source code verifiers make no such sweeping claims to >> perfection (or at least if they do they are wrong to do so), there is >> no such proof that they are impossible. By using more and more >> elaborate checking algorithms, your verifier gets better at correctly >> verifying source code -- but there is no guarantee that it will be >> able to correctly verify every imaginable program. >> > I'm sure you can make a stronger statement than your last one. Doesn't > Godel's incompleteness theorem apply? I would have thought that no matter > how elaborate the checking it is guaranteed there exist programs which are > correct but your verifier cannot prove that they are. Yes, of course. By saying "no guarantee" I was guilty of understatement: at the very least, we can guarantee that the verifier will *not* correctly verify every possible program. (Which of course is no different from human programmers.) -- Steven. From mwm at mired.org Wed Nov 9 15:53:08 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 09 Nov 2005 15:53:08 -0500 Subject: append to non-existing list References: <4371EFBC.1030502@sitasoftware.lu> <4371FA57.40206@sitasoftware.lu> <1131549196.831764.104480@g47g2000cwa.googlegroups.com> <86wtjh90ti.fsf@bhuda.mired.org> Message-ID: <86acgd8rwr.fsf@bhuda.mired.org> "Fredrik Lundh" writes: > Mike Meyer wrote: > >> Float doesn't handle implicit conversion to anything but but builtin types. >> In particular, it doesn't check to see if the object beinng added has a >> __float__ method, and invoke that to do the conversion if it does. > > that's because __float__ is there to let you control what float() does, > not to get automatic type conversion for mixed operations. So is there a mechanism to indicate to the builtin types how they should coerce some user-defined class into themselves? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jim.eggleston at gmail.com Tue Nov 1 14:31:51 2005 From: jim.eggleston at gmail.com (jim.eggleston at gmail.com) Date: 1 Nov 2005 11:31:51 -0800 Subject: Automatically creating a HOME environ variable on Windows? In-Reply-To: References: <1130549236.679806.297670@g43g2000cwa.googlegroups.com> <1130590817.728832.291020@g44g2000cwa.googlegroups.com> <20051029164345.54C1.0.NOFFLE@fiedzia.homeip.net> <20051031112631.261A.0.NOFFLE@fiedzia.homeip.net> <1130841590.254214.311370@z14g2000cwz.googlegroups.com> Message-ID: <1130873511.002661.181770@o13g2000cwo.googlegroups.com> os.path.expanduser('~') is a bit cryptic for non-unix people. os.path.gethome() or something like that would be nicer. expanduser() should then call gethome() so the logic is in one place. It looks like the existing logic in expanduser() is out of date anyway. It should be updated to use %USERPROFILE% before %HOMEDRIVE% + %HOMEPATH% . From guettli at thomas-guettler-dot-de.no-spam.invalid Fri Nov 25 13:21:19 2005 From: guettli at thomas-guettler-dot-de.no-spam.invalid (Thomas Guettler) Date: 25 Nov 2005 18:21:19 GMT Subject: How to get started in GUI Programming? References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <4387561f$0$39563$892e7fe2@authen.yellow.readfreenews.net> Am Fri, 25 Nov 2005 06:02:40 -0800 schrieb peter.mosley: > I am trying to learn GUI programming in Python, but have to confess I > am finding it difficult. > Yes, if you come from Visual Basic you might be missing something. I developed with Visual Basic some time ago and like some parts of it. > I've found the tutorial and reference manual on the PyGtk web site, > but although I've made some progress, I keep reaching points where I > have insufficient background to understand them. Currently I'm stuck > on dialog boxes (the code seems immensely complex for the equivalent of > MsgBox("Do you really want to do this ",vbYesNo) > search for yesNoDialog here: http://guettli.sourceforge.net/gthumpy/src/editMetadata.py > and I haven't > got it to work properly yet) and loading graphical images in anything > other than their original size, but every new step brings another > struggle > search for scale2pixbuf in the link. > Can anyone offer any suggestions as to the least painful way forwards? > Only the beginning is painful. After some time you don't miss anything from Visual Basic anymore. Happy Learning, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From sybrenUSE at YOURthirdtower.com.imagination Tue Nov 1 09:14:48 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 1 Nov 2005 15:14:48 +0100 Subject: python.org offline Message-ID: Hi all, In the past weeks, I often got this message from the python.org webserver: ------------------------------------------------------------------ Service Temporarily Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. ------------------------------------------------------------------ Does anyone know what's going on? 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 steve at REMOVETHIScyber.com.au Thu Nov 3 17:22:36 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 09:22:36 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> <7xr79xzk4f.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 03 Nov 2005 10:01:04 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> Then you don't approve of inheritance? That's fine, it is your choice, but >> as far as I know, all OO languages include inheritance. > > Some OO languages only implement inheritance for method calls. Class > variables don't get inherited. Fascinating. Which languages, and what is the reasoning behind that? I bet they are languages that force the class designer to spend half their time writing setters and getters. Am I right? -- Steven. From tinman31337 at gmail.com Wed Nov 23 08:37:50 2005 From: tinman31337 at gmail.com (Tin Gherdanarra) Date: Wed, 23 Nov 2005 05:37:50 -0800 Subject: syntax errors while building pypgsql In-Reply-To: <1132752102.629457.219060@o13g2000cwo.googlegroups.com> References: <3uj7hcF10k63tU1@individual.net> <1132751543.237501.72520@g44g2000cwa.googlegroups.com> <3uj8g3Fv8p4vU1@individual.net> <1132752102.629457.219060@o13g2000cwo.googlegroups.com> Message-ID: <3uj9lfF11ntnaU1@individual.net> bonono at gmail.com wrote: > Tin Gherdanarra wrote: > >>bonono at gmail.com wrote: >> >>>Have you tried apt-get build-dep pypgsql ? >>> >>>It could be that you lacks the necessary packages to build it. >> >>funny you'd mention it, I did. pypgsql does not seem to >>be an apt-get package, however. It did not work because >>"E: Couldn't find package pypgsql" >> >>The fact that there is a >> >> PyObject_HEAD PGconn *conn; >> >>throws an error can't be relieved by another package, >>I guess... >> > > If that is the case, you need to read the pypgsql for what it is > needed. As an alternative, you may try apt-get build-dep celementtree > which may pull in the necessary files. But this is really WAG. > Thanks, but what is WAG? This came right in: Confusingly, it's not apt-get pypgsql, it is python-pgsql. After doing a apt-get python-pgsql. I'm not yet one happy camper, but getting there. Thanks. From falcon3166 at hotmail.com Wed Nov 16 14:38:05 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 16 Nov 2005 12:38:05 -0700 Subject: Can anyone tell me if pygame and Tkinter can work together? References: <437ab8b5$0$20233$88260bb3@news.atlantisnews.com> Message-ID: <437b81d9$0$20257$88260bb3@news.atlantisnews.com> It's a warning that says: Can only use * in top level or something like that. It's kind of annoying, but the program still ran after I made the import * lines top level, and removed the def's. Nathan Pinno. -- For great sites go to: http://www.the-web-surfers-store.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty "Simon Brunning" wrote in message news:mailman.736.1132140506.18701.python-list at python.org... On 16/11/05, Nathan Pinno wrote: > It worked, but unfornately I can't use this line as it brings up errors: > > from Tkinter (or pygame) import * > > Anyway around this little bug? What's the error? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ -- ............................................................. > Posted thru AtlantisNews - Explore EVERY Newsgroup < > http://www.AtlantisNews.com -- Lightning Fast!!! < > Access the Most Content * No Limits * Best Service < From claird at lairds.us Thu Nov 17 07:08:01 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 17 Nov 2005 12:08:01 GMT Subject: running functions References: <11nna381aoiuc57@corp.supernews.com> Message-ID: In article , Gorlon the Impossible wrote: . . . >the fly' so to speak. I checked out the threading module and its >working for what I am trying to do at the moment, but I am open to >suggestions and eager to learn all I can about other options. Thanks . . . If threading is already working for you, stay with it; it certainly has the technical ability to do all you describe for your eventual goal. Apart from that, just keep reading the standard documentation. You might also consider and (except that the latter is now in its second edition--why hasn't the reviewer addressed this yet!?). From mwm at mired.org Tue Nov 29 12:40:03 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 29 Nov 2005 12:40:03 -0500 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> <86fypkim4x.fsf@bhuda.mired.org> <861x10v4ks.fsf@bhuda.mired.org> Message-ID: <86psoj2w0c.fsf@bhuda.mired.org> Antoon Pardon writes: >> You see, you can make languages more powerful by *removing* things >> from it. > You cast this in way to general terms. The logic conclusion > from this statements is that the most powerfull language > is the empty language. The only way you reach that conclusion is if you read the statement as saying that removing things *always* makes a langauge more powerful. That's not what I said, and that's as false as the belief that adding things always makes a language more powerful. >> Wrong. There are some thing which there should *not* be a way to do. >> For instance, there should not be a way to produce a segmentation >> fault - which means certain features common to other languages will >> never be added. > Then C-extentions shouldn't be allowed. C-extensions aren't part of Python. >> We don't talk much about how you produce buffer >> overfows in Python, but people have asked for that as well. Adding >> ways to write hard-to-read code is frowned upon. And so on. > Do you mean people have asked for the possibility that a buffer > overflow would overwrite other variables? Buffer overflows don't have to overwrite variables. They just asked how you create buffer overflows in Python. >> I won't speak for others, but I wouldn't reject it out of hand. You >> haven't provided enough information. Accepting it just because it adds >> a way to do something is wrong. First, you have to ask whether or not >> that something is something we want in Python at all. Then you >> consider whether how the way proposed fits with the language: is it >> ugly? > That is a highly subjective question, answering it says more about > the person then about the proposal. True. But whether or not a language is good is a highly subjective question. Since the goal - keeping python good to the people who already consider it good - is subjective, it's only natural that part of the evaluation process be sujectie. >> Is it prone to abuse? > I don't see why this is always brought up, given the number of > features that can be abused in python. Just because Python isn't perfect is no reason to make it worse. >> Etc. These could cause a specific proposal >> to be rejected, even if the proposed facility acceptable. Then you >> have to consider how it affects the rest of the language. Adding >> another way to do something isn't reason to reject it out of hand, but >> it's a minus. Consider whether the same end can be achieved in another >> way - preferably without changing the language (Python is *very* >> powerful, a you can do quite a bit with it that isn't obvious), > But there should be one obvious way to do things. That there are > lots of unobvious way to do the same thing thus shouldn't count > against a proposal that introduces an obvious way to do it. "Obvious" is also a subjective statement, so adding *any* other way to do things is a minus. >> In summary, the design philosophy is that it's better to do without >> some facility than to add it in a way that doesn't fit with the >> language, and the process reflects that. > I don't mind that a proposal is worked on and that counter-proposals > can be made. But some people just seem to counter any new proposal, > while other are more interrested in searching for ways to make > the new proposal fit the language. Now sometimes a proposal can't > be fitted and gets rejected, so be it. But maybe more could be > fitted in the langauge if more people were willing to look for > ways to fit something, instead of rejecting it simply because > the current proposal doesn't fit properly yet. The only way this would be good is if "more features" were inherently better. That's simply not true. So the change in behavior you're looking for isn't clearly good. Further, if someone doesn't have a need, trying to make someone elses need fit is largely a waste of their time, though some people - language wonks - will do it anyway. On the other hand, pointing out that something is bad is *not* a waste of their time, as it protects something good. So basically, you're asking that people waste their time on something of dubious value. Not a request that's likely to be get very far. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From __peter__ at web.de Tue Nov 15 09:37:59 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 15 Nov 2005 15:37:59 +0100 Subject: simulating #include in python References: Message-ID: Nick Craig-Wood wrote: > I'd?really?like?to?be able to run an __import__ in the context of the file > thats running the include() but I haven't figured that out. execfile()? Peter From thakadu at gmail.com Fri Nov 4 15:03:07 2005 From: thakadu at gmail.com (thakadu) Date: 4 Nov 2005 12:03:07 -0800 Subject: Python and Lotus Notes References: Message-ID: <1131134587.718453.209650@f14g2000cwb.googlegroups.com> I have had success with jython using the notes.jar classes, for example: import lotus.domino import java.io import java.net import java.lang import java.util lotus.notes.NotesThread.sinitThread() S = lotus.notes.Session.newInstance(); db=S.getDatabase("server/domain","domlog.nsf") agent=db.getAgent("DeleteOldDocs") for x in range(50): print x result=agent.runOnServer() print "res %d" % result From apardon at forel.vub.ac.be Mon Nov 7 09:34:35 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 14:34:35 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Op 2005-11-07, Steve Holden schreef : > Antoon Pardon wrote: >> Op 2005-11-05, Steven D'Aprano schreef : >> >>>On Fri, 04 Nov 2005 12:10:11 +0000, Antoon Pardon wrote: >>> >>> >>>>>There are good usage cases for the current inheritance behaviour. I asked >>>>>before what usage case or cases you have for your desired behaviour, and >>>>>you haven't answered. Perhaps you missed the question? Perhaps you haven't >>>>>had a chance to reply yet? Or perhaps you have no usage case for the >>>>>behaviour you want. >>>> >>>>There are good use cases for a lot of things python doesn't provide. >>>>There are good use cases for writable closures, but python doesn't >>>>provide it, shrug, I can live with that. Use cases is a red herring >>>>here. >>> >>>Is that a round-about way of saying that you really have no idea of >>>whether, how or when your proposed behaviour would be useful? >> >> >> I am not proposing specific behaviour. Because if I do, you will >> just try to argue how much worst my proposed behaviour is. >> >> Whether or not I can come up with a better proposal is irrelevant >> to how sane the current behaviour is. >> > If you can't provide a superior alternative then you have little right > to be questioning the present behavior. Nonesense. Unable to produce a superior alternative doesn't make one unable to evaluate. >>>Personally, I think that when you are proposing a major change to a >>>language that would break the way inheritance works, there should be more >>>benefits to the new way than the old way. >> >> >> How many times do I have to repeat myself. I'm not proposing a change >> to the language. >> > So you have a clear impression that Python's current behavior is > unsatisfactory enough to be called "unsane" which, You are generalizing my words to the point they no longer reasonably resemble what I wrote. >> >>>If you're just trolling, you've done a great job of it because you fooled >>>me well and good. But if you are serious in your criticism about the >>>behaviour, then stop mucking about and tell us what the behaviour should >>>be. Otherwise your criticism isn't going to have any practical effect on >>>the language at all. >> >> I wasn't trolling. I just threw in an off hand remark. That you got so >> heated up about that remark is not my responsibility. I'm not trolling >> because I'm willing to defend my remark and I don't intend to get >> people to get heated up about it. I just don't hold back because >> people may get heated up about it. >> > The defense of your original remark implies very strongly that it wasn't > offhand, and that you are indeed trolling. Hence the reduction in the > frequency of my replies. You make it more and more difficult to take you > seriously. Fine that goes both ways. I don't mind not being taken serious by people I have trouble taking serious my self. No doubt that goes for you too. So I propose we don't react to each other any longer, since there would be very little purpose in it. > Particularly since you have now resorted to a defense which > involves refusing to define a non-existent word in any but the vaguest > terms - you are trying to specify a position on the imaginary continuum > of sanity, but you don't say how close to which end you are trying to > specify. This puts you somewhere between "barmy" and "crackpot" on my > own personal scale. >> >>>If you are serious about wanting the behaviour changed, and not just >>>whining, then somebody has to come up with an alternative behaviour that >>>is better. >> >> >> If I would be whining I would want the behaviour changed. I would just >> keep complaining about it until someone else would have changed it. >> > Instead you just keep complaining about it, full stop. No I don't keep complaining about. I just defend my claim. > Since we are all > now fully aware of your opinions, couldn't you just shut up, or do we > have to send you to your room without any supper? Whine, whine, whine. Well since you are aware of my opinion, why don't you just ignore any new articles of mine in this thread and go on, instead of whining about the fact that I care to defend what I wrote but won't put more fuel on the fire by starting my idea about superior behaviour which would only make this thread live longer without any chance of coming to a shared conclusion. > Every time I reply to you my spell checker looks at your name and shows > me a dialog with an "ignore all" button on it. I have this increasing > suspicion that it's trying to tell me something. Well maybe you should listen to it. It seems damn obvious neither of us has anything interresting to say to the other. -- Antoon Pardon From fuzzyman at gmail.com Mon Nov 28 12:10:57 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Nov 2005 09:10:57 -0800 Subject: New Ordered Dictionery to Criticise Message-ID: <1133197857.754686.133740@g44g2000cwa.googlegroups.com> Sorry for this hurried message - I've done a new implementation of out ordered dict. This comes out of the discussion on this newsgroup (see blog entry for link to archive of discussion). See the latest blog entry to get at it : http://www.voidspace.org.uk/python/weblog/index.shtml Criticism solicited (honestly) :-) We (Nicola Larosa and I) haven't yet made any optimisations - but there are two implementations to play with. One allows you to access the keys attribute as if it was a sequence (as well as a method). All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From nk67v8o02 at sneakemail.com Sat Nov 26 16:41:46 2005 From: nk67v8o02 at sneakemail.com (mojosam) Date: 26 Nov 2005 13:41:46 -0800 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: <1133041306.601950.213710@g43g2000cwa.googlegroups.com> Thanks to everyone so far. You've helped a lot. (BTW, I read this through Google Groups. Somehow they've gotten about 24 hours behind, so I'm seeing your replies a day late.) The biggest misconception I had was that the license could force the code to stay open source. You're right. What I do on company time belongs to the company. I guess I assumed there was a license that forced them to release it. At one place I worked, they had to delay the release of the product by a few weeks, because they discovered that they had included an open source (don't know which license) module. They had to pull it out and recode it themselves (I know the other thread covered the subtleties of whether even that was kosher, but let's ignore that here). I think the problem there was they believed that if they included the module, they would have had to release the source code to the entire project. I was kind of hoping for something like that. I would have to talk to a lawyer to be sure, but right now, I think I can argue that anything I do on my own time belongs to me. I'm technically a consultant right now (even though I'm spending 40 hours/week with the one "client"). I can take on other clients, as long as they don't directly compete. This means they're hiring my expertise. If I bring my own tools, that's part of my expertise. I do recall there was a clause in the contract that anything I did on their time belonged to them. For my next client, I should definitely include a clause about rereleasing open source changes. Anyway, staying away from the lawyer issues, if anyone has additional thoughts to add to this, please keep the conversation going. People are raising some good points. Ron Britton nk67v8o02 at sneakemail.com From deets at nospam.web.de Sun Nov 6 12:54:55 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 06 Nov 2005 18:54:55 +0100 Subject: Learning multiple languages (question for general discussion) In-Reply-To: <7xvez5wvgc.fsf@ruckus.brouhaha.com> References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> <1h5hs5y.19u42x51mo5hupN%aleax@mail.comcast.net> <7xvez5wvgc.fsf@ruckus.brouhaha.com> Message-ID: <3t6ubgFr6f2dU1@uni-berlin.de> > Do you have any opinion of "Types and Programming Languages" by > Pierce? Autrijus Tang (the guy who started PUGS, the Perl 6 > implementation in Haskell) raves about it in an interview, and another > guy I know recommended it too, but I haven't actually looked at a copy > yet (stores I've looked in don't have it). Haskell is the language > that I guess interests me the most these days (in terms of learning > new ones), but I haven't yet attempted doing anything with it. It's a great book - I cetainly owe it the better part of my thesis about multi level specification for functional languages. If you want to understand type-systems, its a great comprehensive read. Diez From nope at nottelling.com Sat Nov 26 16:23:13 2005 From: nope at nottelling.com (JustSomeGuy) Date: Sat, 26 Nov 2005 21:23:13 GMT Subject: Call OCX from python? Message-ID: <5n4if.627200$1i.183531@pd7tw2no> Hi I have a commercial OCX that I want to use in my python application. How do I call OCXs from python? TIA From grante at visi.com Wed Nov 9 15:05:36 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 09 Nov 2005 20:05:36 -0000 Subject: Floating numbers and str References: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> Message-ID: <11n4lkg3hlboq08@corp.supernews.com> On 2005-11-09, Tuvas wrote: > I would like to limit a floating variable to 4 signifigant digits, when > running thorugh a str command. Sorry, that's not possible. > x=.13241414515 > y=str(x)+" something here" > > But somehow limiting that to 4 sign. digits. I know that if > you use the print statement, you can do something like %.4d, > but how can I do this with converting the number to a string? I don't understand what you mean about the print statement. If using str() isn't really a requirement, you can use the string formatting operator "%" like this: >>> x=.13241414515 >>> y = "%0.4g" % x >>> y '0.1324' -- Grant Edwards grante Yow! A GRAM?? A BRAM... A at GROOM... A BROOM... Oh, visi.com Yeh!! Wash the ROOM!! From Dennis.Benzinger at gmx.net Tue Nov 22 10:09:54 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 22 Nov 2005 16:09:54 +0100 Subject: the first element in the list of list In-Reply-To: References: Message-ID: <438334bd$1@news.uni-ulm.de> Ben Bush schrieb: > I have a lis: > [[1,3],[3,4],[5,6],[8,9],[14,0],[15,8]] > I want a code to test when the difference between the first element in > the list of list is equal to or larger than 6, then move the previous > lists to the end of the list. that is: > [[14,0],[15,8],[1,3],[3,4],[5,6],[8,9]] your_list = [[1,3],[3,4],[5,6],[8,9],[14,0],[15,8]] for index, sublist in enumerate(your_list): if abs(sublist[1] - sublist[0]) > 6: your_list = your_list[index:] + your_list[:index] break print your_list Bye, Dennis From ashokagk at gmail.com Thu Nov 24 22:52:41 2005 From: ashokagk at gmail.com (ash) Date: 24 Nov 2005 19:52:41 -0800 Subject: python gui using boa In-Reply-To: References: <1132637738.473190.311620@g43g2000cwa.googlegroups.com> <1132771693.777165.63860@g43g2000cwa.googlegroups.com> <1132863202.952590.33290@g14g2000cwa.googlegroups.com> Message-ID: <1132890761.611114.289430@g14g2000cwa.googlegroups.com> Thanks Brian, I could do it. actually it needs all the three mouse events - LeftDown, LeftUp and MouseMove. with regards, Ashoka From martin.witte at gmail.com Fri Nov 18 10:47:48 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 18 Nov 2005 07:47:48 -0800 Subject: Python on linux In-Reply-To: References: Message-ID: <1132328868.228701.235460@g43g2000cwa.googlegroups.com> Partitioning a hard disk on linux can be done with parted, see http://www.gnu.org/software/parted/parted.html - I don't know how good the python-pated interface is, and what it's capable of From correia_jREMOVECAPS at hotmail.com Mon Nov 14 20:16:16 2005 From: correia_jREMOVECAPS at hotmail.com (J Correia) Date: Tue, 15 Nov 2005 01:16:16 GMT Subject: Pregunta sobre python References: Message-ID: Para Windows: import win32api handle = win32api.OpenProcess(1, False, pid_del_proceso) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) "Yves Glodt" wrote in message news:mailman.627.1131980777.18701.python-list at python.org... > Andres de la Cuadra wrote: > > Hola, me llamo Andres de la cuadra, soy un usuario de python en chile y me > > gustar?a saber como puedo cerrer un programa a trav?s de python. Yo se que > > con la librer?a os puedo ejecutar programas, pero no e encontrado una > > librer?a para poder cerrarlos > > Hola Andres, > > puedes cerrer un programa con os.kill, pero depende de tu plataforma, > por ejemplo en linux (no se para windows): > > os.kill(pid_del_proceso, 9) > > > p.s. > Vas a tener mas excito si escribes en ingles, esta es une lista en > ingles ;-) > > > > Gracias > > > > From nyamatongwe+thunder at gmail.com Fri Nov 18 16:24:21 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 18 Nov 2005 21:24:21 GMT Subject: check if com api is still available In-Reply-To: <3u67k3Fvep32U1@news.dfncis.de> References: <3u67k3Fvep32U1@news.dfncis.de> Message-ID: <9Erff.20624$Hj2.1070@news-server.bigpond.net.au> Hermann Maier: > i am using the com api of a program and if this program is shut down and > my program calls a method of the api, it crashs. that means, i need to > check, if the com server is still available, before i can call for it. The server should not shut down while clients have outstanding references to objects within it. > but i would prefer a > solution that is more clean from the beginning. perhaps there is a > windows event that can tell me, wenn the other application, that hosts > the com server, is closed or perhaps i can do something with the guid of > the com server, maybe there is a call where i can check, if a certain > com server is available. All running COM servers should be in the "Running Object Table" (ROT). If you search the net for this term you will find code that can show what is in the ROT, so there must be an API. Neil From fdu.xiaojf at gmail.com Sun Nov 27 08:48:07 2005 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Sun, 27 Nov 2005 21:48:07 +0800 Subject: Has this problem been fiexed ? Message-ID: <4389B917.3050906@gmail.com> Hello, I'm trying to build python2.4.2 on IRIX6.5(cc version MIPSpro Compilers: Version 7.3.1.3m). But the socket module failed to compile. I found this in ./Modules/socketmodule.c, line 193: -------------------------------------------------------- /* XXX Using _SGIAPI is the wrong thing, 194 but I don't know what the right thing is. */ 195 #undef _SGIAPI /* to avoid warning */ 196 #define _SGIAPI 1 -------------------------------------------------------- I think maybe somebody have already fixed this problem. Or any hints on how to compile socket module on IRIX? Thanks very much. Regards, xiaojf From pwatson at redlinepy.com Sun Nov 20 22:03:43 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 20 Nov 2005 21:03:43 -0600 Subject: Web-based client code execution In-Reply-To: <438066d7$1_3@newspeer2.tds.net> References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> <438066d7$1_3@newspeer2.tds.net> Message-ID: <4381390F.1090004@redlinepy.com> Kent Johnson wrote: > Stephen Kellett wrote: > >> In message <1132342910.799932.58720 at g44g2000cwa.googlegroups.com>, >> Steve writes >> >>> AJAX works because browsers can execute javascript. I don't know of a >>> browser that can execute python. Basically your stuck with java or >>> javascript because everything else really isn't cross platform. >> >> >> >> ActiveState do a version of Python that can run in a script tag like >> JavaScript and VBScript. This requires Windows Scripting Host. They >> also do a similar thing for Perl, not sure about TCL. > > > See > http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830 > > Kent Please correct my misunderstanding if I am wrong, but I thought that this runs server-side only and requires Microsoft IIS as the httpd server. Is that correct? From jjl at pobox.com Sun Nov 20 16:54:37 2005 From: jjl at pobox.com (John J. Lee) Date: 20 Nov 2005 21:54:37 +0000 Subject: Web-based client code execution References: <3u6ngeFvh3v1U1@individual.net> Message-ID: <87zmnzyogy.fsf@pobox.com> Paul Watson writes: > What are the options? > > The user to hits a web page, downloads code (Python I hope), execute it, > and be able to return the results. It needs to be able to go through > standard HTTP so that it could be run from behind a corporate firewall > without any other ports being opened. > > Am I stuck doing an ActiveX control? [...] If you just need to talk on port 80, just go ahead and do that (module socket, module httplib, module urllib2, urllib.getproxies, etc), and write a normal desktop application. If it must run in a browser, here is some food for thought: Compile Python to JavaScript -- very cool http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework http://www.aminus.org/blogs/index.php/phunt/2005/10/09/psst_crackajax_is_in_svn Plain old AJAX with Python on server side https://sourceforge.net/projects/json-py/ http://www.google.co.uk/search?q=ajax+python&btnG=Search (um, ignore the 1st result) Write Java applets in Python http://www.jython.org/ Flash 'local storage' http://www.macromedia.com/support/documentation/en/flashplayer/help/help02.html Sort-of AJAX-for-Flash stuff http://www.cs.unc.edu/~parente/tech/tr04.shtml http://www.simonf.com/flap/ Flash itself (boo;-) http://www.macromedia.com/ XUL and PyXPCOM (Firefox only) http://www.xulplanet.com/ http://trac.nunatak.com.au/projects/nufox Firefox future capabilities in this direction (probably most of this is relevant) http://www.mozilla.org/roadmap/gecko-1.9-roadmap.html http://weblogs.mozillazine.org/roadmap/archives/2005_09.html John From apardon at forel.vub.ac.be Mon Nov 14 06:20:53 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Nov 2005 11:20:53 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <7x64qv1tr3.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-11-14, Paul Rubin schreef : > Antoon Pardon writes: >> We could then have something like the following. >> >> a = 5 >> b = a >> a @= 7 >> b ==> would result in 7. > > Ouch! :-((( > > Can't you live with > > a = [5] > b = a > a[0] = 7 > > so b[0] is now 7. And what do I have to do, in case of the following: a = [3, 5] b = a[0] b @= 7 a ==> would result in [7, 5] This may seem contrived, but in combination with parameters it could be usefull. Something like: a = [3, 5] def treat(b): lots of code b @= new_value f(a[0]) a ==> would result in [7, 5] -- Antoon Pardon From ejensen at visi.com Thu Nov 24 21:34:32 2005 From: ejensen at visi.com (Ed Jensen) Date: Fri, 25 Nov 2005 02:34:32 -0000 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <1132841680.454026.203420@z14g2000cwz.googlegroups.com> Message-ID: <11ocu1og1660965@corp.supernews.com> Paul Boddie wrote: >> I'm aware of this concern. I don't think it's justified. Unless >> you'd like to point out all those closed, proprietary Python >> implementations that are destroying civilization as we know it. > Well, there was some concern voiced at EuroPython that a certain large > software-patent-lobbying organisation wouldn't release the shiny port > of Python that they'd done for their mobile telephone products. Now, > one can either emulate that well-practised foot-stamping routine of > yours... Has this seriously harmed the Python community? Or CPython? Has it caused evolution of Python/CPython to stall? Did it have the unfortunate consequence of causing any CPython code to become closed source or proprietary? Show me the harm done. > In another recent licensing spat, some people are apparently unhappy > with one Python-related project's use of the GPL, since the code they > originally contributed to an older, related project ends up being > redistributed under the GPL in the former project whereas the latter > project cannot redistribute the former project's original code without > putting a GPL licence on the distributed work. Now, if the latter > project, with its advantage of having come into existence first had > chosen a GPL-incompatible licence, it's quite possible that they would > have avoided the situation that some seem to bemoan, but then one has > to consider the likelihood that people actually do want GPL > compatibility in their favourite open source projects. I agree that mixing and matching licenses can be a problem, which is yet another reason I lament the proliferation of source code licenses. It's like a whole generation of software developers have become armchair lawyers, which I find unfortunate. Think how much farther along free software could be if all this energy and concern weren't expended on source code licenses. > My point about the freeloading was that business understandably likes > to do it. I don't feel any sympathy for participants in various Apache > projects that are hugely popular in business, for example, if those > participants dislike the lack of contributions from those companies > using their software to make money, because those who founded those > projects made a conscious licensing decision and that decision defines > the kind of sharing (or otherwise) around such projects. I don't feel sorry for them either, and I don't think they feel sorry for themselves. And the success of projects like Apache are even more proof, in my opinion, that heavy handed licenses like the GPL aren't necessary for the success of free software projects. > So if you're not personally affected, as you claim, why does it bother > you? Because I think a lot of well meaning software developers writing free software don't performance due diligence to determine the true motivation behind, and the chilling effect of, the GPL. From bokr at oz.net Tue Nov 22 20:53:46 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 23 Nov 2005 01:53:46 GMT Subject: Why are there no ordered dictionaries? References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: <4383b600.500692667@news.oz.net> On Tue, 22 Nov 2005 20:37:40 +0100, Christoph Zwerschke wrote: >One implementation detail that I think needs further consideration is in >which way to expose the keys and to mix in list methods for ordered >dictionaries. > >In http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 >the keys are exposed via the keys() method which is bad. It should be a >copy only, like for ordinary dicts (one comment also mentions that). > >In Foord/Larosa's odict, the keys are exposed as a public member which >also seems to be a bad idea ("If you alter the sequence list so that it >no longer reflects the contents of the dictionary, you have broken your >OrderedDict"). > >I think it would be probably the best to hide the keys list from the >public, but to provide list methods for reordering them (sorting, >slicing etc.). > >For instance: > >d1 = OrderedDict( (1, 11), (2, 12), 3, 13) ) > >d1[1:] ==> OrderedDict( (2, 12), 3, 13) ) > >d1[0] + d1[2] ==> OrderedDict( (1, 11), (3, 13) ) > >d1.reverse() ==> OrderedDict( (3, 13), (2, 12), 1, 11) ) > >d1.insert(1, (4, 14)) > ==> OrderedDict( (1, 11), (4, 14), (2, 12), 3, 13) ) > >etc. > >But no other way to directly manipulate the keys should be provided. > >>> from odictb import OrderedDict >>> d1 = OrderedDict([(1, 11), (2, 12), (3, 13)]) >>> d1 {1: 11, 2: 12, 3: 13} >>> d1[1:] {2: 12, 3: 13} >>> d1[0:1] + d1[2:3] {1: 11, 3: 13} >>> d1.reverse() >>> d1 {3: 13, 2: 12, 1: 11} >>> d1.insert(1, (4,14)) >>> d1 {3: 13, 4: 14, 2: 12, 1: 11} >>> d1.items() [(3, 13), (4, 14), (2, 12), (1, 11)] >>> d1.keys() [3, 4, 2, 1] >>> d1.values() [13, 14, 12, 11] >>> d1[1:2] {4: 14} >>> d1[-1:] {1: 11} Que mas? Regards, Bengt Richter From aleax at mail.comcast.net Mon Nov 28 22:21:07 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 28 Nov 2005 19:21:07 -0800 Subject: return in loop for ? References: <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> <86lkz8vh34.fsf@bhuda.mired.org> <7x7jasgy0a.fsf@ruckus.brouhaha.com> Message-ID: <1h6r426.a0kur82slpvmN%aleax@mail.comcast.net> Paul Rubin wrote: > Steven D'Aprano writes: > > I don't know what the state of the art is, but I suspect it > > will be a long, long time before it is as easy as running "import > > mymodule; verify(mymodule)". > > Some pretty significant pieces of software have been formally verified > to meet their formal specifications. The trouble with > "verify(mymodule)" is that usually means something closer to "verify > that mymodule does what I hope it does". The computer does not yet > have a telepathy peripheral that can read your mind and figure out > what you are hoping, and people's attempts to express formally what > they are hoping are easily wrong just like programs are often wrong. Yep. I'm reminded of an ambulance dispatch system (read about it a long time ago on the Risks mailing list, so I might be off on the detail, but the gist should be correct) which was formally proven to obey a long list of rules, one of which was "for this kind of emergency, an ambulance must arrive within 10 minutes" (or the like). Problem, of course, being that in formal logic this implies "if this kind of emergency exists and no ambulance has arrived within 10 minutes, you have an impossibility and from an impossibility ANY theorem can be proven". So, if real-world road conditions meant the ambulance was about to arrive in 10 minutes and 5 seconds, it might instead be rerouted elsewhere... not having arrived in 10 minutes, a contradiction was in the system and it could prove anything (I think that's know as the theorem of Pseudo-Scotus). It's hard in (classic) logic to express "this MUST be true; if it's false, ..." -- to human beings the first "MUST" can be interpreted as "99.9% probability" or the like, so the "if it's false" clause is meaningful ("in the extremely unlikely, but not impossible since nothing's truly impossible in the real world, situation that it's false, ..."), but to Aristotle's logic, if something MUST be true, it's obviously irrelevant whatever might follow if that something were instead to be false. Alex From paddy3118 at netscape.net Wed Nov 9 13:21:23 2005 From: paddy3118 at netscape.net (Paddy) Date: 9 Nov 2005 10:21:23 -0800 Subject: Pythonising the vim (e.g. syntax popups) In-Reply-To: References: Message-ID: <1131560483.691495.125590@g47g2000cwa.googlegroups.com> Hi, I am using gvim 6.4 which has Python colorising, and The menu tools->folding->fold method->indent :help folding May give you more info. Cheers, Paddy. From my_initials at nglogic.com Thu Nov 3 06:46:32 2005 From: my_initials at nglogic.com (Stanislaw Findeisen) Date: Thu, 03 Nov 2005 12:46:32 +0100 Subject: NTFS reparse points Message-ID: I want to create a reparse point on NTFS (any). Here (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/reparse_points.asp) I read: "reparse points are used to implement NTFS file system links". Here (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/hard_links_and_junctions.asp) I read: "Soft links are implemented through reparse points". However I can't see FILE_ATTRIBUTE_REPARSE_POINT turned on in any file / directory shortcuts I create. In fact the only attribute set in shortcuts created using Windows Explorer is FILE_ATTRIBUTE_ARCHIVE. (I am using GetFileAttributes() to examine this.) The questions are: (1) Why is that so? (2) Does anybody have any idea (sample code?) on how to create a reparse point (the simpler, the better) using Python? I am using Windows 2000 Professional, Python 2.4 and Mark Hammond's Python for Windows Extensions build 204. Thank you. +-------------------------------------------------------+ | When replying, please replace "my_initials" in the | | From: address field with my initials - that is, "SF". | +-------------------------------------------------------+ -- http://www.nglogic.com Enter through the narrow gate! (Mt 7:13-14) From bonono at gmail.com Thu Nov 24 01:44:11 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 22:44:11 -0800 Subject: Python as Guido Intended In-Reply-To: References: <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1132800973.008501.34090@g14g2000cwa.googlegroups.com> <867jay1ybk.fsf@bhuda.mired.org> <1132805759.799632.265850@f14g2000cwb.googlegroups.com> <86u0e2zmwb.fsf@bhuda.mired.org> <1132807138.648558.234880@g47g2000cwa.googlegroups.com> Message-ID: <1132814651.199782.285860@z14g2000cwz.googlegroups.com> Steve Holden wrote: > bonono at gmail.com wrote: > > Mike Meyer wrote: > > > >>"bonono at gmail.com" writes: > >> > >>>>Maybe Python attracts people who share that belief. After all, TRTFTJ > >>>>is implies TSBOOWTDI, and vice versa. > >>> > >>>I was not talking about the believe, I was talking about the way you > >>>presented it. You are setting up an "imaginary" me, which is not me. > >>>And that is the kind of arguments I saw, I believe this many times are > >>>done unconciously. > >> > >>You're doing that yourself. But we don't have a real other person to > >>work with - the best we can do is work with our model of that other > >>person. That's life. > >> > > > > In what way am I doing it myself ? It could be unconciously too but I > > always welcome if it could be pointed out. > > > I think Mike (the Mike I imagine, anyway) merely intended to point out > that since we can't live in each others' heads all communication is with > an imaginary person, whose actual thoughts and feelings are unavailable > to us. > If that is the case, it is quite different from saying "you are the one who wants to use a hammer on a screw", but without further clarification, I would leave it. From mwm at mired.org Sat Nov 19 23:24:46 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 19 Nov 2005 23:24:46 -0500 Subject: newbie-question about a list References: <1132412790.252141.76630@g47g2000cwa.googlegroups.com> Message-ID: <86d5kwhrox.fsf@bhuda.mired.org> bobueland at yahoo.com writes: > I've seen this construct in a script >>>> [x.capitalize() for x in ['a','b', 'c']] > ['A', 'B', 'C'] > I tried to find a description of this in "Library Reference" but > couldn't find it. Could somebody direct me where this type of construct > is described. As others have pointed out, it's called a "list comprehension". But it's syntax, so the proper place to look for it is the "Language Reference", not the "Library Reference". Except in this case, the language reference is fairly opaque, so you're better off using the google references others have already provided. You might also look for the related construct, "generator expressions". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bonono at gmail.com Wed Nov 23 01:28:19 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 22:28:19 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: <1132727299.252266.315990@o13g2000cwo.googlegroups.com> Steven Bethard wrote: > rhettinger at gmail.com wrote: > >> > ii. The other problem is easier to explain by example. > >> > Let it=iter([1,2,3,4]). > >> > What is the result of zip(*[it]*2)? > >> > The current answer is: [(1,2),(3,4)], > >> > but it is impossible to determine this from the docs, > >> > which would allow [(1,3),(2,4)] instead (or indeed > >> > other possibilities). > >> > """ > >> > IMO left->right is useful enough to warrant making it defined > >> > behaviour > >> > >>And in fact, it is defined behavior for itertools.izip() [1]. > >> > >>I don't see why it's such a big deal to make it defined behavior for > >>zip() too. > > > > > > IIRC, this was discussednd rejected in an SF bug report. It should not > > be a defined behavior for severals reasons: > [snip arguments about how confusing zip(it, it) is] > > Overall, I think anyone using zip(it,it) is living in a state of sin, > > drawn to the tempations of one-liners and premature optimization. They > > are forsaking obvious code in favor of screwy special cases. The > > behavior has been left undefined for a reason. > > Then why document itertools.izip() as it is? The documentation there is > explicit enough to know that izip(it, it) will work as intended. Should > we make the documentation there less explicit to discourage people from > using the izip(it, it) idiom? > That to me is also a slip but does demonstrate that it is easy for people to be drawn into this "sin", including those people responsible for the formal documentation, or those behind the implementation. But technically speaking, you are still referring to the implementation detail of izip(), not the functionality of izip(). I do now agree with another poster that the documentation of both zip and izip should state clear that the order of picking from which iterable is undefined or can be changed from implementation to implementation, to avoid this kind of temptation. From ashokagk at gmail.com Thu Nov 24 15:13:22 2005 From: ashokagk at gmail.com (ash) Date: 24 Nov 2005 12:13:22 -0800 Subject: python gui using boa In-Reply-To: References: <1132637738.473190.311620@g43g2000cwa.googlegroups.com> <1132771693.777165.63860@g43g2000cwa.googlegroups.com> Message-ID: <1132863202.952590.33290@g14g2000cwa.googlegroups.com> Thanks Brian, that was a good introduction. I have another query for you - how can i make a captionless frame draggable in wxWindows? From csubich.spam.block at spam.subich.block.com Fri Nov 4 12:12:00 2005 From: csubich.spam.block at spam.subich.block.com (Christopher Subich) Date: Fri, 04 Nov 2005 12:12:00 -0500 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > Except when your default is a list > > class foo: > x = [] # default > > a = foo() > a.x += [3] > > b = foo() > b.x > > This results in [3]. So in this case using a class variable x to > provide a default empty list doesn't work out in combination > with augmented operators. This has nothing to do with namespacing at all, it's the Python idiosyncracy about operations on mutable types. In this case, += mutates an object, while + returns a new one -- as by definition, for mutables. From aahz at pythoncraft.com Tue Nov 29 16:59:37 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Nov 2005 13:59:37 -0800 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: In article , Robert Kern wrote: >Aahz wrote: >> In article , >> Robert Kern wrote: >>> >>>Don't listen to schmucks on USENET when making legal decisions. Hire >>>yourself a competent schmuck. >> >> Mind if I .sig this? How would you like to be attributed? > >Please do. "USENET schmuck" is a sufficient attribution if you like, >though "Robert Kern" will work, too. Great! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Don't listen to schmucks on USENET when making legal decisions. Hire yourself a competent schmuck." --USENET schmuck (aka Robert Kern) From venkatasubramanian at gmail.com Fri Nov 4 00:52:47 2005 From: venkatasubramanian at gmail.com (venk) Date: 3 Nov 2005 21:52:47 -0800 Subject: Anomaly in creating class methods In-Reply-To: <1h5gzv0.6g2u1u1u3t3kvN%aleax@mail.comcast.net> References: <1131016762.522810.91780@f14g2000cwb.googlegroups.com> <1h5gzv0.6g2u1u1u3t3kvN%aleax@mail.comcast.net> Message-ID: <1131083567.514797.218880@g43g2000cwa.googlegroups.com> Cool, i got it now... accessing thru attribute reference always returns a bound or unbound method... so, D.f is an unbound method whereas i want the "function" of the unbound method... ok,.... this example and the nice explanations definitively thought me about function, bound method (for which the function is just an attribute accessed by im_func) and unbound method... Also, calling classmethod on an unbound method instead of a function is a strict no... no... ok... nice concept... But, i am at loss when i come to clearly understanding the difference between new-style classes and classic classes.... (or should i post it as new topic?)..... From __peter__ at web.de Sat Nov 26 10:15:17 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Nov 2005 16:15:17 +0100 Subject: Whitespace test after string.split References: Message-ID: David Pratt wrote: > Hi. I am splitting a string on a non whitespace character. One or more > whitespace characters can be returned as items in the list. I do not > want the items in the list that are only whitespace (can be one or more > characters of whitespace) and plan to use string.strip on those items > that are not only whitespace (to remove any whitespace from front or > back of items). > > What kind of efficient test can I use to obtain only list items > returned from the split that I am interested in, ignoring any list > items that would only be comprised of one or more characters of > whitespace (since whitespace can mean one or more spaces, tabs, and > other characters) >>> s = "alpha, \t\n, gamma, delta," >>> s.split(",") ['alpha', ' \t\n', ' gamma', ' delta', ''] >>> [t for t in s.split(",") if not t.isspace()] ['alpha', ' gamma', ' delta', ''] >>> [t for t in s.split(",") if t and not t.isspace()] ['alpha', ' gamma', ' delta'] >>> [t.strip() for t in s.split(",") if t and not t.isspace()] ['alpha', 'gamma', 'delta'] There you are. > As a second question, I am seeing string split as deprecated in 2.4.2 > manual. What is planned in future to split (strings or unicode)? Just use the corresponding methods, e. g. s.strip() instead of string.strip(s) etc. Peter From csubich.spam.block at spam.subich.block.com Fri Nov 4 10:28:52 2005 From: csubich.spam.block at spam.subich.block.com (Christopher Subich) Date: Fri, 04 Nov 2005 10:28:52 -0500 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: Antoon Pardon wrote: >>Since ints are immutable objects, you shouldn't expect the value of b.a >>to be modified in place, and so there is an assignment to b.a, not A.a. > > > You are now talking implementation details. I don't care about whatever > explanation you give in terms of implementation details. I don't think > it is sane that in a language multiple occurence of something like b.a > in the same line can refer to different objects > This isn't an implementation detail; to leading order, anything that impacts the values of objects attached to names is a specification issue. An implementation detail is something like when garbage collection actually happens; what happens to: b.a += 2 is very much within the language specification. Indeed, the language specification dictates that an instance variable b.a is created if one didn't exist before; this is true no matter if type(b.a) == int, or if b.a is some esoteric mutable object that just happens to define __iadd__(self,type(other) == int). From steve at REMOVETHIScyber.com.au Sat Nov 19 21:00:56 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 20 Nov 2005 13:00:56 +1100 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: On Sun, 20 Nov 2005 01:39:04 +0000, Steve Holden wrote: > Steven D'Aprano wrote: > [...] >> Likewise, base conversion into arbitrary bases is not, in my opinion, >> common enough a task that support for it needs to be built into the syntax >> for literals. If somebody cares enough about it, write a module to handle >> it and try to get it included with the Python standard modules. >> > In fact Icon managed to offer a syntax that allowed every base up to 36 > to be used: an "r" was used to indicate the radix of the literal, so hex > 453FF would be represented as "16r453FF". This worked fine. Upper- and > lower-case letters werw regarded as equivalent. Forth goes significantly further than that: you can tell the Forth interpreter what base you are using, and all numbers are then read and displayed using that base. Numbers were case sensitive, which meant Forth understood bases to at least 62. I don't remember whether it allows non-alphanumeric digits, and therefore higher bases -- I think it does, but am not sure. Nevertheless, I don't believe that sort of functionality belongs in the language itself. It is all well and good to be able to write 32r37gm, but how often do you really need to write numbers in base 32? -- Steven. From aleax at mail.comcast.net Tue Nov 1 00:16:41 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 31 Oct 2005 21:16:41 -0800 Subject: Storing empties References: <1130539752.667045.183460@g14g2000cwa.googlegroups.com> <1130638902.048806.183580@g43g2000cwa.googlegroups.com> <1130647542.669549.300360@g43g2000cwa.googlegroups.com> <1h57spy.bpig8y1g0rvzfN%aleaxit@yahoo.com> <1130650215.537552.231990@g49g2000cwa.googlegroups.com> <1h58k4p.12xd7rj1t5peh0N%aleaxit@yahoo.com> Message-ID: <1h5bepj.q0sqsnbqqgjrN%aleax@mail.comcast.net> Aahz wrote: > In article <1h58k4p.12xd7rj1t5peh0N%aleaxit at yahoo.com>, > Alex Martelli wrote: > > > >the canonical idiom when you need such distinction is: > > > >_not_there = object() > >def foo(bar=_not_there, baz=_not_there, bap=_not_there): > > if bar is _not_there: ... > > > >Other unique objects can be substituted for the 'sentinel', but I prefer > >an empty "object()" because it has no other possible meaning except that > >of a distinguishable, identifiable sentinel. IOW, you could set the > >_not_there name to [] or {} or many other things, but that could be > >slightly confusing for the reader (since the other things might have > >other meanings and purposes) while 'object()' shouldn't be. > > What's your preferred idiom when you're dealing with storable objects? What's a "storable object"? You mean, something that can be pickled, or passed to the .write method of a file object, or stored in a database, or what else? Alex From samrobertsmith at gmail.com Sun Nov 20 07:45:52 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 04:45:52 -0800 Subject: about polygon In-Reply-To: References: Message-ID: <1d987df30511200445n5d048b7eqbf087bda09a6d7a1@mail.gmail.com> On 11/20/05, Jan Voges wrote: > Hi! > > Am Sun, 20 Nov 2005 03:55:21 -0800 schrieb Shi Mu: > > > Why I got a black polygon in the following code? > > How can I make it no-color filled? > > Use create_line instead: > c.create_line(60,60,100,60,100,100,60,120,60,60) > > Jan If so, what is the difference between create_line and create_polygon? Thanks! From masudtarek at gmail.com Mon Nov 14 17:29:11 2005 From: masudtarek at gmail.com (masudtarek at gmail.com) Date: 14 Nov 2005 14:29:11 -0800 Subject: Searching date and and time from a text file In-Reply-To: References: <1132005880.158423.45690@g43g2000cwa.googlegroups.com> Message-ID: <1132007351.948170.35040@g44g2000cwa.googlegroups.com> Thanks. It was like 911 From timr at probo.com Sun Nov 13 03:29:49 2005 From: timr at probo.com (Tim Roberts) Date: Sun, 13 Nov 2005 08:29:49 GMT Subject: something wrong in wx References: Message-ID: Robert wrote: > >something wrong in wx I doubt it. >I wrote program training na Artificial Neural Network. It work well in >console mode, but when I try to add GUI there is an error: >FANN Error 10: Error reading info from train data file "zapis.txt", line: 2 How are you launching the GUI version? Are you double-clicking on an icon somewhere? Are you sure the application is starting in the correct directory -- the one that contains zapis.txt? Perhaps you should try hard-code the full path, or at least doing an os.chdir(). -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bonono at gmail.com Wed Nov 23 12:06:11 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 09:06:11 -0800 Subject: defining the behavior of zip(it, it) (WAS: Converting a flatlist...) In-Reply-To: References: Message-ID: <1132765571.644644.44060@g47g2000cwa.googlegroups.com> yet another :-) Fredrik Lundh wrote: > Steven Bethard wrote: > > > Then why document itertools.izip() as it is? The documentation there is > > explicit enough to know that izip(it, it) will work as intended. Should > > we make the documentation there less explicit to discourage people from > > using the izip(it, it) idiom? > > depends on whether you interpret "equivalent" as "having similar effects" > or "corresponding or virtually identical especially in effect or function" or > if you prefer some other dictionary definition... > > because there are of course plenty of subtle differences between a Python > generator C type implementation. let's see... > > >>> from itertools import izip as izip1 > >>> from library documentation import izip as izip2 > > >>> izip1 > > >>> izip2 > > > alright, close enough. > > >>> izip1.func_name > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: type object 'itertools.izip' has no attribute 'func_name' > >>> izip2.func_name > 'izip' > > hmm. > > >>> class myiter: > ... def next(self): > ... raise ValueError("oops!") > ... > >>> izip2(myiter()) > > >>> izip1(myiter()) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: izip argument #1 must support iteration > > oops. > > >>> class myiter: > ... def __iter__(self): > ... return self > ... def next(self): > ... raise ValueError("oops!") > ... > >>> izip1(myiter()) > > >>> izip2(myiter()) > > > that's better. now let's run it: > > >>> list(izip1(myiter())) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 5, in next > ValueError: oops! > >>> list(izip2(myiter())) > Traceback (most recent call last): > File "", line 1, in ? > File "i.py", line 6, in izip2 > result = [i.next() for i in iterables] > File "", line 5, in next > ValueError: oops! > > different stack depths. hmm. > > so how equivalent must something be to be equivalent? > > From steve at REMOVETHIScyber.com.au Sun Nov 20 00:10:58 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 20 Nov 2005 16:10:58 +1100 Subject: what happens when the file begin read is too big for all lines to be read with "readlines()" References: <1132399371.267088.291000@g14g2000cwa.googlegroups.com> Message-ID: On Sun, 20 Nov 2005 12:28:07 +0800, Xiao Jianfeng wrote: > Let me introduce my problem I came across last night first. > > I need to read a file(which may be small or very big) and to check line > by line > to find a specific token, then the data on the next line will be what I > want. > > If I use readlines(), it will be a problem when the file is too big. > > If I use "for line in OPENED_FILE:" to read one line each time, how can > I get > the next line when I find the specific token? Here is one solution using a flag: done = False for line in file("myfile", "r"): if done: break done = line == "token\n" # note the newline # we expect Python to close the file when we exit the loop if done: DoSomethingWith(line) # the line *after* the one with the token else: print "Token not found!" Here is another solution, without using a flag: def get_line(filename, token): """Returns the next line following a token, or None if not found. Leading and trailing whitespace is ignored when looking for the token. """ fp = file(filename, "r") for line in fp: if line.strip() == token: break else: # runs only if we didn't break print "Token not found" result = None result = fp.readline() # read the next line only fp.close() return result Here is a third solution that raises an exception instead of printing an error message: def get_line(filename, token): for line in file(filename, "r"): if line.strip() == token: break else: raise ValueError("Token not found") return fp.readline() # we rely on Python to close the file when we are done > And I think reading one line each time is less efficient, am I right? Less efficient than what? Spending hours or days writing more complex code that only saves you a few seconds, or even runs slower? I believe Python will take advantage of your file system's buffering capabilities. Try it and see, you'll be surprised how fast it runs. If you try it and it is too slow, then come back and we'll see what can be done to speed it up. But don't try to speed it up before you know if it is fast enough. -- Steven. From graham.fawcett at gmail.com Fri Nov 4 11:58:10 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 4 Nov 2005 08:58:10 -0800 Subject: Python and Lotus Notes In-Reply-To: References: <1130941469.353649.195200@g14g2000cwa.googlegroups.com> Message-ID: <1131123489.997463.177100@o13g2000cwo.googlegroups.com> Marco Aschwanden wrote: > The second line of your code is already a show stopper in my case: > > from win32com.client import Dispatch > session = Dispatch('Lotus.NotesSession') > session.Initialize('my_secret_passwort') > > When started, ends: > [snip] > AttributeError: Lotus.NotesSession.Initialize > > It worked before though with Version 5.x of Notes. In Notes Version 6.X > they introduced the session.Initialize() - that was the point, when I > couldn't create an instance anymore. I found no hint on the net... Do you > have any idea what is going wrong here? I'm using 6.x here, so that's not the problem. Is there any chance you have an old gen_py file in your path? E.g., does re-running the PythonWin "makepy" utility again make a difference? Just a thought, but something might be "hard-coded" to your earlier 5.x COM interface, and gen_py would be a likely suspect. Also, If you have another language that you can use to do COM, e.g. Visual Basic (in any of the MS Office apps, or in Visual Studio), verify that you can create a Lotus.NotesSession using those environments as well. It might be a lower-level (non-Python-related) problem. Graham From mwm at mired.org Tue Nov 1 15:35:14 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 01 Nov 2005 15:35:14 -0500 Subject: extracting numbers from a file, excluding words References: <1130865585.189485.249820@f14g2000cwb.googlegroups.com> Message-ID: <867jbs14zh.fsf@bhuda.mired.org> Kristina Kudria?ova writes: > 1 Nov 2005 09:19:45 -0800, dawenliu at gmail.com : >> Hi, I have a file with this content: >> >> zzzz zzzzz zzz zzzzz >> ... >> xxxxxxx xxxxxxxxxx xxxxx 34.215 >> zzzzzzz zz zzzz >> ... >> > > Hi, > > I'd suggest doing this: > > f = file('...') > for line in f: > if 'xxxxxxx xxxxxxxxxx xxxxx' in line: > var = float(line[len('xxxxxxx xxxxxxxxxx xxxxx'):].strip()) > f.close() Alternatively: start = len('xxxxxxx xxxxxxxxxx xxxxx') for line in f: if line.startswith('xxxxxxx xxxxxxxxxx xxxxx'): var = float(line[start:].strip()) http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From samantha7395 at hotmail.com Wed Nov 9 14:53:38 2005 From: samantha7395 at hotmail.com (Samantha) Date: Wed, 9 Nov 2005 11:53:38 -0800 Subject: Cursor Position. References: <3tds08Fsb3p1U1@uni-berlin.de> Message-ID: Diez, > Won't be easy - a toolkit (like tkinter) will only capture your mouse > events that are directed towards it's own windows. That is my exact problem. I want to have the mouse event captured from another application window. In this case an image window opened in Paint Shop Pro that by the way uses Python to make scripts. I would like to be able to click on the image and get the X,Y positions. I have been able to get the X,Y from Tkinter own window as you say. Once I have those positions I can use them in a Paint Shop Pro script. Thanks for your reply. Do you have any advise as to how I can do what I am trying or is it, in a practical matter, impossible. S "Diez B. Roggisch" wrote in message news:3tds08Fsb3p1U1 at uni-berlin.de... > Samantha wrote: >> I will be using Tkinter. All I need is a way to get the X,Y position from >> a mouse click. I am trying to have an image loaded to click on, but that >> seems to be a problem. So if I can just get the position from the screen >> of a graphics program, showing an image, it will work for me. > > Won't be easy - a toolkit (like tkinter) will only cpature your mous > events that are directed towards it's own windows. You might be able to > convince your program to collect mouse-events outside for a short period > of time - like snapshot programs do - but that will reqiure pretty > complicated, OS-dependant coding. Certainly way more complicated than > loading an image using tkinter. Better tell us what's giving you a hard > time there. > > Diez From mwm at mired.org Thu Nov 24 11:44:16 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 11:44:16 -0500 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> Message-ID: <86lkzexafz.fsf@bhuda.mired.org> Ben Finney writes: > I'm looking for a "consenting adults" restriction: classes will have > immutable instances only where it makes sense from the class protocol. > I'm not going to lose sleep over users who go looking for trouble. I think you're defining immutable differently than I do. Python already supports attributes that clients can't rebind. You can make an instance in which all attributes have that property. However attributes added by a client aren't really yours. They don't change the immutability of your attributes, or affect the behavior of your class in any way. Such attributes don't really belong to your class; they belong to the client. Even in full B&D languages, it's trivial to overcome this restriction with a subclass: >>> i = int() >>> i 0 >>> i.foo = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'int' object has no attribute 'foo' >>> class Aint(int): pass ... >>> m = Aint() >>> m 0 >>> m.foo = 1 >>> m.foo 1 >>> The extra class is the kind of boilerplate that Python in general has so little of, and B&D languages so much of. In Python, I can even fix it so *your* code uses my wrapped version: import Finney class Addable(Finnney.Immutable): pass Finney.Immutable = Addable Which means that from now on *your* code that tries to create Immutables will actually get Addables. The inability to do this in B&D languages is - well, painfull. That Python doesns't require the boilerplate in a good thing. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From pkilambi at gmail.com Mon Nov 21 15:11:24 2005 From: pkilambi at gmail.com (pkilambi at gmail.com) Date: 21 Nov 2005 12:11:24 -0800 Subject: ignore specific data In-Reply-To: <86br0dg4uv.fsf@bhuda.mired.org> References: <1132596504.619762.237610@g47g2000cwa.googlegroups.com> <86br0dg4uv.fsf@bhuda.mired.org> Message-ID: <1132603884.655989.327180@f14g2000cwb.googlegroups.com> thanks for that. But this will check for the exact content of the "start of block......" or "end of block". How about if the content is anywhere in the line? From mwm at mired.org Wed Nov 2 09:35:21 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 02 Nov 2005 09:35:21 -0500 Subject: how to check for unix password References: <1130927459.936730.50190@o13g2000cwo.googlegroups.com> Message-ID: <86hdavce3a.fsf@bhuda.mired.org> eight02645999 at yahoo.com writes: > i created a login page that authenticate the user and his/her password > to the unix ssystem. what modules can i used to compare the unix > password with what the user typed in the cgi form? the password is > encrypted (shadowed) so i need to > decrypt it first before comparing to what the user typed. or this > cannot be done at all? As has already been pointed out, users authenticate to Unix systems with a lot more than passwords. Also, it's not a good idea to make a web page use a system password. Web page passwords tend to be poorly protected. Finally, you can't decrypt a Unix password file password. The algorithm is to encrypt what the user typed (with crypt.crypt) then compare that with the entry in the password file. You pass crypt.crypt the user-entered pasword as the first argument, and the password from the password file as the second, and compare the returned value to the password from the password file. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From d at d.com Mon Nov 7 19:56:05 2005 From: d at d.com (python) Date: Mon, 7 Nov 2005 19:56:05 -0500 Subject: how to modify code while debugging it without having to stop and then restart debugger Message-ID: hello and thanks for reading this, i have been a dos/windows user using some form of the basic language for 30 years now. i own and run a small programming company and there is one feature that keeps me in the windows/basic world. while i will agree that it has not evolved well, it does have one awesome feature that i have yet to see replicated in any linux product that i know about so far. i am a long time windows user and have had a great way to learn new api. to write some code and then run it. if there is an error, the debugger will load. then i can figure out what the eror is, just touch up the ocde and continue to run the code. i do not have to stop the code, modify the code, rerun the code. often an error will only happen after a complex set of conditions and not have to completely stop the app is a fantastic way to debug. there are several applications that can do this. in fact, the free version of the visual studio 2005, which is free, have this ability. so how can i use python to debug code and change that code without having to restart the code. thanks so much, dave From claudio.grondi at freenet.de Wed Nov 16 15:46:29 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 16 Nov 2005 20:46:29 -0000 Subject: newbie - How do I import automatically? References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> <3u0el9Fum367U1@individual.net> <1132154531.395649.168870@g14g2000cwa.googlegroups.com> <3u1ce5Fv1b5jU1@individual.net> <1132167930.785898.172070@o13g2000cwo.googlegroups.com> Message-ID: <3u1gkvFv9e85U1@individual.net> Probably you have inbetween already found the 'def runsource(' line in the PyShell.py , but maybe you still wait for a reply, so here it is: yes, you put the two lines at the beginning of in PyShell.py existing runsource() method of the class ModifiedInterpreter(InteractiveInterpreter) If in my Windows IDLE version the things are different from yours, sorry, I can't help in that case having no Linux installation available. Claudio schrieb im Newsbeitrag news:1132167930.785898.172070 at o13g2000cwo.googlegroups.com... > Where do I put > > def runsource(self, source): > if(source == ''): > source = 'from btools import *' > "Extend base class method: Stuff the source in the line cache > first" > filename = self.stuffsource(source) > > Do I put it in Pyshell.py or somewhere else? > > Bob > From steve at holdenweb.com Thu Nov 10 02:14:27 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 10 Nov 2005 07:14:27 +0000 Subject: How to set program name in Python? ($0 in Perl) In-Reply-To: References: <1131604682.713383.284230@g49g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > > >>>Is there a way to set the program name in Python, similar to $0 in >>>Perl? >>> >>>>From `man perlvar`: >>> >>>$0 Contains the name of the program being executed. On some oper- >>> ating systems assigning to "$0" modifies the argument >>>area that >>> the ps program sees. This is more useful as a way of >>>indicat- >>> ing the current program state than it is for hiding the >>>program >>> you're running. (Mnemonic: same as sh and ksh.) > > >>import sys >>print sys.argv[0] > > > that *gets* the name, but assigning to sys.argv[0] doesn't *set* it (afaik). > > setting the name involves overwriting the C level argv array, several large > buckets of worms, and huge portability issues, and is thus better left to non- > standard extensions. > Indeed. My bad. 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 rubencharles at gmail.com Sat Nov 12 08:55:43 2005 From: rubencharles at gmail.com (Ruben Charles) Date: Sat, 12 Nov 2005 09:55:43 -0400 Subject: tutorial example In-Reply-To: References: <20051112015026.74881.qmail@web35903.mail.mud.yahoo.com> Message-ID: On 11/12/05, Max Erickson wrote: > > Not in python. > > For example, what would you call the following? > > def rsum(n, m): > print n+m > return n+m > > > In python a method is callable attached to an object. A function is a > callable object constructed with a def statement. You are right, i was trying to explain the concept outside the objects. PD: I would call your example: a function. Without the return declaration, a routine or a method. From fredrik at pythonware.com Thu Nov 3 06:11:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Nov 2005 12:11:38 +0100 Subject: strtok equvialent ? References: <1131015553.805775.196230@g14g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > are there a strtok equivalent in python ? str.split() only takes single > seperator. use a regular expression split with a character group: >>> s = "breakfast=spam+egg-bacon" >>> import re >>> re.split("[-+=]", s) ['breakfast', 'spam', 'egg', 'bacon'] to deal with an arbitrary set of delimiting characters without having to bother with RE syntax, use re.escape: >>> re.split("[" + re.escape("-+=") + "]", s) ['breakfast', 'spam', 'egg', 'bacon'] From ashokagk at gmail.com Thu Nov 3 09:56:14 2005 From: ashokagk at gmail.com (Ashok) Date: 3 Nov 2005 06:56:14 -0800 Subject: how to associate files with application In-Reply-To: References: <1130439184.801178.280190@g14g2000cwa.googlegroups.com> Message-ID: <1131029774.628246.197080@g44g2000cwa.googlegroups.com> Thanks Lasse, that was really helpful From fredrik at pythonware.com Thu Nov 3 13:26:09 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Nov 2005 19:26:09 +0100 Subject: random number generator References: <1131041944.218053.16400@z14g2000cwz.googlegroups.com> Message-ID: > How to generate a random number in Python. Is there any build in > function I can call? >>> import random >>> help(random) also see: http://docs.python.org/lib/module-random.html From duncan-news at grisby.org Tue Nov 22 07:39:56 2005 From: duncan-news at grisby.org (Duncan Grisby) Date: Tue, 22 Nov 2005 13:39:56 +0100 Subject: How to write an API for a Python application? References: <437af434@news.bezeqint.net> <80842$437e51f0$520491f0$23836@nf2.news-service.com> Message-ID: <5f05b$4383119c$520491f0$4821@nf2.news-service.com> In article , Piet van Oostrum wrote: >On http://www.zeroc.com/performance/ they compare it with TAO and it seems >to be faster. It looks also a bit simpler. I don't have experience with Ice >myself but a colleague of mine experimented with it and was enthousiastic. > >It could well be that it is comparable in speed to omniORB, which is my >favorite platform for Corba on Python, or maybe even slower. Do you have >benchmark results about that? I've not done any benchmarks for Python (yet), but I've just posted some results to comp.object.corba that show omniORB is a lot faster than Ice for many things. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From fuzzyman at gmail.com Wed Nov 23 03:27:27 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Nov 2005 00:27:27 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <438258f2.411334718@news.oz.net> <4383635b.479535916@news.oz.net> Message-ID: <1132734447.104113.99140@o13g2000cwo.googlegroups.com> Christoph Zwerschke wrote: > >>I still believe that the concept of an "ordered dictionary" ("behave > >>like dict, only keep the order of the keys") is intuitive and doesn't > >>give you so much scope for ambiguity. But probably I need to work on an > >>implementation to become more clear about possible hidden subtleties. > > Bengt Richter schrieb: > > > Does that mean that the Larosa/Foord odict.py implementation in PyPI > > does not do what you want? > > Basically, it is what I had in mind. But I'm now seeing some things that > could be improved/supplemented, e.g. > - performance improvements Implementation changes to follow, based on suggestions in this thread. For *optimal* performance it needs to be implemented in C of course. :-) As F points out, a list of tuples may give you a data structure that can be accessed quicker (although some operations will be slower). An ordered dictionary will be a lot easier to use and make your code more readable though. > - the internal keys list should be hidden I disagree. It is exposed so that you can manually change the order (e.g. to create a "sorted" dict, rather than one ordered by key insertion). What do you *gain* by hiding it ? > - list methods should be mixed in instead > Hmm... I did consider this. Which list methods would you consider appropriate ? The difficulty is that integers are valid keys for a dictionary. Perhaps a subclass that uses integers as indexes instead... You can always perform list operations on the ``sequence`` attribute of course. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -- Christoph From python at rcn.com Tue Nov 8 21:09:50 2005 From: python at rcn.com (Raymond Hettinger) Date: 8 Nov 2005 18:09:50 -0800 Subject: which feature of python do you like most? References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: <1131502190.274658.237490@o13g2000cwo.googlegroups.com> > which feature of python do you like most? Indentation From kent37 at tds.net Sun Nov 6 13:01:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 13:01:37 -0500 Subject: modifying source at runtime - jython case In-Reply-To: References: <436cd898$1_3@newspeer2.tds.net> Message-ID: <436e42a7$1_2@newspeer2.tds.net> Jan Gregor wrote: > my typical scenario is that my swing application is running, and i see > some error or chance for improvement - modify sources of app, stop and run > application again. > so task is to reload class defitions (from source files) and modify also > existing instances (their methods). Ok, I think my first reply completely missed the mark. IIUC what you want is hard. This recipe might help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Kent From mwm at mired.org Sat Nov 12 13:11:40 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 12 Nov 2005 13:11:40 -0500 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> Message-ID: <86u0eh20tf.fsf@bhuda.mired.org> Paul Rubin writes: > "The Eternal Squire" writes: >> Without copyright, how could one possibly earn a living writing a >> novel? > This guy seems to be doing ok: http://craphound.com > His publishers are the only ones allowed to sell his novels commercially, > but you can download them all and print them out noncommercially for > your own personal enjoyment or to share with your friends. No obfuscation > is needed. Not really a good counterexample, because "His publishers are the only ones allowed to sell his novels commercially" is only possible because of copyright. Without that, anyone could take the downloadable copy of his novels and start competing with his publishers - presumably with lower overhead, because they didn't have to pay Cory. Asking about novels is an excellent question - it's one of the few forms of copyrightable material where it's not the final end product and you have to give the public access to the media for them to use it. If either one of those isn't true, you can probably find a business model that doesn't depend on copyright. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From aleax at mail.comcast.net Fri Nov 4 00:28:50 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 21:28:50 -0800 Subject: Learning multiple languages (question for general discussion) References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> Message-ID: <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> Magnus Lycka wrote: > John Salerno wrote: > > LOL. As weird as it sounds, that's what I *don't* want to happen with > > C#! I've spent a lot of time with it, and I love it, but I don't want > > Python to take over! :) > > Then it might be better to keep away from Python. It *will* spoil > you. Python is a good team player. It's excellent to use in large > projects where different languages fit better for different parts > of the final system,and it's excellent as a programmers tool even > if all production code is written in C# or whatever. Given a free > choice, you'll probably shift more and more of the code to Python > though,since it's faster to write and easier to maintain that way. Yes, but I haven't found knowing (and using) Python dampens my enthusiasms for learning new languages. Using a language for real life programming isn't the only reason to learn it, after all. Mozart (==Oz) is a great way to reflect on programming paradigms (and Van Roy's and Hariri's book is the 21st century equivalent of SICP!!!); Ruby offers an interesting perspective of a slightly different ways to do the same things Python is good at; O'Caml is an object (;-) lesson in how not all functional languages are elegant rather than practical; Boo shows how Pythonic syntax might go with static typing and inference; pyrex shows how Pythonic syntax might go with optional static typing to generate quite decent C code; sawzall (http://labs.google.com/papers/sawzall.html) is a great example of a very specialized language; Limbo (http://www.vitanuova.com/inferno/papers/limbo.html) has its good moments, and any language designed by Ritchie must be worth looking at for that sole reason; Erlang shows a very different FP language... These are all languages I studied after falling in love with Python -- i.e., in the last 6 years. At 8 languages in 6 years, I meet or exceed the "one new language a year" recommendation of the Pragmatic Programmers, on average -- admittedly, out of these, only sawzall and pyrex are ones I've used "for real", the other ones I've studied but never found real-life occasions to use, but that, too (using IRL about 25% of the languages one learns), is roughly par for the course (I would guess that over my lifetime I've learned about 50 languages and seriously used maybe a dozen of them...). Alex From sanjay.k.arora at gmail.com Wed Nov 30 03:48:39 2005 From: sanjay.k.arora at gmail.com (Sanjay Arora) Date: Wed, 30 Nov 2005 14:18:39 +0530 Subject: Newbie: Python & Serial Port question Message-ID: <1133340520.3509.130.camel@swayam.transcontinental.co.in> Am a python newbie. Does python have a native way to communicate with a PC serial port? I found that pyserial needs java. I am using Linux..CentOS 4.2, to be exact, no java installed and zilch/no/none/maybe never experience of java too. I have an application where I want to resd logs from the serial port of an EPABX and log them to a postgreSQL database. What's the best way to do this using python? Does anyone know of an existing software/python library/module for this? Please help. With best regards. Sanjay. From deets at nospam.web.de Sat Nov 26 21:39:39 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Nov 2005 03:39:39 +0100 Subject: SOAP - Beginner Desperately looking for Help In-Reply-To: <3uskfeF12hhjqU3@uni-berlin.de> References: <3uskfeF12hhjqU3@uni-berlin.de> Message-ID: <3uskjcF12hhjqU4@uni-berlin.de> > I wanted to attach these - however, > taht didn't work for NNTP, so I mail them to you. Didn't work - my mail server won't let me send these to you. So you're on your own here. Shouldn't be too hard :) Diez From cvanarsdall at mvista.com Wed Nov 16 15:18:29 2005 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 16 Nov 2005 12:18:29 -0800 Subject: repeating regular expressions in one string In-Reply-To: <20051116200956.8273.qmail@server285.com> References: <20051116200956.8273.qmail@server285.com> Message-ID: <437B9415.5040303@mvista.com> Shane wrote: > Hi folks, > > I'm new to regular expressions (and a novice at Python) but it seems to be the tool I need for a particular problem. I have a bunch of strings that looks like this: > > 'blahblah_sf1234-sf1238_blahblah' > > and I would like to use the re module to parse all the 'sfXXXX' parts of the string. Each 'sfXXXX' needs to be its own string when I am through. How do I compile a regular expression that looks for more than one instance? Currently my expression looks like this: > > myString = re.compile('sf[0-9][0-9][0-9][0-9]') > > Well, since all your strings come in the same format you might try something like myString = re.compile(r'\w+_(sf\d\d\d\d)-(sf\d\d\d\d)_\w+') then when you do your matching: extracted = myString.match(originalStrnig) your two extracted strings would be accessible via: extracted.group(1) extracted.group(2) > This works great for finding the first instance of 'sfXXXX'. I hope that was clear :) > > Thanks, > > Shane > From steve at REMOVETHIScyber.com.au Thu Nov 24 05:55:06 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 24 Nov 2005 21:55:06 +1100 Subject: wxPython Licence vs GPL References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> <86hda2zcli.fsf@bhuda.mired.org> <1132820796.119386.309160@o13g2000cwo.googlegroups.com> Message-ID: On Thu, 24 Nov 2005 00:26:36 -0800, bonono at gmail.com wrote: > As for the liability, that is for sure, withness what is happening for > the linux kernel. What is happening for the Linux kernel? -- Steven. From rurpy at yahoo.com Tue Nov 22 11:53:07 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 22 Nov 2005 08:53:07 -0800 Subject: about sort and dictionary In-Reply-To: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> Message-ID: <1132678387.884058.107900@z14g2000cwz.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > > so what would an entry-level Python programmer expect from this > > piece of code? > > > > for item in a.reverse(): > > print item > > for item in a.reverse(): > > print item > > > > I would expect it to first print a in reverse then a as it was. > > > > a=[1,2,3] > > > > I expect it to print > > > > 3 > > 2 > > 1 > > 1 > > 2 > > 3 > > > really? wouldn't > > 3 > 2 > 1 > 3 > 2 > 1 > > make a lot more sense ? I am not a complete newb at python, but I am still pretty new. I too thought immediately that the output should be 3,2,1, 1,2,3. I used reverse() and sort() a couple time and of course read the docs before I did. I noted they do the change inplace, and don't find rememering that to be a terrible burden. Actually, I get rather annoyed by the comment that they return None "as a reminder" that the change is inplace. How arrogant! While I'm sure the designers had kindly intentions. my memory, though bad, is not that bad, and I object to being forced to write code that is more clunky than need be, because the designers thought they needed to help me with my memory. From steve at holdenweb.com Wed Nov 23 03:22:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Nov 2005 08:22:29 +0000 Subject: python gui using boa In-Reply-To: <1132637738.473190.311620@g43g2000cwa.googlegroups.com> References: <1132637738.473190.311620@g43g2000cwa.googlegroups.com> Message-ID: Ashok wrote: > hi, > i am trying to develop a small gui app using boa constructor. say this > app has one frame which has one static text control. i want the frame > to resize itself to the width of the text contrl when i change the > label of the text control via SetLabel(). how can i do this in boa > constructor? > > can anybody guide me to a good source for learning the use of sizers in > boa? > Sizers are a tricky topic, and there doesn't appear to be much that's specific to Boa. You could take a look in the wxPython wiki at http://wiki.wxpython.org/index.cgi/UsingSizers but whether this will help you with Boa I'm not sure. I have tried Glade and Boa as well as Python Card, and all I can really say is that I found it worth spending the money to *buy* wxDesigner. It's not a perfect product, but it fits my brain. Sorry if this isn't an option for you. 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 amfr.org at gmail.com Wed Nov 30 20:07:44 2005 From: amfr.org at gmail.com (amfr) Date: 30 Nov 2005 17:07:44 -0800 Subject: Code returns error when not supposed to Message-ID: <1133399264.207054.293230@z14g2000cwz.googlegroups.com> This code always returns a ValueError when it is not supposed to: i = rest.rfind('?') Error: ValueError: need more than 0 values to unpack rfind is not supposed to generate an erro, just return -1. Any ideas? From aleax at mail.comcast.net Mon Nov 7 23:44:12 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 7 Nov 2005 20:44:12 -0800 Subject: BayPIGgies: November 10, 7:30pm (Google) References: Message-ID: <1h5obxy.15fgk5w1l9z7cuN%aleax@mail.comcast.net> Aahz wrote: > The next meeting of BayPIGgies will be Thurs, November at 7:30pm at > Google (Bldg 43, room Tunis). 1600 Amphitheater Parkway in Mountain View (CA), btw. > Hasan Diwan will demonstrate a prototype GPS system written in Python. > Let's all work to convince him that he doesn't need to rewrite it in > Java! Hear, hear! > BayPIGgies meetings alternate between IronPort (San Bruno, California) > and Google (Mountain View, California). For more information and > directions, see http://www.baypiggies.net/ ...and if you're interested in a Google-offered dinner, at 6:30pm just before the meeting, please email Neal Norwitz, nnorwitz at google.com, ***ASAP*** -- in theory the number of dinner-attendees is now set (we had to confirm said number earlier this afternoon), but maybe we can make space for you. As the "price" for your dinner, you'll have to listen to a short spiel by a Google recruiter explaining why we desperately need YOU (or more generally brilliant Pythonistas interested in working for Google!-)... If you show up at 7:30pm, after dinner, you won't have to listen to anything except Hasan's talk (but, you'll miss a chance to sample Google's famous food...;-). Emailing Neal would still be nice, just so we know you're expected to show up... but, not absolutely _required_! Alex From aleax at mail.comcast.net Fri Nov 18 00:25:44 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 17 Nov 2005 21:25:44 -0800 Subject: Hot to split string literals that will across two or more lines ? References: <1132284614.326121.252250@g49g2000cwa.googlegroups.com> <*firstname*nlsnews-A71E9A.23194917112005@news.verizon.net> Message-ID: <1h66wln.1beu8uj10yn7caN%aleax@mail.comcast.net> Ben Finney wrote: > Tony Nelson <*firstname*nlsnews at georgea*lastname*.com> wrote: > > While we're at it, I use bracketing instead of line continuation: > > > > print ( "a long string, longer than this " > > "and some more of the string" ) > > To continue the pedantry: Those are parentheses, not brackets. > > Slightly more on-topic, the parentheses make it look like a sequence > to this reader (though, without a comma, not to the Python parser, of > course). Nevertheless, my favorite style has also always been to use parentheses, and I was glad to see, on joining Google and studying its in-house Python style guide, that Google mandates that style, too. After all, though they're overloaded, it's _commas_ that make a tuple, not parentheses, which essentially just *group* things (in cases where the language's syntax would otherwise not suit you). So, you always do have to watch out for commas, ayway, since, e.g., x = "Sempre caro", "mi fu" and x = "Sempre caro mi fu" are so different -- it makes no difference whether either or both of these assigments use parentheses (after the = and at line end), it's the comma that does make all the difference. So, you can see it as a very good side effect of the "long string use parentheses, not backslashes" style rule, that the reader is soon weaned of the mistake of believing that parentheses signify tuples. Alex From apardon at forel.vub.ac.be Mon Nov 7 03:04:04 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 08:04:04 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Op 2005-11-04, Christopher Subich schreef : > Antoon Pardon wrote: > >> Except when your default is a list >> >> class foo: >> x = [] # default >> >> a = foo() >> a.x += [3] >> >> b = foo() >> b.x >> >> This results in [3]. So in this case using a class variable x to >> provide a default empty list doesn't work out in combination >> with augmented operators. > > This has nothing to do with namespacing at all, Yes it has. > it's the Python > idiosyncracy about operations on mutable types. In this case, += > mutates an object, while + returns a new one -- as by definition, for > mutables. It is the combination of the two. If python had chosen for an approach like function namespaces, the problem wouldn't have occured either. What would have happened then is that the compilor would have noticed the a.x on the right hand side and based on that fact would then have deciced that all a.x references should be instance reference (at least in that function block). The a.x += ... would then result in an AttributeError being raised. You may prefer the current behaviour over this, but that is not the point. The point is that resolution of name spaces does play its role in this problem. It also has little to do with mutable vs immutable types. Someone could implement an immutable type, but take advantage of some implemtation details to change the value inplace in the __iadd__ method. Such an immutable type would show the same problems. -- Antoon Pardon From jstroud at mbi.ucla.edu Tue Nov 1 17:09:28 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 1 Nov 2005 15:09:28 -0700 Subject: WTF? Message-ID: <200511011409.28683.jstroud@mbi.ucla.edu> Why do my posts get held for suspcious headers and troll Xha Lee gets to post all sorts of profanity and ranting without any problem? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bokr at oz.net Fri Nov 11 23:39:18 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 12 Nov 2005 04:39:18 GMT Subject: list of lambda References: <7xoe4q4n21.fsf@ruckus.brouhaha.com> Message-ID: <43757052.262288140@news.oz.net> On 11 Nov 2005 18:28:22 -0800, Paul Rubin wrote: >jena writes: >> l=[lambda:x.upper() for x in ['a','b','c']] >> then l[0]() returns 'C', i think, it should be 'A' > >Yeah, this is Python late binding, a standard thing to get confused >over. You want: > > l = [lambda x=x: x.upper() for x in ['a', 'b', 'c']] or if you want the upper() eagerly (and do it only once each, in case of multiple lambda calls) l = [lambda x=x.upper():x for x in ['a', 'b', 'c']] >>> l = [lambda x=x.upper():x for x in ['a', 'b', 'c']] >>> for lamb in l: print lamb.func_defaults[0],'=?=',lamb() ... A =?= A B =?= B C =?= C Regards, Bengt Richter From calfdog at yahoo.com Thu Nov 3 13:44:01 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 3 Nov 2005 10:44:01 -0800 Subject: Web automation (was: Pressing a Webpage Button) In-Reply-To: <1131042041.155434.254810@g44g2000cwa.googlegroups.com> References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> <1131042041.155434.254810@g44g2000cwa.googlegroups.com> Message-ID: <1131043441.814308.9480@g44g2000cwa.googlegroups.com> Twill or Pamie looks good, if your looking for a solution using Python. If you are looking for Cross- browser solution for testing there is also selenium that does that. The have some code for use in Python. There is also WATIR in RUBY and SAMIE in PERL It depends on your enviroment and needs. Hope that helps!! Rob M. From dont at spam.me Mon Nov 7 16:16:18 2005 From: dont at spam.me (Bugs) Date: Mon, 07 Nov 2005 13:16:18 -0800 Subject: PyFLTK - an underrated gem for GUI projects In-Reply-To: References: Message-ID: Roger Binns wrote: > > It is possible to make the wxPython smaller by having more DLLs each with > fewer widgets in it. That way you will only suck in the ones you use. > I find this VERY interesting Roger, I've been contemplating making such a request to the maintainer of wxPython (when he gets back). It would be ideal if there was some way to break up the wx library into smaller logical chucks so as little of wx as possible is distributed when utilizing tools such as py2exe. Plus, there are parts of wx that aren't wrapped by the wxPython classes that don't need to go anyways. Do you have any more information to share on this Roger? Thanks! From eternalsquire at comcast.net Wed Nov 16 19:22:11 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 16 Nov 2005 16:22:11 -0800 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> Message-ID: <1132186931.445973.140900@o13g2000cwo.googlegroups.com> Plenty of case law exists behind judgements made to repair loss of sales opportunites... these are called infringement upon sales territories.. From dwahler at gmail.com Fri Nov 4 11:22:23 2005 From: dwahler at gmail.com (David Wahler) Date: 4 Nov 2005 08:22:23 -0800 Subject: Shareware in Python In-Reply-To: References: Message-ID: <1131121343.926733.116830@g44g2000cwa.googlegroups.com> Ivan Sas wrote: > I want to create some shareware program in Python. Can I distribute > this program with > python24.dll file from Python 2.4.2? I'm not sure if Python GPL > compatible license allowing for doing it. > Thanks, > Ivan Sas Python is distributed under its own license, not the GPL: see http://www.python.org/2.4.2/license.html for details. I've just skimmed it, and it looks like you're fine as long as you include the Python license agreement and copyright notice. -- David From aleax at mail.comcast.net Sun Nov 20 21:11:00 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 20 Nov 2005 18:11:00 -0800 Subject: Why are there no ordered dictionaries? References: Message-ID: <1h6c7sd.1z0nwvuy4g9c9N%aleax@mail.comcast.net> Christoph Zwerschke wrote: ... > The 'sorted' function does not help in the case I have indicated, where > "I do not want the keys to be sorted alphabetically, but according to > some criteria which cannot be derived from the keys themselves." Ah, but WHAT 'some criteria'? There's the rub! First insertion, last insertion, last insertion that wasn't subsequently deleted, last insertion that didn't change the corresponding value, or...??? Alex From fredrik at pythonware.com Tue Nov 1 13:28:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 1 Nov 2005 19:28:39 +0100 Subject: Python's website does a great disservice to the language References: Message-ID: message = message.replace("you're", "your") From michaelschneider at fuse.net Wed Nov 16 12:08:00 2005 From: michaelschneider at fuse.net (Michael Schneider) Date: Wed, 16 Nov 2005 12:08:00 -0500 Subject: AJAX => APAX? Or: is there support for python in browsers? In-Reply-To: <1h6439o.11s40bt880tllN%aleax@mail.comcast.net> References: <6qpln1hg7q5up93kder88seduphnjpebtg@4ax.com> <1h6439o.11s40bt880tllN%aleax@mail.comcast.net> Message-ID: <437B6770.3050000@fuse.net> Alex, Good point. Can python be used to write firefox extensions that could be called from javascript? 1) javascript would come in on the HTML page 2) javascript would communication with the Extension API 3) the extension would be written in python That way, you would only need to make your extension's API safe to the wild. It would require the user to download an extension, but flash, et all seem to do ok. Is this possible today? Thanks Mike PS. Sorry for my ignorance on this, I am a client-side developer, trying to explore serious client development. Alex Martelli wrote: > Tim Roberts wrote: > ... > >>Internet Explorer will allow any registered ActiveScript language to be >>used in a web page. Python qualifies. In the latest Win32 extensions, >>there is a script in win32comext/axscript/client/pyscript.py that will >>register Python as an ActiveScript language. >> >>The you can say >> >> > > > Out of curiosity, how "sandboxed" is this Python? I remember a similar > solution being withdrawn once because it wasn't really safely sandboxed, > so the ``script'' could easily do any arbitrary damage to the machine... > > > Alex -- The greatest performance improvement occurs on the transition of from the non-working state to the working state. From cito at online.de Mon Nov 28 17:30:31 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 28 Nov 2005 23:30:31 +0100 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Aahz wrote: >Christoph wrote: >>Aahz wrote: >>>Christoph wrote: >>>>For instance, I just wanted to use the index() method on a tuple which >>>>does not work. ... >>> >>>Because Guido believes that tuples should be primarily used as >>>lightweight replacements for C structs. Therefore they have minimal >>>functionality. >> >>But the problem is that the tutorials and manuals give the impression >>that the difference between lists and tuples is only mutablity versus >>immutability. They don't talk about such considerations and honestly >>speaking even now I know that it does seem more plausible for me. > > Then feel free to submit patches for the docs. Why should I patch the docs to add things that don't seem plausible for me? I'd rather change the behavior to be more consistent instead tweaking the docs to somehow justify the inconsistent behavior. > PS: If you want further responses from me, please follow standard Usenet > quoting conventions (like those above). I am tempted to answer, "A Foolish Consistency is the Hobgoblin of Little Minds" ;-) No honestly, it was not in bad faith. I'm just not a regular usenet user and believed one attribution line per post should suffice. But reading the conventions I agree that they make sense. And I think it's a good analogy. Some people dislike Python's stringent whitespace syntax and "one obvious way" rule because it does not give them freedom to write programs in their individual style. But I don't think it's "foolish consistency" - it simply makes programs of others more easy to read, you can concentrate on the content and not the style. It's the same reason why people use quoting conventions. And BTW, I think that makes particularly suited for open source and XP projects. -- Christoph From simon.brunning at gmail.com Wed Nov 23 07:16:28 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 23 Nov 2005 12:16:28 +0000 Subject: SelfExtract with zipfile In-Reply-To: References: Message-ID: <8c7f10c60511230416s55e9dcdfm@mail.gmail.com> On 23/11/05, Catalin Lungu wrote: > Hi, > I need to compress files in self-extract archive. I use the zipfile module. > Is there an option or parameter to do that? No, AFAIK. If you have a command line tool, perhaps you could try driving that. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From andrew.nelis at gmail.com Tue Nov 15 05:20:21 2005 From: andrew.nelis at gmail.com (Andrew Nelis) Date: 15 Nov 2005 02:20:21 -0800 Subject: Parse file into array References: <1132004925.481923.47520@z14g2000cwz.googlegroups.com> <1132007477.237649.40740@g44g2000cwa.googlegroups.com> Message-ID: <1132050021.243510.122440@f14g2000cwb.googlegroups.com> If it helps, there's a builtin module for figuring out mimetypes; http://docs.python.org/lib/module-mimetypes.html >>> import mimetypes >>> mimetypes.guess_type('.gif') ('image/gif', None) Cheers, Andy. From grante at visi.com Tue Nov 1 18:29:11 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Nov 2005 23:29:11 -0000 Subject: WTF? References: <11mfqsibenjoqff@corp.supernews.com> Message-ID: <11mfui7aht4520@corp.supernews.com> On 2005-11-01, James Stroud wrote: > On Tuesday 01 November 2005 14:26, Grant Edwards wrote: >> On 2005-11-01, James Stroud wrote: >> > Why do my posts get held for suspcious headers > ... >> Held? It's not a moderated group... > > And I quoteth (that's King James for "cuteth-and-pasteth"): Nope. IIRC, Jacobean English first person doesn't add a suffix onto the verb, so it's the same as modern English: "I quote". The "eth" suffix is used for the third-person singular form of regular verbs: "He quoteth". >> Your mail to 'Python-list' with the subject Ah yes. I forgot that some of the postings to comp.lang.pythong are gatewayed from a mailing list. I still don't get why anybody would choose e-mail over an NNTP server for stuff like this. I don't even use e-mail for the mailing lists I do subscribe to: www.gmane.org. If a mailing list refuses to be carried by gmane, I figure I can do without it. [There was one mailing list of the dozen or so that I used to subscribe to that refused to be carried by gmane. That mailing list now does without me.] -- Grant Edwards grante Yow! I'm sitting on my at SPEED QUEEN... To me, visi.com it's ENJOYABLE... I'm WARM... I'm VIBRATORY... From http Wed Nov 2 10:24:28 2005 From: http (Paul Rubin) Date: 02 Nov 2005 07:24:28 -0800 Subject: Most efficient way of storing 1024*1024 bits References: <86d5ljcdtn.fsf@bhuda.mired.org> Message-ID: <7xr79zyswj.fsf@ruckus.brouhaha.com> Mike Meyer writes: > Six megabytes is pretty much nothing on a modern computer. I'd store > the things as a string of "0" and "1", and then use .find (or maybe > the in keyword) for doing the searches. > > This doesn't work very well if you're going to mutate the string, > though. You can use re.search on array.array byte vectors. I don't know how the speed compares with string.find. From gaudetteje at gmail.com Wed Nov 30 12:30:23 2005 From: gaudetteje at gmail.com (NavyJay) Date: 30 Nov 2005 09:30:23 -0800 Subject: How could I ask Thread B to call B().Method() from inside Thread A's run? In-Reply-To: References: <311b5ce10511300311u201c31aej6cc7f1e8cd42e232@mail.gmail.com> Message-ID: <1133371823.232492.81420@g44g2000cwa.googlegroups.com> I agree with jmj's solution, you would want to send a signal of some sort to Thread B from A when some event occurs in A. A queue is one way to do it, but keep in mind that there are numerous ways to communicate between threads/processes (queue, pipe, exit status, TCP/UDP message, etc.). I believe one of the first couple chapters in O'Reilly's "Programming Python" book discusses most of these methods. Choose the simplest one that meets your needs. From mclister at zeesource.net Mon Nov 7 12:21:54 2005 From: mclister at zeesource.net (Claire McLister) Date: Mon, 7 Nov 2005 09:21:54 -0800 Subject: [OT] Map of email origins to Python list Message-ID: <425926b9683e56644bf034dfb9ed65d7@zeesource.net> We've been working with Google Maps, and have created a web service to map origins of emails to a group. As a trial, we've developed a map of emails to this group at: http://www.zeesource.net/maps/map.do?group=668 This represents emails sent to the group since October 27. Would like to hear what you think of it. Thanks for listening. Claire -- Claire McLister ? ? ? ? ? ? ? ? ? ? ? mclister at zeesource.net 1684 Nightingale Avenue ? ??Suite 201 Sunnyvale, CA 94087? ? ? ? 408-733-2737(fax) http://www.zeemaps.com From jeff at schwabcenter.com Fri Nov 11 09:18:01 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Fri, 11 Nov 2005 14:18:01 GMT Subject: Job - PYTHON Engineers, BitTorrent, Inc., San Francisco, CA In-Reply-To: References: Message-ID: camdenjobs wrote: > PYTHON Engineers, BitTorrent, Inc., San Francisco, CA > > Interested candidates should forward their resumes to ... > Please understand that due to the large volume of responses, I will > not be able to acknowledge each of you individually. Now, that's confidence! May such optimism always be fulfilled. :) From lycka at carmen.se Tue Nov 8 03:04:55 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 08 Nov 2005 09:04:55 +0100 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > Fine that goes both ways. I don't mind not being taken serious by people > I have trouble taking serious my self. No doubt that goes for you too. You know Antoon, these internet communities aren't really like Speaker Corner in Hyde Park. You earn respect based on your merits, not from the stubborn persistence in you arguments. Steve has written a very good book on Python, he's worked a lot with Python conferences, and helped people on comp.lang.python for years etc. He has earned his respect. You are fighting wind mills, bickering about things that you don't have any solutions for. It's possible that you have just not realized how Python handles objects, names and classes, but I can't understand what you are trying to accomplish. What can you possibly try to convey that you haven't already stated? It's as if you've got stuck in this thread. In the real world, I haven't heard of anyone ever having had problems with this. Isn't it better to let it go and to spend your time on something constructive? I recently heard a priest say, that the difference between the saint and the fanatic is that the fanatic tries to remove the evil in the world, while the saint tries to remove the evil in himself. Just as introspection is useful both in fighting evil and in Python programming, I think it's useful when we get into heated discussions. I've always loved heated discussions, but over time, I've come to realize that the best thing that can happen in such a discussion is to realize that I was wrong. Then I've learnt something! If I don't change my mind, I'm just standing still. In that case, it might be useful for someone else, if she or he learnt something from it, but the best thing is if I learn something. This thread is all to infected to lead to good things. Hopefully you'll learn something about communication from it, but the price has been higher than you might be aware of right now. From yaswanth at gmail.com Tue Nov 29 16:39:26 2005 From: yaswanth at gmail.com (Yaswanth Narvaneni) Date: Wed, 30 Nov 2005 03:09:26 +0530 Subject: Python Application Servers Message-ID: <56ca7a7e0511291339v4252ef2aj3c17ebbf2db4cc64@mail.gmail.com> Hi! I am a newbie and I have just started working on Python. I am planning to develop a web-based 1v1 game in flash and would like to use python as a back end for the game. I am an experienced programmer/web programmer, so I have no probs learning a new language from scratch and ppl tell me that Python is very easy to learn. I need you guys to suggest me a good application server to use along with Python to develop this game. My basic requirements are as follows: 1) Database abstraction -- Should act as a middle-layer so that Flash RPC calls wont directly have DB Access 2) Platfrom independence (back-end should work on both Windows and Linux). I have read about Zope and it looks very huge and complex. And I also read about SkunkWeb but some ppl claim that it wont work in windows. Webware is still in its 0.9 stages and I didnt find any good documentation on it. So I am kinda confused, so it would be great if any of you guys can help me out to decide which is the best. Regards, Yaswanth -- "In theory there is no difference between theory and practice. In practice there is." -- Fortune Cookie From berrybear at gmx.net Mon Nov 28 10:43:39 2005 From: berrybear at gmx.net (Anton81) Date: Mon, 28 Nov 2005 16:43:39 +0100 Subject: Extracting documentation for user relevant functions only? Message-ID: Hi, I've written a python script and added short docstrings. Now I'd like to create a short overview of commands the user can use. However I don't want the internal stuff that I also commented. Is there a way to create a fancy documentation (e.g. pydoc) of certain functions only? Anton From david.rasmussen at gmx.net Sat Nov 12 19:03:05 2005 From: david.rasmussen at gmx.net (David Rasmussen) Date: Sun, 13 Nov 2005 01:03:05 +0100 Subject: Multikey Dict? Message-ID: <437682b5$0$2108$edfadb0f@dtext02.news.tele.dk> If I have a collection of dicts like: john = {'id': 1, 'name': "John Cleese", 'year': 1939} graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} I could store all of them in a list. But for easy lookup, I might store all these in a dict instead, like people = {'1': john, '2': graham} or maybe people = {'John Cleese': john, 'Graham Chapman': graham} or whatever key I might choose. Now, first of all, it seems a bit annoying that I have to keep that redundant data in the second dict that is already in the individual dicts within people. Secondly (and this is my question), it is annoying that I have to choose one of several unambiguous keys as a key. I would like to be able to say: people['1'].year in some case and in other cases I want to say people['John Cleese'].year That is, sometimes I have the name at hand and would like to look up data based on that. Other times, I have the ID at hand and would like to look up data based on that instead. Also, I would like if I didn't have to keep the key data both in the dict of dicts and in the dicts :) If I could just say to Python: john and graham (and ...) are all a part of a "superdict" and either their id or their name can be used as keys. Can I do that somehow? /David From aleax at mail.comcast.net Fri Nov 4 01:46:11 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 3 Nov 2005 22:46:11 -0800 Subject: I need Motivation References: Message-ID: <1h5h37v.1137jn51yis6zmN%aleax@mail.comcast.net> blah at blah.blah wrote: > I m not a python Expert or anythin > i need help, i m losin my motivation to continue with python > can anyone inspire me again.??? Not without knowing more about your motivations for starting Python in the first place... Alex From chris.cahoon at gmail.com Wed Nov 30 14:18:29 2005 From: chris.cahoon at gmail.com (ccahoon) Date: 30 Nov 2005 11:18:29 -0800 Subject: wxPython - processes Message-ID: <1133378309.639047.271450@g49g2000cwa.googlegroups.com> In wxPython, I want to be able to start downloading a file and have the window doing such remain interactive, so that the user can cancel downloading the next file. Also, if there is a way to cancel a downloading process, what is it? I am using urllib.urlretrieve. Thanks for any help, in advance. From roccomoretti at hotpop.com Tue Nov 22 19:10:20 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 22 Nov 2005 18:10:20 -0600 Subject: [Fwd: Re: hex string to hex value] In-Reply-To: References: Message-ID: tim wrote: > ok, but if i do > > >>> n=66 > >>> m=hex(n) > >>> m > '0x42' > >>> h=int(m,16) > >>> h > 66 > >>> > > I end up with 66 again, back where I started, a decimal, right? > I want to end up with 0x42 as being a hex value, not a string, so i can > pas it as an argument to a function that needs a hex value. > (i am trying to replace the 0x42 in the line midi.note_off(channel=0, > note=0x42) with a variable) >>> note = 0x42 >>> print note 66 >>> note is 66 True There is no such thing as a "hex value"- only hex *representations* of a value. midi.note_off() doesn't take a "hex value", it takes an integer, and, for whatever reason, it happens to be listed in your example in a hexidecimal representation. From scott.daniels at acm.org Fri Nov 11 12:15:18 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 11 Nov 2005 09:15:18 -0800 Subject: Lie Hetland book: Beginning Python.. In-Reply-To: References: Message-ID: <4374d066$1@nntp0.pdx.net> Magnus Lycka wrote: > Vittorio wrote: > Using the same symbol for both string substitutions and SQL placeholder > such as pysqlite 1 and the MySQL interface does, is not really a bright > idea in my opinion. Who thinks this is pretty? > > sql = "SELECT %s FROM %s WHERE %s = %%s" > cur.execute(sql % (col,table,search_col), (param,)) > > I think it's less confusing with: > > sql = "SELECT %s FROM %s WHERE %s = ?" > cur.execute(sql % (col,table,search_col), (param,)) > or you could use: sql = "SELECT %s FROM %s WHERE %s = %s" cur.execute(sql % (col,table,search_col, '%s'), (param,)) which I like better, because you don't have to read extremely carefully for the double-percents. --Scott David Daniels scott.daniels at acm.org From ajikoe at gmail.com Wed Nov 30 18:58:51 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 30 Nov 2005 15:58:51 -0800 Subject: help python swig problem Message-ID: <1133395131.393065.32480@g44g2000cwa.googlegroups.com> Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c */ #include double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); } ------------------------- /* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); ------------------------------------------------------------ I write this in my dos console: swig -python example.i # this is ok bcc32 -c example.c example_wrap.c # this has error I found this error: Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland example.c: example_wrap.c: Warning W8004 example_wrap.c 428: 'uu' is assigned a value that is never used in function SWIG_UnpackData Warning W8004 example_wrap.c 669: 'flags' is assigned a value that is never used in function PySwigObject_print Error E2063 example_wrap.c 791: Illegal initialization in function PySwigObject_type Warning W8057 example_wrap.c 1660: Parameter 'self' is never used in function _wrap_fact Warning W8057 example_wrap.c 1688: Parameter 'self' is never used in function _wrap_my_mod Warning W8065 example_wrap.c 1696: Call to function 'get_time' with no prototype in function _wrap_get_time Warning W8057 example_wrap.c 1702: Parameter 'self' is never used in function _wrap_get_time Warning W8060 example_wrap.c 2106: Possibly incorrect assignment in function SWIG_Python_FixMethods *** 1 errors in Compile *** How can I solve the problem. Thanks in advance. pujo From iddw at hotmail.com Wed Nov 23 09:44:58 2005 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 23 Nov 2005 08:44:58 -0600 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: On Tue, 22 Nov 2005 23:17:31 -0700 in comp.lang.python, Steven Bethard wrote: >rhettinger at gmail.com wrote: [...] >> IIRC, this was discussednd rejected in an SF bug report. It should not >> be a defined behavior for severals reasons: >[snip arguments about how confusing zip(it, it) is] >> Overall, I think anyone using zip(it,it) is living in a state of sin, >> drawn to the tempations of one-liners and premature optimization. They >> are forsaking obvious code in favor of screwy special cases. The >> behavior has been left undefined for a reason. > >Then why document itertools.izip() as it is? The documentation there is >explicit enough to know that izip(it, it) will work as intended. Should >we make the documentation there less explicit to discourage people from >using the izip(it, it) idiom? ISTM that one would use itertools.izip in order to get some functionality not available from zip. Perhaps this is one of those bits of functionality. But I admit, I'm not all that familiar with itertools... In any case, the solution seems obvious: if you want the guarantee, use the tool that provides it. Regards, -=Dave -- Change is inevitable, progress is not. From gsakkis at rutgers.edu Mon Nov 21 13:01:23 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 21 Nov 2005 10:01:23 -0800 Subject: about sort and dictionary References: Message-ID: <1132596083.632911.160610@g49g2000cwa.googlegroups.com> "Shi Mu" wrote: > Got confused by the following code: > >>> a [6, 3, 1] > >>> b [4, 3, 1] > >>> c > {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]} > >>> c[2].append(b.sort()) > >>> c > {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]} > #why c can not append the sorted b?? In python 2.4, you can use the sorted() builtin instead: c[2].append(sorted(b)) George From onurb at xiludom.gro Thu Nov 10 07:50:27 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 10 Nov 2005 13:50:27 +0100 Subject: getting results into one variable In-Reply-To: <1131611798.561119.48770@g43g2000cwa.googlegroups.com> References: <1131611798.561119.48770@g43g2000cwa.googlegroups.com> Message-ID: <43734215$0$639$626a14ce@news.free.fr> s99999999s2003 at yahoo.com wrote: > hi (snip) > > in python, can we do something like > > a = db.execute(stmt) and then expand variable 'a' > instead of doing > (a,b) = db.execute(stmt) for return of 2 > (a,b,c) = for return of 3 > (a,b,c,d) for return of 4 Did you try ?-) Took me about 30'': >>> def fun(): return 1,2,3 ... >>> a = fun() >>> a (1, 2, 3) >>> def fun2(): return 1,2,3,4,8,9 ... >>> b = fun2() >>> b (1, 2, 3, 4, 8, 9) >>> It of course works since a function *always* returns a *single* value. Now this value *can* be a sequence, and this sequence *can* be unpacked - directly at the return of the function, or latter: >>> a = fun() >>> a (1, 2, 3) >>> v1, v2, v3 = a >>> v1 1 >>> v2 2 >>> v3 3 >>> HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gh14tq5 at yahoo.com Mon Nov 21 06:18:09 2005 From: gh14tq5 at yahoo.com (gh14tq5 at yahoo.com) Date: Mon, 21 Nov 2005 20:18:09 +0900 Subject: tkinter and cygwin Message-ID: Hi, I've recently started learning python programming and have been experimenting with a few basic GUI programs. My work system is cygwin/Windows XP. I use X-windows in cygwin but when I run my python/tkinter program from an x-win terminal , a normal XP window is opened up. Any text output from the program of course shows up in the terminal I started the program from. Is there a way to make python open up a window in the X display instead of an XP window? It's really annoying because if I click on another window or terminal in the X-window screen, the X-window display will then cover up the python GUI. Thanks, John From bobueland at yahoo.com Thu Nov 17 07:30:37 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 17 Nov 2005 04:30:37 -0800 Subject: IDLE question References: <1132217965.434209.122200@f14g2000cwb.googlegroups.com> <3u3186FvbckvU1@individual.net> <1132221788.888868.8370@f14g2000cwb.googlegroups.com> <3u34abFv24c5U1@individual.net> <1132225335.948524.162190@g43g2000cwa.googlegroups.com> <3u3899Fv3vulU1@individual.net> <3u393bFtovgcU1@individual.net> Message-ID: <1132230637.099278.295980@z14g2000cwz.googlegroups.com> This works! Thanks Claudio For complete happiness I would also like to know what's hapening. Is there anywhere I can read about PyShell.py. Bob From mwm at mired.org Thu Nov 3 00:52:38 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 03 Nov 2005 00:52:38 -0500 Subject: another beginner sort of question References: Message-ID: <86hdaujn15.fsf@bhuda.mired.org> John Salerno writes: [Wants to learn C# and Python simultaneously.] > So my question is, is this feasible? Should be. It might be faster to do them sequentually. > Or does learning Python require (or entail) learning all the details > behind it? Not really. There are some traps you can fall into that are obvious if you know how the underlying implementation works, but even for those, you just need the general idea, not the details. > Also, do I need to know anything about C or C++? No. In fact, the less you know about them, the less you'll have to unlearn to use Python effectively. > Python seems to connected to those languages that I'm afraid > learning Python by itself might not be practical, but hopefully > that's unfounded. CPython (the implementation most people mean when they say "Python") is written in C, and has well-defined APIs for putting an interpreter into a C program, or making functionality from a C library available to a CPython program. Other implementations have similar hooks for different languages. Unless you want to get into the internals of an implementation, to embed Python in an application, or to write a Python extension (usually because you're wrapping an existing library), you won't need to worry about any of these. One thing. While Python is called a "scripting language", it doesn't have facilities for dealing with shell scripting that other "scripting languages" have. As such, it's harder to do shell scripting type things in Python than in those languages. On the other hand, it's easier than doing them in C, for the same reason that doing pretty much anything in Python is easier than doing it in C. On the gripping hand, if you do things pythonically instead of like you'd do them in a shell script, you may find that Python is easier than the shell script. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From nyamatongwe+thunder at gmail.com Mon Nov 7 18:13:02 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 07 Nov 2005 23:13:02 GMT Subject: [OT] Map of email origins to Python list In-Reply-To: References: Message-ID: <2cRbf.11232$Hj2.11218@news-server.bigpond.net.au> Claire McLister: > We try to get a best guess estimate of the originating IP and its > location. If we cannot find that, we fall back on the earliest server > that has a location information. Clearly this marks quite a few email > origins in the wrong way. It doesn't do the collection of ALL gmail > addresses this way, however. If you do a filter on 'gmail' in the 'Name' > filter, you'll see a lot of gmail addresses all over the world. So, we > need to do a better job of guessing the originating IP, and not try to > go too far forward. The points are labelled with the email address which won't always be the account posted from. I'm listed in both Sydney (correct) and Melbourne with my gmail account (actually a subaddress, nyamatongwe+thunder at gmail.com, only used for news posting) but I post to comp.lang.python through Thunderbird on my local machine through my ISP's news server. I expect the marked locations are for the ISP's news hubs. Gmail only comes into the picture when I'm sent spam in response to a post. Multiple locations for gmail doesn't imply discovery of real origins of traffic through gmail. Neil From aahz at pythoncraft.com Mon Nov 28 11:10:31 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Nov 2005 08:10:31 -0800 Subject: General question about Python design goals References: <1133192617.047862.104920@o13g2000cwo.googlegroups.com> Message-ID: In article <1133192617.047862.104920 at o13g2000cwo.googlegroups.com>, Paul Boddie wrote: > >In this case, I rather agree with the pragmatic responses earlier in >the thread: that it was probably an oversight that tuples lack the >count, index and (arguably) sorted methods, and that patches would >probably be welcome to rectify this state of affairs. You're wrong. I don't have time/energy to look up the relevant posts, but Guido has been extremely clear in the past that tuples are *NOT* going to grow methods. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair From steve at REMOVETHIScyber.com.au Tue Nov 1 16:52:29 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 02 Nov 2005 08:52:29 +1100 Subject: Python's website does a great disservice to the language References: Message-ID: On Tue, 01 Nov 2005 17:45:11 +0000, CppNewB wrote: > I was trying to advocate using Python for an upcoming prototype, so my boss > went out to take a look at the documentation and try and get a feel for what > the language is all about. > > First comment; "I hope the language is designed better than the site." First comment: "I hope your boss can tell the difference between good design of a computer language and good design of a website." What was his second comment? "But I never judge a book by its cover" or "I make technical decisions based on irrelevant factors"? > The site is readable, but is amateurish. If I had an ounce of design skills in > me, I would take a stab at it. Ah, well since you and your lack of design skills are such an expert on good design, perhaps you would like to enlighten us poor peons as to what in particular is amateurish about "the site". You might like to tell us in particular, which site? http://www.python.com/ perhaps? http://www.python.net/ http://www.python.org/ http://www.pythonware.com/ http://www.pygame.org/ Heaven forbid that your boss might have got confused and gone here: http://www.pythonline.com/ And then you might like to point us at a language site or two that your boss considers "professional". -- Steven. From chris.mccoy at spirentcom.com Thu Nov 3 00:21:55 2005 From: chris.mccoy at spirentcom.com (Newsfeeds) Date: Thu, 3 Nov 2005 00:21:55 -0500 Subject: Nested List Question Message-ID: <1130995475_2055@spool6-east.superfeed.net> Hello All, Could anyone tell me why this code produces the output it does? noAdjacencies = 2 gridsPerAdj = 3 rows = 4 columns = 5 gridSystemId = [[None]*columns]*rows for row in range(rows): for column in range(columns): gridSystemId[row][column] = "%d-%d" % (row,column) print gridSystemId Produces: [['3-0', '3-1', '3-2', '3-3', '3-4'], ['3-0', '3-1', '3-2', '3-3', '3-4'], ['3-0 ', '3-1', '3-2', '3-3', '3-4'], ['3-0', '3-1', '3-2', '3-3', '3-4']] Rather than: [['0-0', '0-1', '0-2', '0-3', '0-4'], ['1-0', '1-1', '1-2', '1-3', '1-4'], ['2-0 ', '2-1', '2-2', '2-3', '2-4'], ['3-0', '3-1', '3-2', '3-3', '3-4']] Thanks for your help, Chris M. ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-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 erick_bodine at comcast.net Wed Nov 16 14:30:18 2005 From: erick_bodine at comcast.net (erick_bodine at comcast.net) Date: 16 Nov 2005 11:30:18 -0800 Subject: creating package question Message-ID: <1132169418.759267.265090@o13g2000cwo.googlegroups.com> I have a package directory structure as follows root- | Common (contains __init__.py file) WindowsComponents (contains __init__.py file) ... I would like modules in the WindowsComponents directory to be able to import some modules from the Common directory. In my first pass, I was able to append sys.path ( sys.path.append('../Common') ) in each module that wants to import from Common, but this feels "clunky". Is there a "standard"/"best" way to accomplish this? --ERick From ggrp1.20.martineau at dfgh.net Wed Nov 30 18:24:52 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 30 Nov 2005 15:24:52 -0800 Subject: (newbie) N-uples from list of lists References: <1132776015.567869.214570@g14g2000cwa.googlegroups.com> <1132938602.483207.74600@f14g2000cwb.googlegroups.com> <1133254388.897596.125270@g47g2000cwa.googlegroups.com> Message-ID: <1133393092.845587.178500@f14g2000cwb.googlegroups.com> FWIW, I found Steven Taschuk's solution easiest to understand regarding the question posed in your original post -- namely how to solve the problem non-recursively with generators -- because it was similar to my own thinking about how to do it -- but suspect that Raymond Hettinger's is the likely the "best" (as is usually the case ;-). Best, -Martin vd12005 at yahoo.fr wrote: > great thanks to all. > > actually i have not seen it was a cross product... :) but then there > are already few others ideas from the web, i paste what i have found > below... > > BTW i was unable to choose the best one, speaking about performance > which one should be prefered ? > > ### -------------------------------------------------- > > ### from title: variable X procuct - [(x,y) for x in list1 for y in > list2] > ### by author: steindl fritz > ### 28 mai 2002 > ### reply by: Jeff Epler > > def cross(l=None, *args): > if l is None: > # The product of no lists is 1 element long, > # it contains an empty list > yield [] > return > # Otherwise, the product is made up of each > # element in the first list concatenated with each of the > # products of the remaining items of the list > for i in l: > for j in cross(*args): > yield [i] + j > > ### reply by: Raymond Hettinger > > def CartesianProduct(*args): > ans = [()] > for arg in args: > ans = [ list(x)+[y] for x in ans for y in arg] > return ans > > """ > print CartesianProduct([1,2], list('abc'), 'do re mi'.split()) > """ > > ### from: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975 > ### by: Raymond Hettinger > > def cross(*args): > ans = [[]] > for arg in args: > ans = [x+[y] for x in ans for y in arg] > return ans > > ### from: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975 > ### by: Steven Taschuk > """ > Iterator version, Steven Taschuk, 2003/05/24 > """ > def cross(*sets): > wheels = map(iter, sets) # wheels like in an odometer > digits = [it.next() for it in wheels] > while True: > yield digits[:] > for i in range(len(digits)-1, -1, -1): > try: > digits[i] = wheels[i].next() > break > except StopIteration: > wheels[i] = iter(sets[i]) > digits[i] = wheels[i].next() > else: > break From steve at REMOVETHIScyber.com.au Thu Nov 10 08:53:49 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 11 Nov 2005 00:53:49 +1100 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> Message-ID: On Wed, 09 Nov 2005 15:08:15 -0500, Yu-Xi Lim wrote: > As you said, if you have some novel features, you will need obfuscation. > Copyright doesn't protect the process and patents may take a while. In > the meanwhile, good obfuscation is reasonable protection, imho. > > But I think you failed to note that it may not be a novel feature or > useful functionality. In fact, it might be the opposite: a function the > users want removed. A typical example would be a shareware registration > or nag screen. When the users have to start paying, they might then feel > inclied to "rip off the code", or in this case, rip out the code. Which leads to the important counter-question. Since there is a Python obfuscator, is there a Python un-obfuscator? I am aware that not all obfuscations can be reversed, but some can. -- Steven. From lycka at carmen.se Tue Nov 1 09:25:25 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 01 Nov 2005 15:25:25 +0100 Subject: Forced to Embed? In-Reply-To: References: Message-ID: Lloyd wrote: > As far as I can tell I have to export these all in one massive module as > there is no way for the different python modules to directly communicate > with each other? I don't see how this is a Python issue. If you can make these modules into shared objects / dynamically linked libraries, and make a C++ application use them as such, you should be able to get this to work even if the main program is a Python program that imports them via a wrapper, right? Or is there something I missed? (I'm no expert in writing extensions.) I know that it's possible to mess up C/C++ code in such a way that dynamic linking requires a major rewrite, but I don't see that this has anything to do with Python except that you got two bright ideas at the same time: Use Python as main and modularize the code better. I guess you *should* pull up your sleeves and clean up your code, but it's not always that we get the time to do what we should... From jepler at unpythonic.net Sun Nov 13 22:02:57 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sun, 13 Nov 2005 21:02:57 -0600 Subject: Sorting dominoes In-Reply-To: References: Message-ID: <20051114030257.GA9372@unpythonic.net> So if you have the dominoes (1 2), (3 2) and (3 1) you must arrange them as 1|2|3 2|3|1 ? If so, then it seems to me your algorithm is this: 1. pick an arbitrary domino to be first, and an arbitrary side to be the "top" 2a. until the dominoes are exhausted, pick the other domino with the same digit as the "bottom" of the last domino picked, and put that digit on the top. 2b. If there is no domino with the same digit, then pick an arbitrary domino as in step 1 Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From http Sun Nov 6 12:13:39 2005 From: http (Paul Rubin) Date: 06 Nov 2005 09:13:39 -0800 Subject: Learning multiple languages (question for general discussion) References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> <1h5hs5y.19u42x51mo5hupN%aleax@mail.comcast.net> Message-ID: <7xvez5wvgc.fsf@ruckus.brouhaha.com> aleax at mail.comcast.net (Alex Martelli) writes: > I can't imagine NOT getting enthusiastic and stimulated by reading Van > Roy and Hariri's book -- it IS quite as good and readable as SICP. It's been on my want-to-read list for a long time. I have the downloaded draft edition (from before the print edition came out) and it looks quite good. The Oz language has some interesting approaches. > Ruby's also blessed with good books (and the excellent Rails, too). I haven't been terribly interested in Ruby; it may have a more rigorous OO approach than Python, but Smalltalk already did that decades ago. So Ruby seems like yet another Perl-like language. Am I missing something? Do you have any opinion of "Types and Programming Languages" by Pierce? Autrijus Tang (the guy who started PUGS, the Perl 6 implementation in Haskell) raves about it in an interview, and another guy I know recommended it too, but I haven't actually looked at a copy yet (stores I've looked in don't have it). Haskell is the language that I guess interests me the most these days (in terms of learning new ones), but I haven't yet attempted doing anything with it. From bokr at oz.net Wed Nov 23 05:59:10 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 23 Nov 2005 10:59:10 GMT Subject: Anyway to clarify this code? (dictionaries) References: <1132711108.860281.59900@g49g2000cwa.googlegroups.com> <4383e5be.512914622@news.oz.net> <1132717960.162419.96100@g44g2000cwa.googlegroups.com> Message-ID: <4384470e.537826874@news.oz.net> On 22 Nov 2005 19:52:40 -0800, "bonono at gmail.com" wrote: > >Bengt Richter wrote: >> >>> def my_search(another, keys, x): return dict((k,another[k]) for k in keys if another[k]>x) >> ... >> >>> my_search(another, 'cb', .3) >> {'b': 0.35806602909756235} >> >>> my_search(another, 'abcd', .4) >> {'a': 0.60649466203365532, 'd': 0.77440643221840166} >> >Do you need to guard the case "k not in another" ? > Good catch ;-) What did the OP want as a value if any for that case? None? or no entry at all? Taking a cue from Mike, I like the set method of getting the common keys, to eliminate the entry (untested) def my_search(another, keys, x): return dict((k,another[k]) for k in (set(another)&set(keys)) if another[k]>x) otherwise, to get Nones, maybe (untested) def my_search(another, keys, x): return dict((k,another.get(k)) for k in keys if k not in another or another[k]>x) Regards, Bengt Richter From claudio.grondi at freenet.de Thu Nov 17 06:05:58 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 17 Nov 2005 11:05:58 -0000 Subject: newbie - How do I import automatically? References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> <3u0el9Fum367U1@individual.net> <1132154531.395649.168870@g14g2000cwa.googlegroups.com> <1132219559.826657.209940@f14g2000cwb.googlegroups.com> Message-ID: <3u330rFuppemU1@individual.net> The only difference I can see is, that you are on Python 2.3.4 and I use Python 2.4.2: "Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 - IDLE 1.1.2" So maybe if you upgrade ... this will become obsolete? Claudio "Mikael Olofsson" schrieb im Newsbeitrag news:dlhjtp$jhd$1 at news.island.liu.se... > bobueland at yahoo.com wrote: > > I tried to do it on my computer (win XP). I put an extra line in > > PyShell.py > > [snip] > > # test > > sys.modules['__main__'].__dict__['os'] = os > > [snip] > > Then when I start idle I get > > > > IDLE 1.1.1 > > > >>>>dir() > > > > ['__builtins__', '__doc__', '__name__'] > > > > > > So I don't see 'os' > > > > Do you see 'os' on your computer. If yes, what could be the difference? > > Yes, I do. The following is with IDLE 1.0.3 and Python 2.3.4 on WinXP. > > Without the line in PyShell.py: > > IDLE 1.0.3 ==== No Subprocess ==== > >>> dir() > ['__builtins__', '__doc__', '__file__', '__name__', 'main'] > > With the line in PyShell.py: > > IDLE 1.0.3 ==== No Subprocess ==== > >>> dir() > ['__builtins__', '__doc__', '__file__', '__name__', 'main', 'os'] > >>> os > > > I know nothing about the details of how IDLE work. All I know is what I > have reported here. I was simply inspired by the following remark from > Claudio Grondi up-thread: > > > edit the first lines of %SystemDrive%\Python24\Lib\idlelib\PyShell.py > > I guess that PyShell.py is imported as a module by IDLE at startup. > > One thought, though: Du you have more than one Python installed? If so: > Could it be that you are editing the wrong PyShell.py? > > Regards > /MiO From bignose+hates-spam at benfinney.id.au Fri Nov 25 21:36:59 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 26 Nov 2005 13:36:59 +1100 (EST) Subject: enum 0.3: Enumerations in Python Message-ID: Howdy all, I've uploaded enum 0.3 to the Cheeseshop. Enumerations are now sequences, iterable (as before) *and* indexable:: >>> from enum import Enum >>> Weekdays = Enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat') >>> pizza_night = Weekdays[4] >>> print pizza_night == Weekdays.thu True Since the values of an enumeration are directly reflected in the values and attributes, Enum instances are immutable to preserve this relationship:: >>> Weekdays.foo = object() [...] enum.EnumImmutableError: Enumeration does not allow modification >>> Weekdays.mon = Weekdays.fri [...] enum.EnumImmutableError: Enumeration does not allow modification >>> Weekdays[4] = object() [...] enum.EnumImmutableError: Enumeration does not allow modification The package's long description: """This package provides a class for robust enumerations in Python. An enumeration object is created with a sequence of string arguments to the Enum() function:: >>> from enum import Enum >>> Colours = Enum('red', 'blue', 'green') >>> Weekdays = Enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun') The return value is an immutable sequence object with a value for each of the string arguments. Each value is also available as an attribute named from the corresponding string argument:: >>> pizza_night = Weekdays[4] >>> pixel_colour = Colours.blue The values are constants that can be compared only with other values from the same enumeration, but can be coerced to simple strings matching the original arguments to Enum(). The design is based in part on Zoran Isailovski's recipe, "First Class Enums in Python" in the ASPN Python Cookbook . """ -- \ "I bought some batteries, but they weren't included; so I had | `\ to buy them again." -- Steven Wright | _o__) | Ben Finney From ggrp1.20.martineau at dfgh.net Thu Nov 17 15:29:10 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 17 Nov 2005 12:29:10 -0800 Subject: Default method arguments References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <867jb9r6qr.fsf@bhuda.mired.org> <1132087833.419559.122310@g43g2000cwa.googlegroups.com> <86u0edpq5v.fsf@bhuda.mired.org> Message-ID: <1132259350.192573.212030@f14g2000cwb.googlegroups.com> Mike Meyer wrote, in part:: > "Gregory Petrosyan" writes: > ... > > 2) Is 'foo.s = n' a correct solution? It seems to be a little more > > elegant. (I tested it, and it worked well) > > It's basically the same solution. You're replacing binding a variable > with mutating an object bound to a name in an outer scope. In one case > the container is named s and is a list that you're setting an element > of. In the other case, the container is named foo and is an object > that you're setting an attribute on. Well, perhaps the same in the sense of name binding, but there's a subtle difference in replacing the 's = [n]' with 'foo.s = n'. Namely that in the former case (with the essay's original code) a separate container is created when foo() is first called and is what is used in subsequent calls to the function returned. Whereas in the latter case where the foo object itself is used as the container, there's only a single container used by all returned objects -- which would cause problems if you try accumulating two or more different totals simultaneously. Here's a very contrived test case which illustrates the point I'm trying to make: def foo(n): foo.s = n def bar(i): foo.s += i return foo.s return bar a1 = foo(0) a2 = foo(0) print "before a1(0):", a1(0) print "before a2(0):", a2(0) a1(1) a2(1) print "after a1(0):", a1(0) print "after a2(0):", a2(0) >>>> outputs before a1(0): 0 before a2(0): 0 after a1(0): 2 after a2(0): 2 Notice that it even though each was only incremented by 1 once, they interacted, and show the effects of two calls. This doesn't happen in in Paul Graham's version, where the two 'after' calls would correctly retrun a value of 1. -Martin From strombrg at dcs.nac.uci.edu Tue Nov 29 15:29:30 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Tue, 29 Nov 2005 20:29:30 GMT Subject: CGI question References: Message-ID: On Sat, 26 Nov 2005 13:26:11 +0100, Fredrik Lundh wrote: > Dan Stromberg wrote: > >> What's the best way of converting this: >> >> 'hide\\?http://www.dedasys.com/articles/programming_language_economics.html\x012005-07-20 >> 14:48' >> >> ...to something easily usable in a python CGI script? > > easily usable for what purpose? > > if you want to extract the URL that seems to be hidden in that string, > something like: > > url, junk = text.split("\x01", 1) > junk, url = url.split("\\?", 1) > > should work. > > This is great, but is there no standard python module for taking apart command line arguments to a CGI script? I'm not eager to reinvent the wheel, at least not on this project :) From grisha at apache.org Wed Nov 23 10:30:23 2005 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Wed, 23 Nov 2005 10:30:23 -0500 Subject: ANNOUNCE: Mod_python 3.2.5 Beta Message-ID: <20051123102324.A63699@grisha.dyndns.org> The Apache Software Foundation and The Apache HTTP Server Project are pleased to announce the 3.2.5 Beta release mod_python. Version 3.2.5b of mod_python features several new functions and attributes providing better access to apache internals, file-based sessions and other session improvements, as well as many bug fixes and various performance and security improvements. A detailed description of the changes is available in Appendix A of the mod_python manual, also available here: http://www.modpython.org/live/mod_python-3.2.5b/doc-html/node97.html Beta releases are NOT considered stable and usually contain bugs. This release is intended to solicit widespread testing of the code. We strongly recommend that you try out your existing applications and experiment with new features in a non-production environment using this version and report any problems you may encounter so that they can be addressed before the final release. Preferred method of reporting problems is the mod_python user list mod_python at modpython.org. Mod_python 3.2.5b is available for download from: http://httpd.apache.org/modules/python-download.cgi For more information about mod_python visit http://www.modpython.org/ Regards, Grisha Trubetskoy and the Apache mod_python team. From stefan.arentz at gmail.com Thu Nov 3 07:36:43 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 03 Nov 2005 13:36:43 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> Message-ID: <87psphkiw4.fsf@keizer.soze.com> Antoon Pardon writes: ... > >> No matter wat the OO model is, I don't think the following code > >> exhibits sane behaviour: > >> > >> class A: > >> a = 1 > >> > >> b = A() > >> b.a += 2 > >> print b.a > >> print A.a > >> > >> Which results in > >> > >> 3 > >> 1 > > > > I find it confusing at first, but I do understand what happens :-) > > I understand what happens too, that doesn't make it sane behaviour. > > > But really, what should be done different here? > > I don't care what should be different. But a line with only one > referent to an object in it, shouldn't be referring to two different > objects. It doesn't. > In the line: b.a += 2, the b.a should be refering to the class variable > or the object variable but not both. So either it could raise an > attribute error or add two to the class variable. It does exactly what you say. It adds 2 to the a *instance variable* of the object instance in 'b'. It doesn't touch the *class variable* A.a which is still 1. S. From roccomoretti at hotpop.com Wed Nov 2 16:29:50 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 02 Nov 2005 15:29:50 -0600 Subject: Suggestion for (re)try statement In-Reply-To: References: Message-ID: Sori Schwimmer wrote: > 0) Sorry, I don't know how to post a reply in the same > thread. Usually it is simply hitting the "Reply" button/link/key combination on your mail/news reader when the post you want to reply to in view. (If you want reply to multiple people, you can always reply to the original post, or reply to one, and just treat the topics from all of them.) > 2) Rocco Morreti wrote: First off, let me say that my message wasn't meant to scare you off - it was constructive criticism, appraising you of what would be necessary if you actually want the construct in the language. If you're just shooting the breeze/navel gazing, I apologize for harshing your cool. >>What is so repugnant about the equivalent, currently >>valid way of writing it? > > Nothing "repugnant". "Repugnant" was probably too strong a word. The point I was trying to make was: If you want such a construct added to the language, you need to justify all the hassle & effort of introducing the new syntax. Given that there is a way to accomplish the same thing now, you would need to show that your way is not just as good, but better than the current way. > It's all about convenience, not about > getting to bare bone equivalents. Nothing wrong with convenience - you just have to show that the convenience would be used often enough to justify the hassle. It'd be awfully convenient to have a passenger jet parked in your garage - but you probably wouldn't use it frequently enough to justify the expense of maintaining, fueling, and licensing it. >> And remember - your goal isn't ultimately to >> convince me or someother >> person on comp.lang.python, it's to convince Guido > > I'm not trying to convince anybody. In the democratic > state-of-mind in which I live, the idea will be taken > in consideration if it is found useful by many, not by > one, even if the one is the almighty Guido. My comment made with the assumption that you were trying to actively promote the construct, rather than floating it as a trial balloon. I was aiming at keeping you from getting annoyed later on when your petition with hundreds of signatures gets shot down by Guido. Despite your state-of-mind, in practicality, Python is not a democracy - language constructs live or die by the will of Guido. If you actually want the construct in the language, a comp.lang.python plebiscite isn't going to do it - you'll need to convince the BDFL that it's a good idea. Now, Guido isn't totally ambivalent to the masses - if a large number of people are for it, there's a good chance Guido will be for it too. But you're not aiming for a popularity contest - what'll convince people (including Guido) is good arguments as to *why this construct is better than what we have now,* and *why it will be worth the hassle of implementing and maintaining it*. From apardon at forel.vub.ac.be Mon Nov 28 05:35:40 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2005 10:35:40 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> Message-ID: Op 2005-11-25, EP schreef : > > What is the philosophy? I'm not the one to answer that, > but I do use "import this" for reference, and it seems to > answer some of the points in this thread: > >>>> import this > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea -- let's do more of those! >>>> No, it doesn't answer anything. My impression is that the Zen of Python gets used a lot by the python people like the bible is used by the christions: You can always find a verse/Koan that supports your view. If someone comes with a pratical proposal that breaks a rule, the proponents will cite: "practical beats purity" and the opponents will cite: "Special cases aren't special enough to break the rules: And each will be convince that his view is the pythonic one. I'm even of the impression that what is considered pythonic or not is more related to who proposes it that to what the proposal is and that after one has so decided the right rules are selected to defend that decision. -- Antoon Pardon From amfr.org at gmail.com Mon Nov 21 18:57:03 2005 From: amfr.org at gmail.com (amfr) Date: 21 Nov 2005 15:57:03 -0800 Subject: Command line In-Reply-To: <4382586f.411203839@news.oz.net> References: <1132516802.045403.177660@z14g2000cwz.googlegroups.com> <4382586f.411203839@news.oz.net> Message-ID: <1132617423.411302.55190@o13g2000cwo.googlegroups.com> Thanks for your help. Another question, is there an built in md5/sha1 function in python? From simon.brunning at gmail.com Tue Nov 15 04:42:06 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 15 Nov 2005 09:42:06 +0000 Subject: Is Python worth it?? In-Reply-To: <20051114225249.89689.qmail@web35901.mail.mud.yahoo.com> References: <20051114225249.89689.qmail@web35901.mail.mud.yahoo.com> Message-ID: <8c7f10c60511150142r3d32e3e8j@mail.gmail.com> On 14/11/05, john boy wrote: > I have started out trying to learn Python for my first programming language. > I am starting off with the book "how to think like a computer scientist." > I spend about 4-5 hrs a day trying to learn this stuff. It is certainly no > easy task. I've been at it for about 1-2 weeks now and have a very > elementary picture of how Python works. I am teaching myself from home and > only recieve help from this forum. Can anybody give me a timeframe as to > how long it usually takes to pick something like this up, so I can maybe > figure out a way to pace myself? I can dedicate a good amount of time to it > everyday. Any advice on what is the best way to learn Python? I am a > fairly educated individual with a natural sciences degree (forestry), so I > also have a decent math background. Are there any constraints > mathematically or logic "wise" that would prevent me from building a firm > grasp of this language? Keep at it. Everyone is different, so don't worry about how long it takes you vs. how long others might take. If you have no programming background, there's a lot to learn. Using Python is a good choice, I think, 'cos it gets a lot of extranious crud that many other languages insist on out of your way, but there's still a lot to learn. The best way to learn? Go through the tutorials - but if you get an idea for a mini-project of your own, don't be afraid to dive off and give it a go. Try to solve you own problems for a while, 'cos that's a valuable skill, but don't get to the point of frustration. Ask for help here or on the tutor mailing list[1]. And have fun. [1] http://mail.python.org/mailman/listinfo/tutor -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From broek at cc.umanitoba.ca Tue Nov 15 01:40:00 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 15 Nov 2005 00:40:00 -0600 Subject: compare list In-Reply-To: <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> Message-ID: <437982C0.5090702@cc.umanitoba.ca> Ben Bush said unto the world upon 2005-11-14 23:20: > > On 11/14/05, Brian van den Broek wrote: > >>Ben Bush said unto the world upon 2005-11-14 05:51: >> >>>I have four lists: >>>lisA=[1,2,3,4,5,6,9] >>>lisB=[1,6,5] >>>lisC=[5,6,3] >>>lisD=[11,14,12,15] >>>how can I write a function to compare lisB, lisC and lisD with lisA, if >> >>they >> >>>share two continuous elements (the order does not matter), then return >> >>1, >> >>>otherwise return 0. For example, lisA, lisB and lisC have 5,6 or 6,5 so >>>>>def list_common_continuity_comp(list1, list2): >> >>for item in list1: >>if item in list2: >>if item + 1 in list1 and item + 1 in list2: >>return True >>return False >> > what does the following code mean? > if item in list2: > if item + 1 in list1 and item + 1 in list2: > Hey Ben, first, as expected, the other two answers you received are better. :-) Sets are much better optimized for things like membership testing than are lists. I'm not competent to explain why; indeed, I keep overlooking them myself :-( Unfortunately, the indents got screwed up along the way. But the part of my code you asked about was: for item in list1: if item in list2: if item + 1 in list1 and item + 1 in list2: return True In some detail: Consider each item in list1 in turn. If the item isn't in list2, move on, as there is no chance of it meeting your test. If the item is in list2, then it is pointful to check if your test is met. Given that you wanted consecutive numbers, the 'if item + 1 in list1 and item + 1 in list2' condition checks if both lists (which contain item if we've gone this far) also contain item + 1. If they do, you wanted the function to return 1 (I changed it to True as more idiomatic). After my for loop is a return False which we will only hit if the condition you wanted to test was never satisfied. Does that clarify it? Finally, your response to Alex would have been much more useful if you'd quoted the error rather than just asserting that you got an error :-) Best, Brian vdB From jaco at neottia.net Sun Nov 13 16:48:47 2005 From: jaco at neottia.net (Eric Jacoboni) Date: Sun, 13 Nov 2005 22:48:47 +0100 Subject: strip not working on strings? References: <1131916607.467166.207550@g14g2000cwa.googlegroups.com> Message-ID: In article <1131916607.467166.207550 at g14g2000cwa.googlegroups.com>, dan.j.weber at gmail.com wrote: > I'm using Python 2.3.5 and when I type the following in the interactive > prompt I see that strip() is not working as advertised: > > >>>s = 'p p:p' > >>>s.strip(' :') > 'p p:p' > > Is this just me or does it not work? I want to get rid of all ' ' and > ':' in the string. I've checked the doc and from what I can tell this > is what strip() is supposed to do. In /my/ docs, s.strip return a copy of s where all /leading/ and /heading/ spaces are removed. s.strip(x) does the same but removing chars of x. So, what you're asking for by s.strip(' :') is "remove heading or leading space or ':' chars", /not/ "remove or leading or ':' chars". If you want to get rid of ' ' and ':' anywhere in s, i think that string.maketrans and s.translate will do the job: >>> import string >>> s = 'p p:p' >>> ident = string.maketrans('', '') >>> s.translate(ident,' :') 'ppp' -- Jaco From jstroud at mbi.ucla.edu Wed Nov 2 16:55:14 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 2 Nov 2005 13:55:14 -0800 Subject: Hexadecimal Conversion in Python In-Reply-To: <1130964825.322352.138330@f14g2000cwb.googlegroups.com> References: <1130963306.183112.3720@g49g2000cwa.googlegroups.com> <1130964825.322352.138330@f14g2000cwb.googlegroups.com> Message-ID: <200511021355.14354.jstroud@mbi.ucla.edu> On Wednesday 02 November 2005 12:53, DaBeef wrote: > I have been coding for 5 years. This is a proprietary protocol, so it > is difficult converting. I did this in java but was just able to > convert a stream. I looked through the Python library, I am more or > less getting backa string represented as a "...." So now I want to > convert it to all the hexa, bin until I see a match and can then work > teh rest of my program Its great that you are learning python, but it seems you are confused about how it works, so you are not making sense to a lot of people. Hex conversion can be done in a lot of ways. You should look into "struct" as others have suggested, which might be a more resource effecient (less processor cycles) choice and also give you your data as numerical types. If you have managed to get to the point of having a string that looks like this: '\xcb\xdb\xbe\xef' Then the simplest thing for you to do (least amount of learning) at this point might be to look at "decode" and "encode" for example >>> hex_rep = '\xcb\xdb\xbe\xef'.encode('hex') >>> print hex_rep 'cbdbbeef' Also, you might annoy (read: 'you have annoyed') a lot of people by saying that python has a "llimited" library. Not only are you incorrect, but you made a typo. You will do well to learn as much of the python library as you can, but it will take some time. You will also do well to avoid typos and grammatical errors in your communications. Also, you need to answer Fredrik's question. Let me restate it. What do you mean by '....'? This encodes in hex to '2e2e2e2e'. Is this the cipher text you were expecting? If so, your company may want to re-think its encryption algorithm. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mwm at mired.org Fri Nov 25 18:21:21 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 25 Nov 2005 18:21:21 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> Message-ID: <86lkzcgvpq.fsf@bhuda.mired.org> Christoph Zwerschke writes: > Mike Meyer wrote: > > The mutability - or immutability - of an object is irrelevant to > > the question of whether or not they can be a dictionary key/set > > element. The critical property is that they are hashable. > > *Most* immutable builtin types are hashable, and no builtin > > mutable types are hashable, which deserves a mention. > I think the problem we are facing is that you must distinguish between > hashable/mutable *types* and hashable/mutable objects. You can have > *types* like tuple which are hashable/immutable themselves, but can > have *instances* that are mutable and not hashable, such as ([]). I think you're trying to tweak the wrong definition. Types are immutable if their instances are immutable. The problem is that python defines the value of container objects to depend on their contents, so the value of a container object can change even if the container itself can't change. Tuples can't change - a tuple will always refer to the objects it refers to when created. However, those objects can change, which changes the value of the tuple without changing the tuple. So whether or not a tuple containing a mutable object is immutable depends on whether you define a immutable as "the object can't change" or "the objects value can't change". > For the built-in types I think objects are hashable if and only if > they are immutable (not 100% sure, but can you give a > counterexample?). That's why I got back to talk about mutability > first. But I agree one should also explain the problem of non-built-in > types. If you define immutable as "the object doesn't change", then the counterexample is the one you misspelled above: ([],). If you define immutable as "the value of the object can't change", then I don't have a counterexample. > class mylist(list): > pass > > This class definitely has a __hash__ method. But instances of this > class are not hashable. Do you think it's really necessary to specify "has a __hash__ method that returns a value", as opposed to just "has a __hash__ method"? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From johnjsal at NOSPAMgmail.com Wed Nov 2 16:19:40 2005 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 02 Nov 2005 21:19:40 GMT Subject: Python for .NET and IronPython Message-ID: Hi all. I'm currently learning C#, and I'm also interested in learning Python (all of this just for fun, mind you), so it seems like a decent idea to want to integrate the two. But I don't quite understand the difference between these two Python implementations and I was hoping someone could explain. Does either one require learning something different than the core Python language? With IronPython, would you actually be writing .NET code? I know Python for .NET is treated as a true language in the CLR, but I don't quite grasp what all this means for each language, and what the learning process for either language would be like as a result. Thanks, John From paul at boddie.org-dot-uk.no-spam.invalid Wed Nov 30 14:52:25 2005 From: paul at boddie.org-dot-uk.no-spam.invalid (Paul Boddie) Date: 30 Nov 2005 19:52:25 GMT Subject: python speed References: Message-ID: <438e02f9$0$34180$892e7fe2@authen.yellow.readfreenews.net> Steven Bethard wrote: > David Rasmussen wrote: > Faster than assembly? LOL... :) > Faster than physics? ;-) > I think the claim goes something along the lines of "assembly is so hard > to get right that if you can automatically generate it from a HLL, not > only will it be more likely to be correct, it will be more likely to be > fast because the code generator can provide the appropriate optimizations". > I think this is just a restatement of existing motivations for using high-level languages and compilers. My impression is that PyPy takes inspiration from work which showed that run-time knowledge can sometimes produce code that is better optimised than that produced by a compiler. That said, when everyone starts showing off their favourite benchmarks, it might be more interesting not to parade some festival of arithmetic yet again. Where more recent versions of the Java virtual machines have improved is in their handling of object memory allocation, amongst other things, and merely scoffing that Java is slow (by pulling specific/specialised extension packages out of the hat) fails to acknowledge the potential for similar improvements (and others) in Python, especially where programs involving plain objects - as opposed to numbers, and where no conveniently available and wrapped C/C++ package exists for the task - are concerned. Paul From gregory.petrosyan at gmail.com Tue Nov 15 11:03:26 2005 From: gregory.petrosyan at gmail.com (gregory.petrosyan at gmail.com) Date: 15 Nov 2005 08:03:26 -0800 Subject: Default method arguments Message-ID: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> Hello everybody! I have little problem: class A: def __init__(self, n): self.data = n def f(self, x = ????) print x All I want is to make self.data the default argument for self.f(). (I want to use 'A' class as following : myA = A(5) myA.f() and get printed '5' as a result.) From bokr at oz.net Tue Nov 8 17:35:45 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 08 Nov 2005 22:35:45 GMT Subject: How to convert a number to hex number? References: <1131442115.025438.326670@g49g2000cwa.googlegroups.com> <1131464101.546746.107110@g47g2000cwa.googlegroups.com> <7xmzkfrum1.fsf@ruckus.brouhaha.com> Message-ID: <43712759.482516031@news.oz.net> On 08 Nov 2005 08:07:34 -0800, Paul Rubin wrote: >"dcrespo" writes: >> >>>hex(255)[2:] >> 'ff' > >'%x'%255 is preferable since the format of hex() output can vary. Try hex(33**33). Not to mention (#@%*!-pletive deleted ;-) >>> hex(-255)[2:] 'xff' >>> hex(-255) '-0xff' >>> hex(-255&0xff) '0x1' Regards, Bengt Richter From DavidRushby at gmail.com Fri Nov 4 16:45:30 2005 From: DavidRushby at gmail.com (David Rushby) Date: 4 Nov 2005 13:45:30 -0800 Subject: python gc performance in large apps References: <43594BD5.7050104@u20.org> Message-ID: <1131140730.498779.253800@g44g2000cwa.googlegroups.com> Robby Dermody wrote: > I have not yet run the director with COUNT_ALLOCS yet, due to a > problem dynamically loading in the kinterbasdb (Firebird SQL > interface) module. What're the specifics of the loading problem with kinterbasdb? AFAIK, kinterbasdb itself runs fine in a debug build of Python. The egenix mx extensions, which kinterbasdb uses for date/time handling unless the user specifies otherwise, do not. I've conferred with MAL on this topic and was told that egenix "doesn't support" running the extensions in a debug build. I made my own modifications to the mx extensions so that they work properly in a debug build; I could post the modified version somewhere for download if you're interested. From bokr at oz.net Tue Nov 8 05:13:42 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 08 Nov 2005 10:13:42 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> Message-ID: <43707878.437747677@news.oz.net> On 8 Nov 2005 01:43:43 -0800, "pinkfloydhomer at gmail.com" wrote: >But if lst[42]["pos"] happens to hold an integer value, then > >a = lst[42]["pos"] > >will _copy_ that integer value into 'a', right? Changing 'a' will not >change the value at lst[42]["pos"] Right, but try an example: >>> lst = range(42)+[{'pos':123}]+range(43,50) >>> lst [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 2 6, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, {'pos': 123}, 43, 44, 45, 46, 47, 48, 49] >>> lst[41:44] [41, {'pos': 123}, 43] >>> lst[42] {'pos': 123} >>> lst[42]['pos'] 123 >>> a = lst[42]['pos'] >>> a 123 >>> lst[42]['pos'] 123 >>> id(lst[42]['pos']) 49421860 >>> id(a) 49421860 IOW, a is now an alias for the same 123 immutable integer object as is referred to by the 'pos' key in the dict which is the 43rd element (index 42) of lst. Regards, Bengt Richter From ejensen at visi.com Wed Nov 16 08:51:35 2005 From: ejensen at visi.com (Ed Jensen) Date: Wed, 16 Nov 2005 13:51:35 -0000 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <437a5980$0$18815$636a55ce@news.free.fr> <437A9320.7040308@REMOVEMEcyber.com.au> Message-ID: <11nmeb7ma7nnuba@corp.supernews.com> Steven D'Aprano wrote: > I'm not sure if that is meant to be a rhetorical > question or not, but something of the order of 95% of > all software written is never distributed to others, > and so copyright or the lack of copyright is not an issue. Can you cite your source(s) for this information? From sybrenUSE at YOURthirdtower.com.imagination Sat Nov 5 16:05:29 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 5 Nov 2005 22:05:29 +0100 Subject: starting an X11 session from Python References: <848bf.3759$HB.1191@dukeread12> Message-ID: Philippe C. Martin enlightened us with: > Have there been any attempt to do so, and is there any source out > there that could help me get started ? What's stopping you from using system(), exec() or the likes to start "startx", "xinit" or simply "X"? 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 desparn at wtf.com Wed Nov 30 13:21:08 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Wed, 30 Nov 2005 13:21:08 -0500 Subject: Why I need to declare import as global in function References: <1133184618.689014.85850@z14g2000cwz.googlegroups.com> <1133265470.979764.157620@g14g2000cwa.googlegroups.com> <1133341125.906462.321320@z14g2000cwz.googlegroups.com> Message-ID: Dennis Lee Bieber wrote in news:tmmro191j33lbep1i04pn3a2lcsll9fgt6 at 4ax.com: > On 30 Nov 2005 00:58:45 -0800, didier.doussaud at gmail.com > declaimed the following in comp.lang.python: > >> yes I have imported math in the file I want to use it. But the >> imported module "math" is not visible in function without a >> global instruction. >> > The code you just posted shows it, yes... My reading of an > earlier > message seemed to imply you had a nested import chain with the > "import math" at the wrong level... Something like: > > #file 1 > execfile("file 2") > > #file 2 > import math > import file_3 > > #file_3 > print math.pi > >> But the solutions already proposed seems to work file for my >> sample program. I will try on my project soon :) > > Looking at the documentation for "execfile", I can see > /how/ the > problem occurs -- but can't determine if this can be considered > "expected". > > -=-=-=-=-=-=- > execfile( filename[, globals[, locals]]) > > This function is similar to the exec statement, but parses a > file instead of a string. It is different from the import > statement in that it does not use the module administration -- > it reads the file unconditionally and does not create a new > module.2.2 -=-=-=-=-=-=- > > I'm guessing that the intent was only that "file 1" not > become an > entry on the module list, but it seems to be applying "...not > create a new module" recursively to the imported "math"... Maybe > an expert with the Python byte-code can verify. My hypothesis is > something on the order of: > Outer (file level) references to math (math.pi) are being > handled > during the byte-code compilation phase of execfile, so even if > "math" isn't in the module list, it is still in local scope for > the outer math.pi... > > Inner (function) references to math become dynamic look-ups > evaluated at function execution; at that point math is not in > scope and is not in the module list. > > Interestingly, I note that is the file calling execfile has > imported > math (so math is in the module list), the called file works... > > #no import in run > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python > run.py in module: > Traceback (most recent call last): > File "run.py", line 5, in ? > run_ut("ut_00.py") > File "run.py", line 3, in run_ut > execfile(test) > File "ut_00.py", line 8, in ? > f() > File "ut_00.py", line 5, in f > print "in function: \t %s" % math > NameError: global name 'math' is not defined > > #import is in run > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python > run.py > > in module: > in function: > This may be saying what you said, but it seems to depend on where the import occurs: # File: runt2.py def Bobo(): import math execfile( "ut_00.py" ) b = Bobo() >runt2 First access : 3.14159265359 Second access : Traceback (most recent call last): File "D:\pyWork\test\runt2.py", line 5, in ? b = Bobo() File "D:\pyWork\test\runt2.py", line 3, in Bobo execfile( "ut_00.py" ) File "ut_00.py", line 10, in ? f() File "ut_00.py", line 6, in f print "\t",math.pi # ERROR NameError: global name 'math' is not defined # File: runt.py import math def Bobo(): execfile( "ut_00.py" ) b = Bobo() >runt First access : 3.14159265359 Second access : 3.14159265359 So the import at the module level of the caller works, but an import at the function level of the caller doesn't. I don't see why the namespace would be significantly different by the time execfile is executed, though it apparently is. -- rzed From mjakowlew at gmail.com Thu Nov 3 12:04:30 2005 From: mjakowlew at gmail.com (mjakowlew) Date: 3 Nov 2005 09:04:30 -0800 Subject: Filepath string manipulation help References: <1130959950.485233.230230@z14g2000cwz.googlegroups.com> <1131032213.559554.163730@g14g2000cwa.googlegroups.com> Message-ID: <1131037470.042070.316820@g44g2000cwa.googlegroups.com> I got the "IE Fix" working, here's the code: ____________________________ path = r'c:\here\there\files\file.ext' i=len(path) j=0 size=len(path) while i: i=i-1 if path[i]== '\\': j=i+1 break filename = path[j:size] print "FILENAME: %s" %(filename) _______________________________ Most importantly this works on my Zope webserver. Thanks again, mjakowlew From martin at v.loewis.de Tue Nov 22 20:33:49 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Nov 2005 02:33:49 +0100 Subject: Built windows installers and Cygwin In-Reply-To: <1132704468.839738.300190@g43g2000cwa.googlegroups.com> References: <1132704468.839738.300190@g43g2000cwa.googlegroups.com> Message-ID: <4383c6fd$0$28830$9b622d9e@news.freenet.de> SPE - Stani's Python Editor wrote: > Is there any way for these kind of installers to be used with cygwin. No. The bdist_wininst packages link against Microsoft's C library; the cygwin Python against Cygwin's. If there is no native code in the package, it would be possible to *use* them - installing them still won't work. To use them, unzip them, and spread the files as you see fit. Regards, Martin From Serge.Orlov at gmail.com Thu Nov 17 03:31:24 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Nov 2005 00:31:24 -0800 Subject: pySonic - writing a sample to a file In-Reply-To: <437ad168$1@mail.netspeed.com.au> References: <437ad168$1@mail.netspeed.com.au> Message-ID: <1132216284.796089.236890@o13g2000cwo.googlegroups.com> netspeed.com.au wrote: > Hi all: > > Hopefully a simple question. I have been putting together an application > using pySonic. I find the documentaion fine with plenty of examples but I > cant see how to save a sample (or any recorded audio) to a file. > > Am I missing something obvious? Python comes with read/write support for several audio file formats: http://docs.python.org/lib/mmedia.html perhaps you can get raw stream from pySonic and save it using python stdlib module? From bearophileHUGS at lycos.com Tue Nov 1 16:19:15 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Nov 2005 13:19:15 -0800 Subject: Python's website does a great disservice to the language In-Reply-To: References: Message-ID: <1130879955.704130.183770@f14g2000cwb.googlegroups.com> CppNewB>and maybe a readable default font is in order.< That font looks fine to me, maybe there's a problem in the default font of your browser, you can probably fix your problem... Bye, bearophile From cfajohnson at gmail.com Fri Nov 4 20:55:48 2005 From: cfajohnson at gmail.com (Chris F.A. Johnson) Date: Fri, 4 Nov 2005 20:55:48 -0500 Subject: Getting Python Accepted in my Organisation References: <_7naf.22662$uB4.10329@fe06.highwinds-media.phx> <1131023021.643251.113330@f14g2000cwb.googlegroups.com> <1h5fwpi.1wjmgm417fbm8dN%aleax@mail.comcast.net> <1131033712.535402.193520@z14g2000cwz.googlegroups.com> <1h5grc5.1f520xizhqvucN%aleax@mail.comcast.net> <1131128383.049466.179370@f14g2000cwb.googlegroups.com> Message-ID: <42gt33-cst.ln1@rogers.com> On 2005-11-04, bonono at gmail.com wrote: > > Alex Martelli wrote: >> It would still be easier to respond to your posts if you didn't >> top-post, though (i.e., if you didn't put your comments BEFORE what >> you're commenting on -- that puts the "conversation" in a weirdly >> distorted order, unless one give up on quoting what you're commenting >> on, or invests a lot of time and energy in editing...;-). >> > oops. I developed this habit because I found I like to read it this > way. As I usually would read just the first few lines to see if I > want to read on. top post serve me well for this purpose. And I > assume other may also find my stuff not worth reading and skip quick > so why force them to scroll all the way down? If I want to read that way, I just tell my newsreader not to display the quoted material (actually it displays the first line of each block). Or I press TAB to jump to the next original material. > I would only do in-line response type when there is a need for > specific response in context. If there's not, why would you quote anything? -- Chris F.A. Johnson | Author: | Shell Scripting Recipes: Any code in this post is released | A Problem-Solution Approach, under the GNU General Public Licence | 2005, Apress From MrJean1 at gmail.com Sat Nov 19 11:09:33 2005 From: MrJean1 at gmail.com (MrJean1) Date: 19 Nov 2005 08:09:33 -0800 Subject: what happens when the file begin read is too big for all lines to be read with "readlines()" In-Reply-To: References: Message-ID: <1132416573.900778.181320@g49g2000cwa.googlegroups.com> Just try it, it is not that hard ... ;-) /Jean Brouwers PS) Here is what happens on Linux: $ limit vmemory 10000 $ python ... >>> s = file().readlines() Traceback (most recent call last): File "", line 1 in ? MemoryError >>> From iainking at gmail.com Mon Nov 7 10:49:10 2005 From: iainking at gmail.com (Iain King) Date: 7 Nov 2005 07:49:10 -0800 Subject: need help extracting data from a text file In-Reply-To: <1131375863.977379.120620@f14g2000cwb.googlegroups.com> References: <1131375863.977379.120620@f14g2000cwb.googlegroups.com> Message-ID: <1131378550.887946.127680@g43g2000cwa.googlegroups.com> nephish at xit.net wrote: > Hey there, > i have a text file with a bunch of values scattered throughout it. > i am needing to pull out a value that is in parenthesis right after a > certain word, > like the first time the word 'foo' is found, retrieve the values in the > next set of parenthesis (bar) and it would return 'bar' > > i think i can use re to do this, but is there some easier way? > thanks well, you can use string.find with offsets, but an re is probably a cleaner way to go. I'm not sure which way is faster - it'll depend on how many times you're searching compared to the overhead of setting up an re. start = textfile.find("foo(") + 4 # 4 being how long 'foo(' is end = textfile.find(")", start) value = textfile[start:end] Iain From mwm at mired.org Wed Nov 9 12:40:41 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 09 Nov 2005 12:40:41 -0500 Subject: append to non-existing list References: <4371EFBC.1030502@sitasoftware.lu> <4371FA57.40206@sitasoftware.lu> <1131549196.831764.104480@g47g2000cwa.googlegroups.com> Message-ID: <86wtjh90ti.fsf@bhuda.mired.org> "bonono at gmail.com" writes: > Fredrik Lundh wrote: >> x = "10" + 20 # should this be 30 or 1020 or "1020" or ...? >> > I think Perl handles this case pretty well and sane. > > In fact, this strict but dynamic type checking is quite painful to work > with, especially the new decimal class. > > I can do a : > > decimal + int > > but not > > decimal + float > > But then when I use some built-in math functions, it can convert > decimal to float and return a float which then cannot be operate with > another decimal. Interesting probllem. Decimal + float can't return a decimal - we don't do implicit conversion from float to decimal, because there's no obvious correct conversion. So decimal.__add__ returns NotImplemented, which I believe is the correct thing to do. IIRC, this defers the operation to the float type. Float doesn't handle implicit conversion to anything but but builtin types. In particular, it doesn't check to see if the object beinng added has a __float__ method, and invoke that to do the conversion if it does. This looks like a bug. Either decimal.__add__ should return a float in these circumstances (not pretty), or float should check for the __float__ attribute and deal with it. On the other hand, the secton in the manual says that in Python 3.0 coercion won't be supported, so this may be a reflection of how things are going to be in the future. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From christopherlmarshall at yahoo.com Fri Nov 11 10:41:58 2005 From: christopherlmarshall at yahoo.com (christopherlmarshall at yahoo.com) Date: 11 Nov 2005 07:41:58 -0800 Subject: derived / base class name conflicts In-Reply-To: <1131676411.993022.63210@f14g2000cwb.googlegroups.com> References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> <1131676411.993022.63210@f14g2000cwb.googlegroups.com> Message-ID: <1131723718.846588.230740@g14g2000cwa.googlegroups.com> I see what you mean now. It would indeed be enlightening if I wanted to study the internals of Tkinter, and perhaps one day I will. From elbertlev at hotmail.com Sun Nov 20 22:30:01 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 20 Nov 2005 19:30:01 -0800 Subject: Aproximative string matching In-Reply-To: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> References: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> Message-ID: <1132543801.861940.146530@g43g2000cwa.googlegroups.com> This algorithm is called soundex. Here is one implementation example. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52213 here is another: http://effbot.org/librarybook/soundex.htm From Serge.Orlov at gmail.com Thu Nov 17 03:24:53 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Nov 2005 00:24:53 -0800 Subject: newbie - How do I import automatically? References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> Message-ID: <1132215893.522275.137350@z14g2000cwz.googlegroups.com> bobueland at yahoo.com wrote: > I also checked in command prompt, and there it works!, but not in IDLE. > And it's in IDLE that I work all the time. Can anything be done to get > it to work there? According to command line help (run C:\Python24\Lib\idlelib>idle.py -h ) "idle -s" is what you're looking for. From steve at REMOVETHIScyber.com.au Wed Nov 16 16:35:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 17 Nov 2005 08:35:19 +1100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: On Wed, 16 Nov 2005 09:06:01 -0500, Rick Wotnaz wrote: [cutting to the important bit] >> except TypeError, msg: >> if msg == "iteration over non-sequence": >> # handle non-iterable case > Does this in fact work on your system? On mine (2.4.1 (#65, Mar 30 > 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]), it doesn't seem to. Dammit, that will teach me not to test my code before posting. No it doesn't: msg is an object of type exceptions.TypeError. The easy fix is to just coerce it to a string: if str(msg) == "iteration over non-sequence": which *does* work on my system. But perhaps a better way is to do this: # Create an instance of the exception you expect: try: for i in 0: pass except TypeError, ITER_OVER_NON_SEQ: pass # Now run your code... try: ...blah blah blah... except TypeError, msg if str(msg) == str(ITER_OVER_NON_SEQ): ...blah blah blah... This means we're no longer assuming what the error message will be, which makes our code a lot more future-proof and implementation-proof: if some version of Python changes the error string from "iteration over non-sequence" to something else, the code should continue to work correctly. -- Steven. From steve at holdenweb.com Fri Nov 18 08:55:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Nov 2005 13:55:44 +0000 Subject: mysql connection In-Reply-To: <1132317291.759987.307310@z14g2000cwz.googlegroups.com> References: <1132317291.759987.307310@z14g2000cwz.googlegroups.com> Message-ID: Python_it wrote: > How can I close more cursors at the END of my page, > after execute some scripts/functions. > > example: > I use one DB connection and 5 cursor actions. > > How can I close these connections/actions at the END of my page? > > > cursor.close() ==> 5 times?? > db.close() > If the five cursor actions are all performed on the same cursor then you only need one cursor.close(). Of course you may also need to delete (or otherwise make available for garbage collection) the results you have fetched with cursor.fetchall() and similar methods, but basically you just need to close each cursor you open once. 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 piet at cs.uu.nl Fri Nov 18 07:38:18 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 18 Nov 2005 13:38:18 +0100 Subject: Making a persistent HTTP connection References: <4378e5bb$0$2103$edfadb0f@dtext02.news.tele.dk> <3tsdvaFugk4lU2@uni-berlin.de> <1132005430.138843.206330@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "Alan Kennedy" (AK) wrote: >AK> http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.1 >AK> Some HTTP 1.0 clients supported persistent connections through the use >AK> of the non-standard "keep-alive" header. >>> And even if it works - what is the problem with connections being created? >AK> The URL above describes the benefits of persistent connections. The >AK> primary problem of the old style of one-request-per-connection is the >AK> creation of more sockets than are necessary. Maybe even more important (and just briefly mentioned in the section referred to above) is the latency introduced by the TCP setup and the slow startup phase of TCP's congestion control. This calculation is one of the exercises the students have to make in my networks class. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From cito at online.de Wed Nov 23 15:17:20 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 21:17:20 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <4384538f.541027426@news.oz.net> References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> Message-ID: Bengt Richter wrote: > I think the concept has converged to a replace-or-append-by-key ordering > of key:value items with methods approximately like a dict. We're now > into usability aspects such as syntactic sugar vs essential primitives, > and default behaviour vs selectable modes, ISTM. Yes, and we would be good if we do not stop the discussion at this point with nothing, but really create such a sophisticated implementation. Whether it will become popular or go to the standard lib some day is a completely different question. > E.g., it might be nice to have a mode that assumes d[key] is d.items()[k][1] when > key is an integer, and otherwise uses dict lookup, for cases where the use > case is just string dict keys. I also thought about that and I think PHP has that feature, but it's probably better to withstand the temptation to do that. It could lead to an awful confusion if the keys are integers. -- Christoph From bretthoerner at gmail.com Sun Nov 27 16:22:07 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 27 Nov 2005 13:22:07 -0800 Subject: Basic about Python class In-Reply-To: <1133123236.518007.123750@z14g2000cwz.googlegroups.com> References: <1133123236.518007.123750@z14g2000cwz.googlegroups.com> Message-ID: <1133126527.101751.315390@z14g2000cwz.googlegroups.com> Manuel11g wrote: > Hello, > I am a new programmer in Python and a need some help. Where can i get a > basic tutorial about Class. I don't know nothing about Object Oriented > Programming. Can you help me? http://diveintopython.org/object_oriented_framework/index.html From adam_goucher at hotmail.com Mon Nov 28 15:13:03 2005 From: adam_goucher at hotmail.com (adam) Date: 28 Nov 2005 12:13:03 -0800 Subject: FTP over TLS In-Reply-To: References: Message-ID: <1133208783.883436.262770@z14g2000cwz.googlegroups.com> I'm not 100% sure whether this answers your problem, but I would ignore getting a special TLS module and just concentrate on the ftp side of the protocol. If your connection to your ftp server must be in TLS, you could modify you socket module similar to how I have using this diff (against 2.3.4) as inspiration. http://www.ninjatactics.com/python/ssl-patch.txt This way, you only need to worry about one thing, not two. I suspect then your program flow would become 1) FTP client contacts server, sends command requesting secure connection. 2) Server responds by sending some sort of request for SSL 3) SSL your socket to the FTP server 4) Continue on your merry FTP way. -adam From bonono at gmail.com Sat Nov 19 00:54:14 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 18 Nov 2005 21:54:14 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132376750.855932.45470@g47g2000cwa.googlegroups.com> Message-ID: <1132379653.994033.206930@z14g2000cwz.googlegroups.com> Roy Smith wrote: > I think the list comprehensions are going to be the death of readable > python programs. Could be, but seems that someone in charge of the language wants readable python programs to die then as if list comprehension is not enough, there comes generator expression and now the formal acceptance of ternary operator. From shane.mitchell at gmail.com Fri Nov 25 08:58:23 2005 From: shane.mitchell at gmail.com (Shane) Date: 25 Nov 2005 05:58:23 -0800 Subject: Python book for a non-programmer In-Reply-To: References: <1132917813.690671.74960@o13g2000cwo.googlegroups.com> Message-ID: <1132927103.599897.48600@f14g2000cwb.googlegroups.com> Simon Brunning wrote: > I wouldn't have thought either of those was suitable for a > non-programmer. Great for cross-trainers, yes, but neither is intended > as a programming tutorial. I agree, I just thought that the other replies had provided more than enough resources to cover the basics, so I was just suggesting some material that could be used when the basics had been absorbed. Sorry about the confusion. From __peter__ at web.de Sat Nov 12 02:27:18 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Nov 2005 08:27:18 +0100 Subject: What do you use as symbols for Python ? References: <4372f88a$0$31833$636a15ce@news.free.fr> <1131653466.538695.69890@f14g2000cwb.googlegroups.com> <3tk628Fsqa6aU1@news.dfncis.de> Message-ID: Daniel Evers wrote: > I mixed this with the class-version and created a new class derived from > "str" for easier printing and added an iterator: > > --- > > class Enum: > class Type(str): > def __init__(self, name): > self.__name = name > def __str__(self): > return self.__name > > def __init__(self, *keys): > self.__keys = [] > for key in keys: > mytype = self.Type(key) > self.__dict__[key] = mytype > self.__keys.append(mytype) You should ditch what follows and instead add just def __iter__(self): return iter(self.__keys) > self.__index = -1 > self.__count = len(keys) > > def __iter__(self): > return self > > def next(self): > self.__index = self.__index + 1 > if (self.__index >= self.__count): > self.__index = -1 > raise StopIteration > return self.__keys[self.__index] > > friends = Enum("Eric", "Kyle", "Stan", "Kenny") > print "These are my friends:", > print ", ".join([kid for kid in friends]) > for kid in friends: > print kid, > if kid is friends.Kenny: > print "dead" > else: > print "alive" > --- To see the problem with your original code (an object serving as its own iterator) try the following example: friends = Enum("Eric", "Kyle", "Stan", "Kenny") if "Kyle" in friends: print "Hi Kyle" print "My friends:", ", ".join(friends) Only Stan and Kenny show up in the last print statement because the containment test did not iterate over all friends. Also, Type.__name seems redundant. Just class Type(str): pass should do the job. Peter From grante at visi.com Wed Nov 2 09:28:04 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 02 Nov 2005 14:28:04 -0000 Subject: About the Python Expert References: Message-ID: <11mhj7k46ce2m87@corp.supernews.com> On 2005-11-02, blahman (blah at blah.blah) <> wrote: > Hey, i didnt say i need an expert. wel i did... anyways, i m just > saying that Fan is not a good python programmer, he doesnt know enough > python to help those who have joined his group, They should have "joined a group" that _does_ contain people who know enough to help. Comp.lang.python, for example. Or the tutor mailing list. > i know its askin a lot, Yes it is. As apparently is spelling and punctuation. > and i m not askin for a private tutor, just someone(s), to pop > into the group, see the discussions and help the people. but > it is ur decision. There's _already_ a tutor mailing list and a general Python newsgroup -- both full of knowledgeable and helpful people. [Since I took a shot at this guy's spelling, there's _got_ to be a spelling error in my post, but I can't find it...] -- Grant Edwards grante Yow! I want a VEGETARIAN at BURRITO to go... with visi.com EXTRA MSG!! From me at privacy.net Tue Nov 29 22:18:10 2005 From: me at privacy.net (Dan Sommers) Date: Tue, 29 Nov 2005 22:18:10 -0500 Subject: Precision for equality of two floats? References: <1h6q8gv.16lvyv91k5bodeN%aleax@mail.comcast.net> <438c634e.224486674@news.oz.net> Message-ID: On Tue, 29 Nov 2005 14:31:46 GMT, bokr at oz.net (Bengt Richter) wrote: > On Mon, 28 Nov 2005 07:58:37 -0800, aleax at mail.comcast.net (Alex Martelli) wrote: >> Python's builtin floats compare for exact bit-by-bit equality -- no >> "threshold". You may want to look at the allclose function in the > Does "exact bit-by-bit" mean that > a = > a == > is 100% guaranteed? I.e., are there implementations where an > expression value might remain in 80-bit representation in the fpu and > be rounded to 64 bits for assignment to a and then not compare equal > because the second a is a rounded 64-bit value compared to the > regenerated 80-bit value? IIRC, if you consider NaNs, then a == a isn't even guaranteed if a might be a NaN, but that's probably Too Much Information. ;-) There have been (and may well still be) seemingly endless debates about this on comp.std.c (even without the possibility of NaNs, for similar reasons to the one you cite). I don't know if the Lisp and/or IEEE-754 crowds have worked all of this out. Regards, Dan -- Dan Sommers From jepler at unpythonic.net Mon Nov 28 10:11:15 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 28 Nov 2005 09:11:15 -0600 Subject: Data Structure in Python like STL Stack? In-Reply-To: <20051128150025.87368.qmail@web81502.mail.mud.yahoo.com> References: <20051128150025.87368.qmail@web81502.mail.mud.yahoo.com> Message-ID: <20051128151115.GA8570@unpythonic.net> What property of the STL stack is important to you? You can use a Python list as a stack. It has methods append() and pop() which run in amortized-constant-time. It can be tested for empty/nonempty in constant time too (if st: # stack is not empty). Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mediocre_person at hotmail.com Sat Nov 19 13:54:04 2005 From: mediocre_person at hotmail.com (Terrance N. Phillip) Date: Sat, 19 Nov 2005 12:54:04 -0600 Subject: Tkinter from Vis. BASIC In-Reply-To: <1132414886.146889.158170@g43g2000cwa.googlegroups.com> References: <437f3e9f$0$6383$a82e2bb9@reader.athenanews.com> <1132414886.146889.158170@g43g2000cwa.googlegroups.com> Message-ID: <437f745d$0$6391$a82e2bb9@reader.athenanews.com> jmdeschamps at gmail.com wrote: >>I want to do the same thing in Python/Tkinter: >> >> # Wait for network to recognize the workstation: >> while os.system("slist") != 0: >> self.notify["fg"] = randcolor() >> # how do I refresh label l3 at this point? >> time.sleep(3) > I know of an update_idletask() method, look it up in the tkinter doc to > see if that's what you need! > Thanks. I did a dir(label_object) and saw update() and update_idletasks(). updeate() seems to do the trick. From aleax at mail.comcast.net Thu Nov 24 14:47:46 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 24 Nov 2005 11:47:46 -0800 Subject: Why is dictionary.keys() a list and not a set? References: <8664qi3oef.fsf@bhuda.mired.org> <1h6iyik.86v3t3z8icd7N%aleax@mail.comcast.net> Message-ID: <1h6j466.1pwsjsevabcuxN%aleax@mail.comcast.net> Christoph Zwerschke wrote: > mathematics, everything is a set and set theory is the "theory of > everything". When I grew up pedagogues here in Germany even believed it > would be best if kids learn set theory and draw venn diagrams before An alternative theory, of course, is "God made the natural numbers; all else is the work of man" -- and that one is by a German, too (Kronecker, if I recall correctly). The hope to found all of mathematics on set theory was primarily a _British_ effort, as I see it (Russell and Whitehead), and failed a long time ago... I'm not sure what, if anything, a mathematician of today would propose as the foundational theory... perhaps modal logic, but I'm really just guessing, being, myself, an engineer rather than a mathematician (perhaps category theory? it's hard to say...). What, if anything, is the theoretically proper foundation, is of course a separate issue from where is it best to start _teaching_ maths... with geometry as the Greeks would have it, with arithmetic as in traditional schooling, or with sets as the modern pedagogues would have it. Me, I'm partial to arithmetic, but sets are just fine with me if they turn out to work better (I wonder if proper controlled studies have ever been done before revolutionizing the teaching of elementary maths, though...!). Again you see my engineer's bias: "whatever works"!-) But OO really requires a different mindset, particularly when operating under a regime of "mutable" objects. "A circle IS-AN ellipse" in Euclidean geometry... but inheriting Circle from Ellipse doesn't work in OO if the objects are changeable, since you can, e.g., change eccentricity in an Ellipse but not in a Circle... Alex From getkaizer at gmail.com Tue Nov 29 22:17:59 2005 From: getkaizer at gmail.com (Kaizer) Date: 29 Nov 2005 19:17:59 -0800 Subject: Newbie question: Tab key giving different output In-Reply-To: References: <1133155539.865554.216610@g14g2000cwa.googlegroups.com> Message-ID: <1133320679.286109.122130@g47g2000cwa.googlegroups.com> HI there Tim! I've been using your suggestion every since I've been having this issue. I realized exactly what you said...that a space works just as well.... Thanks! Kaizer. From roy at panix.com Tue Nov 15 21:59:44 2005 From: roy at panix.com (Roy Smith) Date: Tue, 15 Nov 2005 21:59:44 -0500 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <437A9596.6020006@REMOVEMEcyber.com.au> Message-ID: In article <437A9596.6020006 at REMOVEMEcyber.com.au>, Steven D'Aprano wrote: > try: > for item in obj: > do_stuff(item) > except TypeError, msg: > if msg == "iteration over non-sequence": > handle_non_iterator() > else: > # re-raise the exception > raise That's the obvious solution, but it's a poor one because it depends on an undocumented feature of the language. What's documented is that TypeError is raised; it's not documented what the text of the message will be. From mwm at mired.org Sat Nov 26 20:05:14 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 20:05:14 -0500 Subject: New docs for set elements/dictionary keys (Was: Why is dictionary.keys() a list and not a set?) References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> <863bljf1o8.fsf@bhuda.mired.org> <4388f6ce$0$22897$9b622d9e@news.freenet.de> Message-ID: <86mzjqew8l.fsf_-_@bhuda.mired.org> "Martin v. L?wis" writes: > Mike Meyer wrote: >>>This is not true. The second definition of __hash__ does not meet >>>the specifications: >> The specification isn't on the __hash__ method, but on objects. > What does it mean for a specification to be "on" something? The > specification I quoted is listed "under" the __hash__ heading > of the reference manual. "applies to" >> That's pretty flaky. The same docs say: >> Should return a 32-bit integer usable as a hash value for dictionary >> operations. > What is flaky about this? What's flaky is the claim in the docs that "the *only* requirement is ...". There are clearly other requirements, and they're listed in the same paragraph as that requirement. >> the dictionary implementation requires that a key's hash value is >> immutable > Indeed, the question here is: what does "an object is immutable" > mean in this context? You appear to read it as "an object whose > state does not change", however, what it really means is "an object > which will always use the same state in __hash__ and __eq__". I've given up on trying to say what "immutable" means, because common usage in the CS and Python communities is ambiguous when it comes to container objects. You give an unambiguous definition, but it's specific to python, and clashes with common usage in the CS and Python communities. Every old-style class that doesn't define __hash__, __eq__ or __cmp__ is immutable by that definition, even if it has mutator methods. Similar comments apply to new-style classes, but require more work to pin down. That's the reason this thread went the direction it did - because I started discussing fixing the docs to not use "immutable" as the defining property. >> Maybe those are only "recommended" properties, but any class that >> doesn't meet them is going to have instances with interesting >> behaviors in sets and as dictionary keys. > Indeed, you can anything return you want in __hash__, or always > raise an exception. What precisely the result of dictionary > operations is when you do so is undefined in Python. I certainly hope that if __hash__ raises an exception, dictionary operations pass the exception on to their caller. For the other cases, undefined behavior is perfectly reasonable. Back onto topic: If you want to use your definition of "immutable" in the docs for dictionary keys and set elements, I think that the docs should explicitly include that definition. We can probably come up with a less ambiguous (does "same state" mean "same state variables" or "variables that don't change value"?) wording as well. Personally, I think we'd be better off to come up with a term for this property that doesn't have a commonly understood meaning that has such broad areas of disagreement with the property. I've been using "hashable", which I would currently define as "has a __hash__ method with the properties described in the __hash__ documentation, or does not have either a __cmp__ or a __eq__ method." Listing which builtin types are hashable and which aren't (and which vary on an instance-by-instance basis) would seem to be worthwhile as well. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From scott.daniels at acm.org Thu Nov 10 15:01:37 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 10 Nov 2005 12:01:37 -0800 Subject: What do you use as symbols for Python ? In-Reply-To: <437397e8$0$7586$636a15ce@news.free.fr> References: <4372f88a$0$31833$636a15ce@news.free.fr> <437397e8$0$7586$636a15ce@news.free.fr> Message-ID: <4373a5e7$1@nntp0.pdx.net> Pierre Barbier de Reuille wrote: > Well, thank you all ! > > I still feel it could be good for Python to have some kind of symbols > built in, and I will try to expose that to the python-dev list, to see > their reaction. > > But in the different solutions proposed, the one I prefer is probably > the definitions of contants in a class to group them. Simple and > organized, I like it. > > Thanks, > > Pierre A suggestion: There are enough PyDev-ers who read this list that you needn't bother talking over there (it will be resented). If you want to pursue it farther, either submit an RFE with a fairly thorough explanation of why this is useful, or write and carry a PEP through about it. This suggestion is neither new nor unique (many people used to other languages suggest it as they come to Python), so you probably will have to have quite persuasive arguments. --Scott David Daniels scott.daniels at acm.org From apardon at forel.vub.ac.be Wed Nov 16 02:51:36 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Nov 2005 07:51:36 GMT Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <7x64qv1tr3.fsf@ruckus.brouhaha.com> <4378a8d6.473364191@news.oz.net> <437a1458.566422091@news.oz.net> Message-ID: Op 2005-11-15, Bengt Richter schreef : > On 15 Nov 2005 08:51:59 GMT, Antoon Pardon wrote: > >>Op 2005-11-14, Bengt Richter schreef : > [...] >>> You may be interested in reviewing >>> >>> http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3 >>> >>> before continuing this topic ;-) >> >>It is a rather long thread. You want to avoid this one becomes of >>comparable length? > Not necessarily. I just thought it might help in making new discussions > of previously discussed ideas clearer faster ;-) Well I hope you are right. But I must confess I skimmed a number of articles, there were just too many, to read them all in such a short times. > Sometimes rehashing old topics seems just tedious, but sometimes someone > has a hunch that they are struggling to express, and they haven't yet succeeded > in communicating its essence. Then old discussions can sometimes serve > like first drafts of a speech, and revisions can prevent repeat of misunderstandings > that in the archived discussions one can see were inevitable. > If the nascent idea comes out viable, we all benefit, and the tedium will have been > worth it. If not, well, then at least some ideas will have clearer form, and > the whole process will have been a social event that some will have enjoyed anyway ;-) Well I certainly support that idea. -- Antoon Pardon From david.ascher at gmail.com Tue Nov 1 10:39:22 2005 From: david.ascher at gmail.com (David Ascher) Date: Tue, 1 Nov 2005 08:39:22 -0700 Subject: OfflineIMAP needs a good home In-Reply-To: References: Message-ID: On 10/31/05, John Goerzen wrote: I have found that I don't have the time or interest to work on > OfflineIMAP anymore, and I'm wondering if there is anyone out in the > Python community that would be interested in taking over this code. > > OfflineIMAP is GPL'd and written 100% in Python. You can get it with: If you switch to a license which is compatible with the PSF's license (i.e. BSD or MIT), then you're more likely to find adoptees (IMO). --david -------------- next part -------------- An HTML attachment was scrubbed... URL: From limodou at gmail.com Wed Nov 16 20:06:39 2005 From: limodou at gmail.com (limodou) Date: Thu, 17 Nov 2005 09:06:39 +0800 Subject: Newbie wxPython ListCtrl Question In-Reply-To: References: Message-ID: <505f13c0511161706j1bf42b4fv@mail.gmail.com> 2005/11/17, Todd7 : > I am new to python and to wxWindows. I have tried searching google, > reading the documentation and trying to figure out some of the examples, > but I am stumped as to how to get information out of a listctrl at a > certain row and column. I tried to write a simple example to learn to > work with the listctrl as follows: I'v made some helper function as that: def getRowText(self, index, col): if index >= 0: return self.list_ctrl_1.GetItem(index, col).GetText() else: return '' def getSelRowText(self, col): return self.getRowText(self.getSelection(), col) def getSelection(self): return self.list_ctrl_1.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) You can just use self.getSelRowText(1) to gain the second column text of selection row. -- I like python! My Blog: http://www.donews.net/limodou NewEdit Maillist: http://groups.google.com/group/NewEdit From martin at v.loewis.de Wed Nov 23 17:24:24 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 23 Nov 2005 23:24:24 +0100 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <3uk6siF11mqgvU1@individual.net> References: <3uk6siF11mqgvU1@individual.net> Message-ID: <4384ec18$0$25871$9b622d9e@news.freenet.de> Paul Watson wrote: > Any ideas why ./Modules/cjkcodecs/_codecs_cn.c fails to compile? It > appears that the CODEC_STATELESS macro is concatenating 'hz' with a > number and text. More likely, hz is already defined to be 100, then forming 100_encode. It would be best if you could find out what AIX header file defines hz to be 100, and whether there is any way to supress that definition. Regards, Martin From apardon at forel.vub.ac.be Thu Nov 3 09:13:13 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Nov 2005 14:13:13 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: Op 2005-11-03, Stefan Arentz schreef : > Antoon Pardon writes: > >> Op 2005-11-03, venk schreef : >> > You see, >> > The seen behavior is due to the result of python's name >> > binding,scoping scheme. >> >> I know what causes the behaviour. But I still think it is >> not sane behaviour. >> >> >> > ... >> > >> > the same thing happens in the case of b.a = b.a + 2 .... search for b.a >> > not found, read the value from the enclosing scope (of the class >> > object).... then assign b.a to the local scope, with the value 3. >> >> This is an explanation depending on a specific implementation. >> >> Now can you give me a language design argument that supports the >> idea that in "b.a = b.a + 2" b.a refers to two different objects. >> >> And even if you could do that, can you give such an argument that >> in "b.a += 2" that one occurence of b.a should refer to two different >> objects. > > Your problem is a namespace conflict together with a certain > stubborness about lookup order :-) > > It is really simple. When you say b.a then the instance variable 'a' > is looked up first. If it does not exist then a class variable lookup > is done. Fine, we have the code: b.a += 2 We found the class variable, because there is no instance variable, then why is the class variable not incremented by two now? > Remember, Python is a dynamic language. So? Python being a dynamic language doesn't prevent the following to fail: >>> a=1 >>> def f(): ... a += 2 ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f UnboundLocalError: local variable 'a' referenced before assignment > It is all according to how things have been in Python for a long time. Unsane behaviour for a long time is still unsane behaviour. > The real issue here is that you should propery name class variables so > that there can't be any confusion about class or instance scope. I use > all uppercase identifiers for class variables for example. The fact that this can be regarded as unwise coding, doesn't imply it is sane behaviour of python. Variable shadowing happens. I don't consider it sane behaviour if the same reference in a line gets resolved in different name spaces -- Antoon Pardon From graham.fawcett at gmail.com Thu Nov 3 20:11:43 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 3 Nov 2005 17:11:43 -0800 Subject: ADT for restricted set of values In-Reply-To: References: Message-ID: <1131066703.487745.12960@f14g2000cwb.googlegroups.com> Ben Finney wrote: > Howdy all, > > I'd like to have an Abstract Data Type for a scalar value that is > restricted to a small set of values. Like an Enum, I suppose. > > What I would like is to be able to use simple 'str' values in most of > the code, but where the values are actually used in a semantically > meaningful context, have them used as an ADT that will barf if the > value isn't part of the set. How about this: class BaseEnum(str): """Base class for enumerations. You must subclass and provide values for the _valid list.""" _valid = [] def __init__(self, v): assert self in self._valid, 'value %r not in %r' % (self, self._valid) cass Gender(BaseEnum): _valid = ['male', 'female', 'unknown'] Trying the following: Gender('male') Gender('female') assert Gender('male') == 'male' Gender('shemale') The last will return an error: AssertionError: value 'shemale' not in ['male', 'female', 'unknown'] Graham From bignose+hates-spam at benfinney.id.au Sat Nov 26 18:21:00 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 Nov 2005 10:21:00 +1100 (EST) Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: Jorgen Grahn wrote: > Tom Anderson wrote: > > The logic, i think, is that the freedom of the code is the key to > > the freedom of the end-users: applying the GPL to your code means > > that other programmers will be forced to apply to to their code, > > which means that users of that code will get the benefits of open > > source. > > ... which implies that one believes that every end-user has the > potential to become a hacker. To become, or *independently engage another person as* a hacker without necessary further contact with the copyright holder. The same freedom you get with, e.g., any complicated machine. You can open it up yourself, or you can persuade a third party to do so, without the necessity to get the maker involved. It's not necessary for every single user of such machines to become hackers of those machines; they still all get the benefit of the freedom for anyone they choose to hack on it. -- \ "I have a map of the United States; it's actual size. It says | `\ '1 mile equals 1 mile'... Last summer, I folded it." -- Steven | _o__) Wright | Ben Finney From jmdeschamps at gmail.com Thu Nov 3 14:39:36 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 3 Nov 2005 11:39:36 -0800 Subject: Can Anyone Help me on this In-Reply-To: References: Message-ID: <1131046776.264102.88220@g43g2000cwa.googlegroups.com> ... list2=list1[:] ... Yes, naturally, where was my head ?-)) From peter at engcorp.com Sat Nov 26 20:31:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Nov 2005 20:31:53 -0500 Subject: Comparison problem In-Reply-To: References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: Tom Anderson wrote: > On Sat, 26 Nov 2005, Peter Hansen wrote: >>Tom Anderson wrote: >>>On Sat, 26 Nov 2005, Chris wrote: >>>> if item[0:1]=="-": >>> >>>item[0:1] seems a rather baroque way of writing item[0]! I'd actually >>>suggest writing this line like this: >> >>Actually, it's not so much baroque as it is safe... item[0] will fail if >>the string is empty, while item[0:1] will return '' in that case. > > Ah i didn't realise that. Whether that's safe rather depends on what the > subsequent code does with an empty string - I meant "safe" as in "doesn't throw an exception", as item[0] will when passed an empty string... sometimes you don't want code to throw an exception, and you don't want to have to do a separate test for certain conditions that might do so. This technique is one example. > an empty string might be some > sort of error (in this particular case, it would mean that the loop test > had gone wrong, since bool("") == False), and the slicing behaviour would > constitute silent passing of an error. > > But, more importantly, egad! What's the thinking behind having slicing > behave like that? Anyone got any ideas? What's the use case, as seems to > be the fashionable way of putting it these days? :) Well, since slicing is (I believe, and speaking only roughly) supposed to return a sequence of the same type as that on which it's operating, what would be the alternative? Unless you allow slicing to return None, or raise an exception in certain cases, return a null sequence of the appropriate type seems to be perfectly logical behaviour when the requested slice doesn't exist in the input. But I'm not sure this is from a specific use case so much as a side effect of other more desirable behaviours of slicing. Asking for this to behave differently without analyzing the impact it has on slicing in general is likely to overlook something crucial... -Peter From robert.kern at gmail.com Tue Nov 22 13:50:49 2005 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 22 Nov 2005 10:50:49 -0800 Subject: PIL FITs image decoder In-Reply-To: <1132684114.165243.33310@g43g2000cwa.googlegroups.com> References: <1132681491.921657.291860@z14g2000cwz.googlegroups.com> <1132684114.165243.33310@g43g2000cwa.googlegroups.com> Message-ID: jbrewer wrote: >>http://www.stsci.edu/resources/software_hardware/pyfits > > I know and love PyFits, but I need to be able to do draw shapes on a > FITs image (and perhaps some other operations), and I don't believe > that PyFits allows these kinds of operations. It might be possible to > import the data into a numarray object and turn that into something PIL > can read, though. If you can bear having two copies in memory, Image.frombuffer() generally does the trick. -- 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 mwm at mired.org Wed Nov 23 23:32:20 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 23:32:20 -0500 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1132800973.008501.34090@g14g2000cwa.googlegroups.com> <867jay1ybk.fsf@bhuda.mired.org> <1132805759.799632.265850@f14g2000cwb.googlegroups.com> Message-ID: <86u0e2zmwb.fsf@bhuda.mired.org> "bonono at gmail.com" writes: >> Maybe Python attracts people who share that belief. After all, TRTFTJ >> is implies TSBOOWTDI, and vice versa. > I was not talking about the believe, I was talking about the way you > presented it. You are setting up an "imaginary" me, which is not me. > And that is the kind of arguments I saw, I believe this many times are > done unconciously. You're doing that yourself. But we don't have a real other person to work with - the best we can do is work with our model of that other person. That's life. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From simon.brunning at gmail.com Tue Nov 15 05:27:45 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 15 Nov 2005 10:27:45 +0000 Subject: compare list In-Reply-To: <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> References: <8c11e4350511140351m6aa551e1ybb695c36048825ad@mail.gmail.com> <437936F6.1010503@cc.umanitoba.ca> <8c11e4350511142120l436a1cb5k48dec7b10a524266@mail.gmail.com> <437982C0.5090702@cc.umanitoba.ca> <1d987df30511142330t39b137fdpdc9eee56e73d6e1f@mail.gmail.com> <4379AA95.80806@cc.umanitoba.ca> <1d987df30511150149g778fdd0ep141e9998160fcb22@mail.gmail.com> Message-ID: <8c7f10c60511150227v297140e1n@mail.gmail.com> On 15/11/05, Shi Mu wrote: > it does not work. > >>> len(set(lisA).intersection(set(lisB))) == 2 > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'set' is not defined 'set' is introduced as a built-in at Python 2.4. If you have 2.3, there's an analogous module. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From da.martian at gmail.com Fri Nov 11 08:26:58 2005 From: da.martian at gmail.com (ChaosKCW) Date: 11 Nov 2005 05:26:58 -0800 Subject: Import statements for timeit module Message-ID: <1131715618.580594.68630@z14g2000cwz.googlegroups.com> Hi I was wondering if someone could help with the import statements needed to use the timeit module in the following code. I need to access the "cur" object. Thanks, import cx_Oracle import timeit def VerifyTagIntegrity(con, TableOwner): cur = con.cursor() sql = 'select (select count(*) from %s.f4111) as F4111_COUNT, (select count(*) from %s.f4111_tag) as TAG_COUNT from dual;' % (TableOwner, TableOwner) print " SQL: %s" % (sql) timer = timeit.Timer('cur.execute(sql)', 'from __main__ import cur') print timer.timeit() From pmartin at snakecard.com Sat Nov 5 12:41:53 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Sat, 05 Nov 2005 17:41:53 +0000 Subject: Python gui Message-ID: Hi, Is wxWidget now part of python ? or will it be ? regards, Philippe From clansofintrigue at gmail.com Wed Nov 2 14:15:33 2005 From: clansofintrigue at gmail.com (Clans Of Intrigue) Date: 2 Nov 2005 11:15:33 -0800 Subject: Forcing the position of scroll bars on a wxTextCtrl References: <1130950032.605129.194930@g14g2000cwa.googlegroups.com> Message-ID: <1130958933.572241.154150@z14g2000cwz.googlegroups.com> Thanks, that did the trick perfectly :) also got rid of the self._log member so the class is now just: class LogControl: """ Simple helper to redirect stdout to a panel in the GUI """ def __init__( self, textCtrl ): self._ctrl = textCtrl self.write( "Application Started..." ) def write( self, Message ): # Add message to log and force scroll bars to end of window self._ctrl.SetValue( self._ctrl.GetValue() + Message ) self._ctrl.ShowPosition(self._ctrl.GetLastPosition()) Lovely :) From dieter.vanderelst at gmail.com Wed Nov 30 09:54:40 2005 From: dieter.vanderelst at gmail.com (Dieter Vanderelst) Date: Wed, 30 Nov 2005 15:54:40 +0100 Subject: Cropping sound files In-Reply-To: <1133360961.766130.277790@g43g2000cwa.googlegroups.com> References: <1133360961.766130.277790@g43g2000cwa.googlegroups.com> Message-ID: <438DBD30.9030100@gmail.com> Hello, My previous problem with Winsound has boiled down to a new problem. I have some soundfiles (wav) of which I only need the n first seconds. So, I thought I could crop them using the standard wave-module: This is some of my code: #I open the wav file and I read the first n frames f_org = wave.open(file_name, 'r') frames = f_org.readframes(f_org.getframerate( )*sec) #these frames I write to a new file #the parameters for the new file are the same as for the original file, #only the number of frames is different f_new.setparams(pra) f_new.writeframesraw(frames). This works fine for short files (up to 20 sec). But if I try this with larger files, an later play the new cropped files with windsound, winsound doesn't play the whole new file (although windows media player does so). Does anybody has a piece of code that I can use to crop my files? Because I must be doing something wrong. Thanks, Dieter Graham Fawcett wrote: >Dieter Vanderelst wrote: > > >>Hello, >> >>I'm having a problem with playing WAV files using Winsound. >> >>If I use winsound to play a certain WAV files only the first few seconds >>of the file get played. I think this comes because these files contain >>some parts of silence. There winsound seems the stop playing the files >>(windows media player plays the sounds correctly). >> >> >[snip] > > >>Just as a reference, the code I use: >>winsound.PlaySound("My_wav.wav", winsound.SND_FILENAME) >> >> > >This is totally a guess, but add the following to the end of your test >script: > >import time >time.sleep(10) > >Did the file play for ten seconds longer? I don't know anything about >winsound, but I'm guessing that the PlaySound call is non-blocking, and >your playback stops because your process is quitting before the sound >has played. > >Graham > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From s99999999s2003 at yahoo.com Tue Nov 15 05:52:54 2005 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 15 Nov 2005 02:52:54 -0800 Subject: generate HTML In-Reply-To: <4378dc0c$1@nntp0.pdx.net> References: <1131962200.216285.307760@g44g2000cwa.googlegroups.com> <4378dc0c$1@nntp0.pdx.net> Message-ID: <1132051974.733119.184010@f14g2000cwb.googlegroups.com> hi thanks for all the help actually i am doing it the hard way alist = [ '
TEST
', '


', 'blah' ] f = open('test.html",'w') f.writelines(alist) f.close() but everytime i hit ... alist = [ '

.... ValueError: unsupported format character '"' (0x22) at index 14 what does it mean? i tried alist = [ '
TEST
'] on the IDE and it works thanks. From thorsten at thorstenkampe.de Tue Nov 1 04:36:03 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 1 Nov 2005 09:36:03 +0000 Subject: OpenSSL in Python References: <1130425810.431748.39660@g14g2000cwa.googlegroups.com> <1130807503.274960.158820@g14g2000cwa.googlegroups.com> Message-ID: * dcrespo (2005-11-01 01:11 +0100) >> wouldn't your question then not be more appropriate on the >> OpenSSL newsgroup/mailinglist/forum/whatever? > > Well, I think that because python is the language where I want it to > run, I ask it right here. You might think again. Your problem is not related to Python in any way. > OpenSSL is written in C, so they wont help me. Who's "they"? > I need the right wrappers to that C library. The "wrapper" is pyopenssl, right? But anyway, your question in a FAQ: http://www.openssl.org/support/faq.html#MISC4 Took me about ten seconds to find it... From p at ulmcnett.com Tue Nov 29 23:58:46 2005 From: p at ulmcnett.com (Paul McNett) Date: Tue, 29 Nov 2005 20:58:46 -0800 Subject: an intriguing wifi http server mystery...please help In-Reply-To: <1133324893.968023.79050@z14g2000cwz.googlegroups.com> References: <1133324893.968023.79050@z14g2000cwz.googlegroups.com> Message-ID: <438D3186.2070800@ulmcnett.com> jojoba at gmail.com wrote: > 1) > Laptop wired, client > Desktop wired, server > GREAT! > webpage served in 2 seconds > > 2) > Laptop wired, server > Deskop wired, client > GREAT! > webpage served in 2 seconds > > 3) > Laptop wireless, client > Desktop wireless, server > GREAT! > webpage served in 2 seconds > > 4) > Laptop wireless, server > Desktop wireless, client > CRAP! > webpage served in 90 seconds > > > What the heck is happening? Please post your routing tables and, if you are referencing your server machine by name, your name server addresses (/etc/resolv.conf on Linux). -- Paul McNett http://paulmcnett.com http://dabodev.com From apardon at forel.vub.ac.be Wed Nov 30 04:48:10 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Nov 2005 09:48:10 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: On 2005-11-29, Duncan Booth wrote: > Antoon Pardon wrote: > >> The question is, should we consider this a problem. Personnaly, I >> see this as not very different from functions with a list as a default >> argument. In that case we often have a list used as a constant too. >> >> Yet python doesn't has a problem with mutating this list so that on >> the next call a 'different' list is the default. So if mutating >> a list used as a constant is not a problem there, why should it >> be a problem in your example? >> > Are you serious about that? I'm at least that serious that I do consider the two cases somewhat equivallent. > The semantics of default arguments are quite clearly defined (although > suprising to some people): the default argument is evaluated once when the > function is defined and the same value is then reused on each call. > > The semantics of list constants are also clearly defined: a new list is > created each time the statement is executed. Consider: > > res = [] > for i in range(10): > res.append(i*i) > > If the same list was reused each time this code was executed the list would > get very long. Pre-evaluating a constant list and creating a copy each time > wouldn't break the semantics, but simply reusing it would be disastrous. This is not about how things are defined, but about should we consider it a problem if it were defined differently. And no I am not arguing python should change this. It would break too much code and would make python all the more surprising. But lets just consider. Your above code could simply be rewritten as follows. res = list() for i in range(10): res.append(i*i) Personnaly I think that the two following pieces of code should give the same result. def Foo(l=[]): def Foo(l): ... ... Foo() Foo([]) Foo() Foo([]) Just as I think, you want your piece of code to give the same result as how I rewrote it. I have a problem understanding people who find the below don't have to be equivallent and the upper must. -- Antoon Pardon From cfajohnson at gmail.com Sat Nov 19 00:55:58 2005 From: cfajohnson at gmail.com (Chris F.A. Johnson) Date: Sat, 19 Nov 2005 00:55:58 -0500 Subject: os.popen('alias') References: <1132345866.163167.174360@f14g2000cwb.googlegroups.com> Message-ID: On 2005-11-18, Belebele wrote: >>From an interactive python shell, I execute the following: > > import os > for line in os.popen('alias').readlines(): > print line > > > No aliases are printed. > > I started python from an bash environment that had many aliases > defined. I expected to see the list of aliases from within the > interactive python shell. Since bash does not export aliases, they cannot be seen by a child process. > What could I do to see those aliases defined in the shell from where > I started python? Store them in a file before calling python, and read that file. -- Chris F.A. Johnson, author | Shell Scripting Recipes: | My code in this post, if any, A Problem-Solution Approach | is released under the 2005, Apress | GNU General Public Licence From s99999999s2003 at yahoo.com Tue Nov 8 00:39:24 2005 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 7 Nov 2005 21:39:24 -0800 Subject: problem generating rows in table In-Reply-To: <86ek5r90p1.fsf@bhuda.mired.org> References: <1131424393.303923.263380@g43g2000cwa.googlegroups.com> <86ek5r90p1.fsf@bhuda.mired.org> Message-ID: <1131428364.306057.145000@g47g2000cwa.googlegroups.com> thanks for all the help. problem solved by taking out range(). From steve at REMOVEMEcyber.com.au Thu Nov 24 02:17:43 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 24 Nov 2005 18:17:43 +1100 Subject: [OT] Enough! [was: wxPython Licence vs GPL] References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <11oabrjoplekcfd@corp.supernews.com> Message-ID: <43856917.8000704@REMOVEMEcyber.com.au> Robert Kern wrote: > Take your off-topic argument off-list. You don't think questions of the legality of when and how you can write and distribute Python programs are of interest to Python developers? Fair enough I suppose. Who cares what the licences say, we're all just going to break them anyway. -- Steven. From paul at boddie.org.uk Wed Nov 30 10:32:44 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 30 Nov 2005 07:32:44 -0800 Subject: Which License Should I Use? In-Reply-To: <7xu0dvsn5e.fsf@ruckus.brouhaha.com> References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> <7xu0dvsn5e.fsf@ruckus.brouhaha.com> Message-ID: <1133364764.129752.138250@g47g2000cwa.googlegroups.com> Paul Rubin wrote: > That is the guy who claims it is impossible to release anything into > the public domain, other than by dying and then waiting 70 years. Is that an indirect reference to the following article? http://www.linuxjournal.com/article/6225 Paul From jeremy+complangpython at jeremysanders.net Wed Nov 9 04:32:10 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 09 Nov 2005 09:32:10 +0000 Subject: Using python for writing models: How to run models in restricted python mode? References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> Message-ID: vinjvinj wrote: > 2. restrict the amount of memory a module uses as well. For instance > how can I restrict a user from doing a = range(10000000000) or similar > tasks so that my whole compute farm does not come down. The safest way to do this in unix is to run the model in a separate process, and use ulimit (or the resource module) to limit the memory usage. -- Jeremy Sanders http://www.jeremysanders.net/ From steve at holdenweb.com Thu Nov 24 16:36:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 21:36:08 +0000 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: <1132862512.146221.33970@g44g2000cwa.googlegroups.com> References: <1132778601.776080.80100@g44g2000cwa.googlegroups.com> <1132862512.146221.33970@g44g2000cwa.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > "Fredrik Lundh" wrote: > >>rurpy at yahoo.com wrote: >> >> >>>>the thing that's in favour is "then-if-else", not "if-then-else". >>> >>>Sorry if I confused you, I though it was clear that I meant the >>>concept, not a specific syntactical implementation. >> >>yup, but if you care readability about, the words order appear in >>would to seem matter too. > > > Yes, order does matter. Which is why I chose the order I > did. Anyone familiar with programming (including Python > programmers) will understand what an "if-then-else" statement > and expression are. The term "then-if-else" will make sense > only to people who use Python and are familiar with the > twists and turns of the PEP-308 debate. Why would I choose > to intentionally restrict the audience of my post when there > is no need to? (That this is a Python newsgroup read by > Python users is not relevant. Other people read it too.) > > It is very interesting I think, because this is the core of my > complaint about Python. Python seems unwilling to adapt > to any unapproved styles, even when it could do so at > little cost. Like you, it prefers targeting a narrow(*) > audience willing to adopt the "one true programming style" > even when it could appeal to a wider audience. > Now, see, that's the thing. The more ways there are to write the same program, the harder any given program will be to understand. This is indeed a fairly deliberate approach in the Python world, and contrasts with languages where readability is low because of the multiple different ways of expressing the same idea. > That you extend this Python philosophy even to english > and newsgroup posting is fascinating... > I think Fredrik was trying to make a point about the need to be accurate in discussing language features, but I could be wrong. > (*) I mean narrow in their view of what constitutes good > style, not narrow or small in numbers. > 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 mde at micah.elliott.name Wed Nov 16 16:15:34 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Wed, 16 Nov 2005 13:15:34 -0800 Subject: readline vi mode in python interactive shell In-Reply-To: <1132171451.328876.177210@z14g2000cwz.googlegroups.com> References: <1132171451.328876.177210@z14g2000cwz.googlegroups.com> Message-ID: <20051116211534.GK18475@kitchen.client.attbi.com> On Nov 16, tnoell at gmail.com wrote: > Hi comp.lang.python: > New to the group and new to python, so don't tear me up too much ... > I installed the GNU readline support in python2.4, and it is working, > but there is one annoying behaviour that I am hoping to squash ... > > Namely, when I hit to go to edit mode, then hit 'k' to go up > in the command history, the prompt is put at the start of the line. Amazing that you brought this up right now; I was just thinking about whether or not to bother posting my own annoyance (invisible last history command) with readline 4.3-5 (default with Fedora Core 3) and Python 2.4.2. Since you brought it up, here's my test case: My ~/.inputrc simply contains "set editing-mode vi". When I start python I type "print 'a'". Then "k" to recall the last command -- but the line is invisible! If I start editing the blank/invisible line the text magically appears. Or if I press "k" twice I have visible history again. So now I have in muscle memory "kkj" to get my last command :-( This is not a problem on the same machine with older versions of python that are installed. Is this worth filing a bug against python? I didn't find anything reported on sf.net/projects/python. > Other places I use vi mode command line editing (e.g., zsh), the > cursor is at the end of the previous command. More often than not, I > am wanting to edit the latter part of the previous command, not the > start. In bash "k" puts me at the *beginning* of the line. Of course $ puts you where you want to be then, but I'm not sure how to affect the behavior you're asking for; "help bind" might be useful, and "bind -P" shows some mappings. -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From ssjassal at gmail.com Mon Nov 21 22:21:17 2005 From: ssjassal at gmail.com (ssjassal at gmail.com) Date: 21 Nov 2005 19:21:17 -0800 Subject: Preventing modules to be read from current working directory In-Reply-To: References: <1132628732.123362.122820@g43g2000cwa.googlegroups.com> Message-ID: <1132629677.274318.178190@g43g2000cwa.googlegroups.com> Great, thanks. From robert.kern at gmail.com Mon Nov 21 11:07:30 2005 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 21 Nov 2005 08:07:30 -0800 Subject: Numeric array in unittest problem In-Reply-To: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> References: <1132576811.598640.57530@f14g2000cwb.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > hello, > > I found that if I use Numeric.array into unittest it is not > consistance, > Is that normal ? > > import Numeric > class myTest(unittest.TestCase): > def runTest(self): > a = Numeric.array([1,2]) > b = Numeric.array([1,33]) > self.assertEqual(a, b) > pass > > > This will not raise any error ??? > > Any idea? unittest.TestCase.assertEqual() uses == to compare a and b. Numeric arrays have rich comparisons and so return arrays, not booleans. Try it in the interpreter. To get a boolean from a==b, use Numeric.alltrue(a==b). -- 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 mwm at mired.org Sat Nov 26 04:59:59 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 04:59:59 -0500 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> Message-ID: <86k6evg25c.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Fri, 25 Nov 2005 23:20:05 -0500, Mike Meyer wrote: >> If you've got a use case, I'd be interested in hearing it. > frozenset perhaps? If it were needed once, it could be needed again. That's not a use case, that's an example. And not a very good one, as it's not at all clear that the restriction is intentional in that case. After all, the same restriction applies to every builtin type, including the mutable version of frozenset. > The obvious case would be for a class where distinct instances that > compare equal but not identical map to the same value in a dict. How does the ability to add attributes to the instances of the class change that behavior? > In any case, I'm not the one claiming that I need custom immutable > classes. I'm just suggesting that there is nothing non-Pythonic about > them. If Ben thinks he needs them, I'm sure he has put *far* more thought > into it than I have. I know Ben in RL, and he is not someone to make snap > judgements about turning Python into Some Other Language Just Because. I claim that the dynamic natture of Python - which is exemplified by things like duck typing and the ability to add attributes to nearly everything on the fly - is a fundamental part of what makes Python Python. The best reason Ben could come up with is that it makes finding bugs a bit easier. But so do type declarations, static namespaces, private and protected attributes, and a slew of similar B&D features that are pretty much anathema to dynamic languages. This feature fits *very* well in languages that have those features, and poorly in languages that reject them, which includes Python. Of course, that a feature has a lot in common with features from un-Pythonic languages doesn't make it ipso facto unPythonic. After all, practicality beats purity. So what's the practical application for such a feature? What's the use case? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From apardon at forel.vub.ac.be Thu Nov 3 06:55:06 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Nov 2005 11:55:06 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: Op 2005-11-03, Steven D'Aprano schreef : >> There are two possible fixes, either by prohibiting instance variables >> with the same name as class variables, which would allow any reference >> to an instance of the class assign/read the value of the variable. Or >> to only allow class variables to be accessed via the class name itself. > > There is also a third fix: understand Python's OO model, especially > inheritance, so that normal behaviour no longer surprises you. No matter wat the OO model is, I don't think the following code exhibits sane behaviour: class A: a = 1 b = A() b.a += 2 print b.a print A.a Which results in 3 1 -- Antoon Pardon From elbertlev at hotmail.com Mon Nov 21 01:09:34 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 20 Nov 2005 22:09:34 -0800 Subject: ownership problem? References: Message-ID: <1132553374.585901.315200@g49g2000cwa.googlegroups.com> Yes! Python uses auto garbage collection. As soon as the object reference count becomes 0 it is removed from existence. So the problem typical for C/C++: accessing pointers to already deleted objects does not exist in Python. From steve at REMOVETHIScyber.com.au Thu Nov 3 17:29:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 04 Nov 2005 09:29:23 +1100 Subject: OT - Re: Microsoft Hatred FAQ References: Message-ID: On Thu, 03 Nov 2005 14:56:44 -0500, Tim Daneliuk wrote: > There is a difference between what is *illegal* and what constitutes > a *crime*. Why thank you, you've really made my day. That's the funniest thing I've heard in months. Please, do tell, which brand of corn flakes was it that you got your law degree from? -- Steven. From aleax at mail.comcast.net Mon Nov 28 10:46:45 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 28 Nov 2005 07:46:45 -0800 Subject: should python have a sort list-map object in the std-lib? References: <1h6pg7c.1q4nxaf4virbiN%aleax@mail.comcast.net> <1133157636.793917.206740@g47g2000cwa.googlegroups.com> Message-ID: <1h6q7sw.3vrvce1rp7rieN%aleax@mail.comcast.net> Tim Henderson wrote: > ahh, i hadn't thought of using a proirity queue but that is the correct > solution most of the time, except i suppose when you have input that > causes you to excessively reheap which could be problematic. The worst case is still O(N logN) for heap as well as timsort. But since timsort can take advantage of order or reverse order already present in the sequence, it's surely possible to find real use cases in which one sort at the end of all insertions is O(N) and thus much faster. Nevertheless, that also depends on having a lot of insertions before you need any sorting; if you need to "walk sorted" after each insertion or thereabouts, I would guess heap would be faster again. > i may still look into writing a general sorted map though, it could be > useful especially if there were and easy way to set the type of > functionality required with out resorting to several different types of > sorted-maps. You can record a callable equivalent to sort's key= once and for all at the creation of the "sorted map". heapq's functions don't directly support that in 2.4 (they will in 2.5) but it's easy to implement via explicit key-extraction upon insertion (once known as the D step in the DSU, decorate-sort-undecorate, idiom). It's unclear whether you want to be able to key the sorting off keys only, or keys AND values: the latter is more general but also takes more work and complication. As for "different types", if I catch your drift...: I would suggest avoiding the temptation to overload the type with a bazillion options-flags requiring deeply different behavior, e.g. copying keys and/or values versus just taking references to either or both, or either requiring or foregoing hashable keys (with different implementations). If such differences are warranted by use cases, it's better to have several different types than one complicated one. I would personally suggest mimicking dict's semantic: require hashable keys, make no copies. Alex From tinman31337 at gmail.com Wed Nov 23 11:01:28 2005 From: tinman31337 at gmail.com (Tin Gherdanarra) Date: Wed, 23 Nov 2005 08:01:28 -0800 Subject: syntax errors while building pypgsql In-Reply-To: References: <3uj7hcF10k63tU1@individual.net> Message-ID: <3uji38F11j0brU1@individual.net> Gerhard H?ring wrote: > Tin Gherdanarra wrote: > >> Hallo, >> >> I'm trying to install pypgsql. However, I get syntax errors >> while compiling the C sources. The following excerpt >> from pgconnection.h looks a little funny to me: >> >> typedef struct { >> PyObject_HEAD /* Here is the syntax error, and rightly so */ >> [...] >> I don't know what PyObject_HEAD or PGconn is, >> but if they are types, a syntax error is justified here: [...] > > > I don't think that's the real error. Well, I don't know what's going on in that struct def, but to me it looks a little weird. > Are there any error messages > *before* that? Nope. First error. > Like the compiler can't find "Python.h" or something? > That would be an indication that you do not have the python-devel > package installed. This provokes different errors. Your idea is good, though, because this was the first problem another correspondent pointed out. > > Btw. the Debian package of pyPgSQL is called python-pgsql, so an apt-get > install python-pgsql should do. Thanks, this I have found out already (see previous post). It is in the fine print of the documentation. Thanks Tin > > -- Gerhard > From y.glodt at sitasoftware.lu Thu Nov 10 08:41:24 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Thu, 10 Nov 2005 14:41:24 +0100 Subject: iterate over class variables In-Reply-To: <4373402c$0$30556$636a15ce@news.free.fr> References: <43733767.1040205@sitasoftware.lu> <4373402c$0$30556$636a15ce@news.free.fr> Message-ID: <43734E04.9020706@sitasoftware.lu> bruno at modulix wrote: > Yves Glodt wrote: >> Yves Glodt wrote: >> >>> Hello list, >>> >>> I need to iterate over a class and get all her variable names and >>> values, e.g. considering this example: >>> >>> >>> class testclass: >>> var1 = 'ab' >>> var2 = 'cd' >>> var3 = 'ef' > > Take care, these are *class* variables, not instance variables. > >>> test = testclass() >>> >>> Then I wanna do sonmething like this: >>> >>> for name,value in test: >>> print name >>> print value >>> > (snip) >> sorry for selfreplying, but I found a solution: >> >> for key in dir(test): >> if '__' not in key: >> value = getattr(test,key) >> print key, value >> >> Does anything speak about this? > > 1/ dir() doesn't necessary returns all the attributes of an object: > """ > dir(...) > dir([object]) -> list of strings > > Return an alphabetized list of names comprising (some of) the attributes > of the given object, and of attributes reachable from it: > """ > > But I don't think this is a problem here. > > 2/ everything being an object, dir() also returns methods (a method > being a - callable - attribute of the object's class). > > If you're only interested in data attributes, you may want to try this: > > for key in dir(test): > if not key.startswith('__'): > value = getattr(test,key) > if not callable(value): > print key, value This serves me well so far, thanks to you, Peter and Daniel for the suggestions! Yves (still amazed of the responsiveness of this list :-) > You can also check inspect.getmember() From shalabh at cafepy.com Thu Nov 24 12:57:18 2005 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 24 Nov 2005 09:57:18 -0800 Subject: Understanding Python Documentation In-Reply-To: <200511240906.00008.joshuacronemeyer@sunflower.com> References: <200511240906.00008.joshuacronemeyer@sunflower.com> Message-ID: <4385FEFE.1080108@cafepy.com> Josh Cronemeyer wrote: > Hi, > > I have very little experience programming in python but considerable > experience with java. One thing that is frustrating me is the differences in > the documentation style. Javadocs, at the top level are just a list of > packages. Drilling down on a package reveals a list of classes in that > package, and drilling down on a class reveals a list of methods for that > class. Is there something similar for python? > > The closest thing I have found to this for python is > http://www.python.org/doc/2.4.2/modindex.html which really isn't the same > thing at all. > > wxpython has their documentation like this http://www.wxpython.org/docs/api/ > is there something like this for the rest of python? Here is the Python 2.3 standard lib docs generated using epydoc: http://epydoc.sourceforge.net/stdlib/ In look and feel it's more like javadoc. However always check the standard library documentation for usage and examples that might not be in this. Cheers, Shalabh From waldbie at yahoo.com Wed Nov 23 18:12:02 2005 From: waldbie at yahoo.com (Carl Waldbieser) Date: Wed, 23 Nov 2005 18:12:02 -0500 Subject: Embedding a CPython Script engine in a .NET application. Message-ID: Has anyone had any experience embedding a CPython engine in a .NET application? In the COM/ActiveX world, it was pretty easy to use Mark Hammond's win32 modules to create a script engine component that you could expose other COM objects to, but I was not sure how I would go about doing something similar in a .NET environment. For example, something like: ... .NET Application code ... 'Create Foo object. set Foo = New Foo("baz") 'Create embedded cpython script engine. set engine = New CPythonEngine() 'Expose Foo object to engine. engine.AddNamedItem(Foo, "Foo") 'Load python script. engine.LoadScript("D:\scripts\frotz.py") 'Run script (uses Foo). engine.Run() 'Get results' set resultsCollection = engine.getResults() Is something like this possible, or am I thinking about things the wrong way? I am mainly interested in knowing if this is possible with cpython, as I understand IronPython is currently in beta. Thanks. From petr at tpc.cz Thu Nov 3 17:52:07 2005 From: petr at tpc.cz (Petr Jakes) Date: 3 Nov 2005 14:52:07 -0800 Subject: UART parity setting as "mark" or "space" (using Pyserial???) Message-ID: <1131058327.332739.308620@z14g2000cwz.googlegroups.com> Hi, I am trying to set-up communication to the coin change-giver from my Linux box using the Python code. The change giver uses MDB (Multi Drop Bus) serial protocol to communicate with the master. MDB protocol is the 9bit serial protocol: (TX, RX lines only) 9600bps, 9bits, No Parity, 1 Start, 1 Stop. I would like to control the UART "parity bit" to try to simulate 9bit communication. Using Pyserial it is possible to set the parity bit as ODD, EVEN or NONE. I have found in the following link (paragraph 21.3) http://howtos.linux.com/howtos/Serial-HOWTO-21.shtml#ss21.1 that UART hardware supports two "rarely used" parity settings as well: mark parity and space parity (these setings are also known as "sticky parity") A "mark" is a 1-bit (or logic 1) and a "space" is a 0-bit (or logic 0). For mark parity, the parity bit is always a one-bit. For space parity it's always a zero-bit. Does anybody here knows some "tricks" how to set up the mark and space parity on the UART (using pyserial???), so I can simulate 9bit communication? (I know it sounds silly, but I would like to try to re-configure the UART parity before each byte transmission). Any comment will be appreciated. Petr Jakes From jeff at schwabcenter.com Sat Nov 5 07:50:44 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Sat, 05 Nov 2005 12:50:44 GMT Subject: Using Which Version of Linux In-Reply-To: References: Message-ID: blah at blah.blah wrote: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. Solaris isn't Linux, but it is good. I've never installed it from scratch, though. I might get lambasted for suggesting this, but try Slackware. It will let you do a very minimal installation, which means there's less stuff that can go wrong. It also has nice, beginner-friendly FAQs to help you get started. Like the other distros already suggested, it comes with the graphical desktop environments Gnome and KDE, too. If at all possible, have another computer available with a working internet connection and a floppy disc drive or CD burner. Like Maciej said, if you have a buddy nearby who is already an expert on a particular distro, try that distro. This is especially true for distros like Gentoo that have... their own way of doing things. :) From everettcc at hotmail.com Tue Nov 8 21:58:30 2005 From: everettcc at hotmail.com (Chad Everett) Date: Tue, 8 Nov 2005 20:58:30 -0600 Subject: Newb ?? Message-ID: Hi all, I am new to the group. Trying to learn Python programming on my own. I am working through Michael Dawson's Book Python Programming for the absolute beginner. I am tring to write a program that is a number guessing game. I want to be able to give the user 5 tries to guess the number before the program ends. I get the result that I want when the user misses after the 5th try. But it does not go down to my closing statement to end. Rather is askes for another guess. I appreciate any help you can give. If this is not the correct group for these types of questions, I apologize and hope that you can direct me to another NG. Thanks, Chad import random print "\tWelcome to 'Guess my Number'!" print "\nI'm Thinking of a Number between 1 and 100." print "\nTry to Guess it in as few attempts as possible.\n" #Set the initial values the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess:")) tries = 1 #Guessing Loop while (guess != the_number): if (guess >the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take another Guess:")) tries +=1 if tries == 5: print "Sorry you lose." print "The Correct Number was ", the_number print "You guess correctly!!" print "The number was:", the_number print "You got it correct in", tries, "tries" raw_input("Press Enter to exit the program") From roy at panix.com Wed Nov 9 08:29:28 2005 From: roy at panix.com (Roy Smith) Date: Wed, 09 Nov 2005 08:29:28 -0500 Subject: append to non-existing list References: Message-ID: Yves Glodt wrote: > My question is: Is there no way to append to a non existing list? Nope. The problem (well, part of the problem, anyway) is that when you do: foo.append (bar) what's happening is you're calling foo's append method. If foo doesn't already exist, it has no way of knowing what to call. > I am lazy for declaring it first, IMHO it bloats the code, and (don't > know if it's good to say that here) where I come from (php) I was used > to not-needing it... Python is not php. Nor is it Perl. Nor it is a whole bunch of other things. From steve at REMOVETHIScyber.com.au Sat Nov 19 02:02:21 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 18:02:21 +1100 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132376750.855932.45470@g47g2000cwa.googlegroups.com> Message-ID: On Fri, 18 Nov 2005 21:05:50 -0800, bonono at gmail.com wrote: > Steven D'Aprano wrote: >> WHY WHY WHY the obsession with one-liners? What is wrong with the good old >> fashioned way? >> >> if cond: >> x = true_value >> else: >> x = false_value >> >> It is easy to read, easy to understand, only one of true_value and >> false_value is evaluated. It isn't a one-liner. Big deal. Anyone would >> think that newlines cost money or that ever time you used one God killed a >> kitten. >> > How do you put this block into list comprehension or generator > expression ? Why the obsession of these block style ? Why do you assume that everything you need for your list comprehension has to go into a single line? Chances are your list comp already calls functions, so just create one more for it to use. py> def describe(cond): ... if cond: ... return "odd" ... else: ... return "even" ... py> L = [describe(n % 2) for n in range(8)] py> L ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd'] One major advantage is that this makes it easier to test your function describe() in isolation, always a good thing. Another advantage is that the idiom "call a function" is extensible to more complex problems: def describe(n): if n < 0: return "negative " + describe(-n) elif n == 0: return "zero" elif n % 2: return "odd" else: return "even" L = [describe(n) for n in range(8)] if much easier to understand and follow than using ternary expressions: # obviously untested L = ["zero" if n == 0 else \ "negative " + ("odd" if n % 2 else "even") if n < 0 else \ "odd" if n % 2 else "even" for n in range(8)] Yes, I've seen ternary expressions nested three and even four deep. I find it fascinating to read Guido's reasoning for introducing a ternary statement. From the PEP here http://www.python.org/peps/pep-0308.html he links to this comment of his: [quote] I think Raymond's example is more properly considered an argument for adding a conditional expression than for removing the current behavior of the and/or shortcut operators; had we had a conditional expression, he wouldn't have tried to use the "x and y or z" syntax that bit him. [end quote] Looking back to Raymond's example here: http://mail.python.org/pipermail/python-dev/2005-September/056510.html [quote] I propose that in Py3.0, the "and" and "or" operators be simplified to always return a Boolean value instead of returning the last evaluated argument. 1) The construct can be error-prone. When an error occurs it can be invisible to the person who wrote it. I got bitten in published code that had survived testing and code review: def real(self): 'Return a vector with the real part of each input element' # do not convert integer inputs to floats return self.map(lambda z: type(z)==types.ComplexType and z.real or z) The code fails silently when z is (0+4i). It took a good while to trace down a user reported error (when Matlab results disagreed with my matrix module results) and determine that the real() method contained an error. Even when traced down, I found it hard to see the error in the code. Now that I know what to look for, it has not happened again, but I do always have to stare hard at any "and/or" group to mentally verify each case. [end quote] Dare I suggest that if Raymond wasn't struggling to force the body of his function real() to be a one-liner, he wouldn't have tried to use the "x and y or z" syntax that bit him? Brevity is not always a virtue. -- Steven. From a.flow at tiscali.it Tue Nov 29 10:30:53 2005 From: a.flow at tiscali.it (And80) Date: 29 Nov 2005 07:30:53 -0800 Subject: xpath support in python 2.4 Message-ID: <1133278253.523473.110800@g49g2000cwa.googlegroups.com> Hi, I would like to use xpath modules in python2.4.... In my local machine I am running python2.3.5 and on the server I run python2.4. I have seen that while on my computer i am able to import xml.xpath, on the server the module seems to not exist. Is it still part of the standard library? if not, what should I use? Thank you in advance, Andrea Fiore From bokr at oz.net Thu Nov 24 10:07:02 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 24 Nov 2005 15:07:02 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> Message-ID: <4385d6ea.640190845@news.oz.net> On Thu, 24 Nov 2005 10:49:59 +0000, Simon Brunning wrote: >On 24 Nov 2005 10:21:51 GMT, Antoon Pardon wrote: >> But only Guido, thinks like Guido and then even Guido may now think >> differently than he thought before. And what if Guido had a bad day >> when he came up with something, should we just adopt to what he >> had in mind without questioning them. > >No one is suggesting that Guido is perfect. But he's consistently a >better judge of language design than I am, and in all likelihood >better than you, too. If you like Python, it's 'cos you like the >decisions he's made over many years. > >Where my first impulse is to think that one of decisions is wrong, >nine times out of ten in time I'll come to find that I was wrong and >he was right. > You have a reservation about that other 10% ? ;-) Regards, Bengt Richter From tim.tadh at gmail.com Mon Nov 28 00:19:53 2005 From: tim.tadh at gmail.com (Tim Henderson) Date: 27 Nov 2005 21:19:53 -0800 Subject: Comparison problem In-Reply-To: References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: <1133155193.939460.65060@g47g2000cwa.googlegroups.com> peter would not the more correct way to do this be short circuit evaluation. somthing along lines of if (len(item) > 0) and (item[0] == '-'): pass seems to be the more correct approach. rather than relying on slicing to return an empty string. For instance suppose you wanted to test to see if than spot contained an empty string. If you used the slice meathod you would be in a pickle. However in this particular case it seems to be clear that the use of .startswith() is the single best approach. From pmartin at snakecard.com Sun Nov 27 00:21:43 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Sat, 26 Nov 2005 23:21:43 -0600 Subject: Crash in python while run from U3 device References: Message-ID: PS: I should add that the U3 device does not actually run Python, but copies it to the PC and launches it: I'm almost certain this is a bug in my code. Help please ! Regards, Philippe Philippe C. Martin wrote: > Hi, > > I am currently porting some of my applications to U3 (www.u3.com) and I do > get a crash in ...objects\frameobject.c: PyFrameObject *back = > tstate->frame. > > The point of the current test is to get a python function called on a U3 > device event. (U3 only work with Windows currently). > > My C stub callback does get called but crashes when it tries to call the > python function. > > > > *************************** > This is the function that registers the callback (actual dll prototype in > header): > *************************** > static PyObject *s_callback=NULL; > /******************************************************************/ > /******************************************************************/ > /* HRESULT dapiRegisterCallback ( HSESSION hSession ,wchar_t* > pszConnectionString ,DAPI_CALLBACK pCallBack,void* pEx ,HCALLBACK* > hCallback) */ > /******************************************************************/ > /******************************************************************/ > > static PyObject *Py_dapiRegisterCallback(PyObject *p_self, PyObject > *p_args) > { > HRESULT l_result; > HSESSION l_hSession; > wchar_t* l_pszConnectionString; > PyObject *l_tmp_cb; > //PyObject cs; > void* l_pEx; > HCALLBACK l_hCallback; > > if > (!PyArg_ParseTuple(p_args,"iuOi",&l_hSession,&l_pszConnectionString,&l_tmp_cb,&l_pEx) > ) > { > BAD_PARAM; > return NULL; > } > //l_pszConnectionString = PyObject_Unicode(cs); > Py_XINCREF(l_tmp_cb); > Py_XDECREF(s_callback); > s_callback=l_tmp_cb; > l_result = > dapiRegisterCallback(l_hSession,l_pszConnectionString,Stub_Callback,l_pEx,&l_hCallback); > > CHECK_RESULT; > > return Py_BuildValue("l",l_hCallback); > > } > > *************************************** > This is the stub callback that crashes: > *************************************** > void _stdcall Stub_Callback(HDEVICE p_dev, DWORD p_event, void *p_pEx) > { > PyObject *l_result; > PyObject *l_arg_list; > > l_arg_list = Py_BuildValue("(iii)", p_dev,p_event,p_pEx); > l_result = PyEval_CallObject(s_callback, l_arg_list); /*No crash > if I > comment this line*/ > Py_DECREF(l_arg_list); > } > > > ***************************************** > This is the python source > ***************************************** > (cs, and s have a correct value ... I think ) > import u3 > def mf(a,b,c): > print 'CB' > > h=u3.dapiRegisterCallback(s, cs, mf, 0) > > > > > Any help _greatly_ appreciated. > > Regards, > > Philippe From strombrg at dcs.nac.uci.edu Mon Nov 7 15:58:23 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 07 Nov 2005 20:58:23 GMT Subject: O_DIRECT on stdin? References: <11mvbsv4lbri8d@corp.supernews.com> <11mvf2a2b8nf54b@corp.supernews.com> Message-ID: On Mon, 07 Nov 2005 20:42:50 +0000, Gordon Burditt wrote: >> [quoted text muted] > > Does O_DIRECT perhaps invoke some of the restrictions of "raw" > device files, where the current offset and transfer size must be a > multiple of some block size? (I don't see any mention of that in > FreeBSD's documentation.) What is the value of blocksize at the > time of the traceback above? I suggest keeping it well under 2G. > > Gordon L. Burditt I'm not aware of such a restriction on O_DIRECT, but then I just learned of O_DIRECT's existence earlier today. :) The value of blocksize at the time of the error should be 1 megabyte. From http Wed Nov 30 01:10:03 2005 From: http (Paul Rubin) Date: 29 Nov 2005 22:10:03 -0800 Subject: General question about Python design goals References: <86k6estfkd.fsf@bhuda.mired.org> Message-ID: <7xu0du64zo.fsf@ruckus.brouhaha.com> Mike Meyer writes: > But a programming language (or UI) is not just a collection of syntax > and and interfaces - it's an implementation. You need to keep in mind > that "practicality beats purity". An awful lot of the time in this newsgroup, "practicality beats purity" translates as "the programmer can just be a lazy slob". > If following POLA makes the implementation an order of magnitude > slower or larger, then you don't follow POLA - at least until you > can do it without that cost. If following POLA costs that much, at least in the kinds of examples we talk about all the time here, something is probably wrong with the implementation (or the design) to begin with. From sdouche at gmail.com Fri Nov 25 12:45:17 2005 From: sdouche at gmail.com (Sebastien Douche) Date: Fri, 25 Nov 2005 18:45:17 +0100 Subject: books: Dive into Python vs Beginning Python In-Reply-To: References: Message-ID: <5e1183fa0511250945k47214697k12996677b0bff640@mail.gmail.com> On 11/25/05, Franz Mueller wrote: > Hi, Hi Franz! :) > which of the following books would you recommend: > "Dive into Python" or "Beginning Python: From Novice to Professional"? Both are very good books but I suggest the latter because more recent. Beginning Python talk python 2.3 and 2.4 : set data structure, generator, iterator... -- S?bastien Douche From exarkun at divmod.com Tue Nov 8 15:49:48 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 8 Nov 2005 15:49:48 -0500 Subject: sqlite3 decode error In-Reply-To: <1324293C-5096-11DA-A8B2-000A27B3B070@eastlink.ca> Message-ID: <20051108204948.10365.1937227228.divmod.quotient.5308@ohm> On Tue, 08 Nov 2005 16:27:25 -0400, David Pratt wrote: >Recently I have run into an issue with sqlite where I encode strings >going into sqlite3 as utf-8. I guess by default sqlite3 is converting >this to unicode since when I try to decode I get an attribute error >like this: > >AttributeError: 'unicode' object has no attribute 'decode' > >The code and data I am preparing is to work on postgres as well a >sqlite so there are a couple of things I could do. I could always >store any data as unicode to any db, or test the data to determine >whether it is a string or unicode type when it comes out of the >database so I can deal with this possibility without errors. I will >likely take the first option but I looking for a simple test to >determine my object type. > >if I do: > > >>>type('maybe string or maybe unicode') > >I get this: > > >>> > >I am looking for something that I can use in a comparison. > >How do I get the type as a string for comparison so I can do something >like > >if type(some_data) == 'unicode': > do some stuff >else: > do something else > You don't actually want the type as a string. What you seem to be leaning towards is the builtin function "isinstance": if isinstance(some_data, unicode): # some stuff elif isinstance(some_data, str): # other stuff ... But I think what you actually want is to be slightly more careful about what you place into SQLite3. If you are storing text data, insert is as a Python unicode string (with no NUL bytes, unfortunately - this is a bug in SQLite3, or maybe the Python bindings, I forget which). If you are storing binary data, insert it as a Python buffer object (eg, buffer('1234')). When you take text data out of the database, you will get unicode objects. When you take bytes out, you will get buffer objects (which you can convert to str objects with str()). You may want to look at Axiom () to see how it handles each of these cases. In particular, the "text" and "bytes" types defined in the attributes module (). By only encoding and decoding at the border between your application and the outside world, and the border between your application and the data, you will eliminate the possibility for a class of bugs where encodings are forgotten, or encoded strings are accidentally combined with unicode strings. Hope this helps, Jean-Paul From apardon at forel.vub.ac.be Thu Nov 24 07:55:07 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Nov 2005 12:55:07 GMT Subject: Making immutable instances References: <0I6dncrRuNnuxBjeRVn-ig@comcast.com> Message-ID: Op 2005-11-24, Mike schreef : > > "Ben Finney" wrote in message > news:dm2rmv$aif$1 at rose.polar.local... >> Howdy all, >> >> How can a (user-defined) class ensure that its instances are >> immutable, like an int or a tuple, without inheriting from those >> types? >> >> What caveats should be observed in making immutable instances? > > IMHO, this is usually (but not always) a mistake. (If you're programming a > missle guidance system, or it makes your program go faster it's not a > mistake :)) > So are PRIVATE, CONST (all types), SEALED, FINAL, etc -- even the best > programmer doesn't foresee what a user will want to do to make best use of > his components, But maybe what the user wants no longer guarantees correct working. > and many a time. I've been annoyed (in Java and MS christelijke vorm er van. > frameworks) by not being able to access/modify/subclass a member/class that > I know is there because it has to be there (or because I can see it in the > debugger), Maybe that it is there is just an implementation detail. > but it's not accessable because the programmer was overly clever > and had been to OOP school. I think hiding something that is essentially an implementation detail is good abstraction and programming practice. > A fine-grained capability architecture married > to the language and runtime where I can declare my own level cleverness to > override the programmer's would be nice, but I think Python's voluntary > DoThis, _DoThisIfYouReallyHaveTo, and __You'dBetterKnowWhatYou'reDoing__ > approach is a better way to go than the undefeatable keyword approach. I disagree. Suppose I have the following code. from module import __take_care__ __private_detail__ = ... I now have two variable that are flaged the same way, but they are not. __take_care__ is a private variable from an other module which I should use with extreme care not to break the other package. __private_detail__ on the other hand is just keeping private data for my own module, which I should care about as just any other variable in my module. It are other modules that should take special care if they should choose to import this variable. That is why I don't think the underscore prefixes are very usefull. They constantly flag to take care with a specific variable, while that variable is nothing special within the module itself. -- Antoon Pardon From cito at online.de Mon Nov 21 12:13:57 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 21 Nov 2005 18:13:57 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132531775.399671.93120@o13g2000cwo.googlegroups.com> <1132570504.077360.187490@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh wrote: > (as an example, on my machine, using Foord's OrderedDict class > on Zwerschke's example, creating the dictionary in the first place > takes 5 times longer than the index approach, and accessing an > item takes 3 times longer. you can in fact recreate the index 6 > times before OrderedDict is faster; if you keep the index around, > the OrderedDict approach never wins...) You're right; I found creating a Larosa/Foord OrderedDict in this example to be even 8 times slower than an ordinary dict. However, two things need to be said here: 1) The dictionary in my exmaple was pretty small (only 3 items), so you are not really measuring the performance of the ordered dict, but mainly the overhead of using a user derived class in comparison with the built-in dict type. And 2) the implementation by Larosa/Foord is very slow and can be easily improved, for instance like that: def __init__(self, init_val = ()): dict.__init__(self, init_val) self.sequence = [x[0] for x in init_val] With this change, creating the ordered dictionary is considerably faster and for an average size dictionary, the factor of 8 pretty quickly converges against 1. But of course, it will always be slower since it is constructed on top of the built-in dict. In end effect, you always have to maintain a sequence *plus* a dictionary, which will be always slower than a sheer dictionary. The ordered dictionary class just hides this uglyness of having to maintain a dictionary plus a sequence, so it's rather an issue of convenience in writing and reading programs than a performance issue. It may be different if the ordered dict would be implemented directly as an ordered hash table in C. -- Christoph From samrobertsmith at gmail.com Sun Nov 20 06:05:34 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 03:05:34 -0800 Subject: about dictionary In-Reply-To: <1132484370.740953.79960@g43g2000cwa.googlegroups.com> References: <1132484370.740953.79960@g43g2000cwa.googlegroups.com> Message-ID: <1d987df30511200305s3c14fc99p677c111150143fe1@mail.gmail.com> On 20 Nov 2005 02:59:30 -0800, bonono at gmail.com wrote: > b = dict([(x,dict()) for x in a]) > Shi Mu wrote: > > I have have the following code: > > >>> a=[3,5,8,0] > > >>> b={} > > >>> > > How I can i assign each item in a as the key in the dictionary b > > simultaneously? > > that is, > > b={3:[],5:[],8:[],0:[]} > > Thanks! Thanks!!! From kay.schluehr at gmx.net Mon Nov 7 02:17:09 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 Nov 2005 23:17:09 -0800 Subject: how to present Python's OO feature in design? References: <1131332809.044523.169900@o13g2000cwo.googlegroups.com> <1131333250.078344.176070@g43g2000cwa.googlegroups.com> <1131333662.653503.285330@g47g2000cwa.googlegroups.com> Message-ID: <1131347829.761335.6780@g43g2000cwa.googlegroups.com> pcmanlin wrote: > because i have a problem that python's oo feature is so great, but > maybe when the project become larger, python's no-declaration cannot > mapping the design to practice? > > I am not sure about it. As far cartoon-ware ( UML ) is concerned note that it is NOT Pythons non-declarativeness but it's dynamicity that makes it hard to picture it's design. Classes in Python are cheap, object structures are even cheaper. That's why UML hardly provides an adequate representation of Python programs and Pythonistas usually don't care a lot about it. Kay From noway at sorry.com Thu Nov 24 19:29:14 2005 From: noway at sorry.com (Giovanni Bajo) Date: Fri, 25 Nov 2005 00:29:14 GMT Subject: Making immutable instances References: <0I6dncrRuNnuxBjeRVn-ig@comcast.com> <--adnfC-d7k9dBjeRVn-ig@comcast.com> Message-ID: Mike wrote: >> There's a big difference. An immutable object has a totally different >> semantic, >> compared to a mutable object. If you document it to be immutable, and >> maybe >> even provide __eq__ /__hash__, adding attributes from it is surely >> an user bug. >> And surely a bug for which I'd expect an exception to be raised. > > Why is it "surely" a bug? It is arguable whether adding new > attributes (vs. changing those that are already there) is, in fact, > mutation. If we agree that *changing* attributes is a bug for those classes, we're already a step beyond in this discussion :) About adding attributes, I agree that it's kind of a grey area. Per-se, there is nothing wrong. My experience is that they give the user a false expectation that the object can be modified. It ends up with an object with attributes which can't be modified because that'd break invariants, and others which are freely modificable. In fact, the only thing that you are adding an attribute to *that* instance, and not to all the *equivalent* instances (by definition of __hash__/__eq__) is questionable and bug-prone. You might end up *thinking* you have that very instance around, while you don't. In fact, with immutable objects, you are not supposed to think in terms of instances, but rather of values. When I see a string like "foobar" I don't care if it's the same instance of a "foobar" I saw before. If I could add an attribute to "foobar", I might end up believing that whenever I see a "foobar" around, it will have that attribute. As you said, Python has rich data structures which lets you still find good ways to carry around additional information. So why trying so hard to get into trouble? > It sounds like what you may want are opaque objects where you can > control access better No that's a different issue. One example of my immutable classes is Point2D (two attributes: x/y). Having it immutable gives it many useful properties, such as a real value semantic. -- Giovanni Bajo From smithsm at samuelsmith.org Mon Nov 21 09:36:03 2005 From: smithsm at samuelsmith.org (Samuel M. Smith) Date: Mon, 21 Nov 2005 07:36:03 -0700 Subject: Configure failing why? In-Reply-To: References: Message-ID: <7F4DB984-5C1E-406B-8398-1EB1FB64D583@samuelsmith.org> I found a workaround,that is, to disable attribute caching using the "noac" nfs option. #These two worked on tiger 10.4.3 exec -c "console=ttyAM0,115200 ip=10.0.2.155:10.0.2.150:10.0.2.1:255.255.255.0:ts7250 nfsroot=10.0.2.150:/Data/nfsroot,noac" #fstab entry they have to match 10.0.2.150:/Data/nfsroot/ / nfs noac,noauto 0 0 #If use noac,sync,dirsync then gcc does not work From grante at visi.com Thu Nov 10 10:58:09 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 10 Nov 2005 15:58:09 -0000 Subject: A Tcl/Tk programmer learns Python--any advice? References: <1131502967.138632.94840@g47g2000cwa.googlegroups.com> <1131552039.774736.298520@z14g2000cwz.googlegroups.com> Message-ID: <11n6rghkjpme346@corp.supernews.com> On 2005-11-10, Svenn Are Bjerkem wrote: > (and python can not do "set result [exec someprog << $input]" > as far as I know) I don't remember Tcl very well, but doesn't this do the same thing? result = os.popen('someprog','r').read() -- Grant Edwards grante Yow! I have a VISION! It's at a RANCID double-FISHWICH on visi.com an ENRICHED BUN!! From claird at lairds.us Mon Nov 28 14:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 28 Nov 2005 19:08:04 GMT Subject: How to write an API for a Python application? References: <437af434@news.bezeqint.net> <1h6aek5.7u27ahsflnq7N%aleax@mail.comcast.net> Message-ID: In article <1h6aek5.7u27ahsflnq7N%aleax at mail.comcast.net>, Alex Martelli wrote: . . . >Note also that you can freely download all of the code in my book as >http://examples.oreilly.com/pythonian/pythonian-examples.zip (it's just >36 KB). In that same chapter you will find several implementations of . . . 1. Private e-mail to all the addresses I have for you has been bouncing. 2. Both 19-7 and 19-8 in the ZIP I found at that URL have a curious typo that I'll describe this way: s/_ _/__/g From onurb at xiludom.gro Fri Nov 25 07:24:15 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 25 Nov 2005 13:24:15 +0100 Subject: books: Dive into Python vs Beginning Python In-Reply-To: References: Message-ID: <43870270$0$26543$636a15ce@news.free.fr> Franz Mueller wrote: > Hi, > > which of the following books would you recommend: > "Dive into Python" or "Beginning Python: From Novice to Professional"? I can't recommand the second since I've never read it. But you can freely make your own opinion on the first, since it's freely available online. > I'm an experienced C++-programmer who wants to take a look at Python. Then I'd say that Dive into Python may be a good choice. Welcome BTW -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From yuxi at ece.gatech.edu Thu Nov 10 20:14:14 2005 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Thu, 10 Nov 2005 20:14:14 -0500 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> Message-ID: Bill Mill wrote: > Your only solution, then, is to write unpopular code. Because, as Alex > said, it will otherwise be broken into. Let's look at two very popular > pieces of code: Half-Life 2 and Windows XP. How are they secured? > Previous version of these software products used sophisticated > client-side programming to try and be secure, but the security was > nonexistant. Users share keys and cracks with each other. and Mike Meyer wrote: > What makes you think this is the case? There are ways to distribute > Python modules so that the user can't just open them in a text > editor. There are also ways to get cryptographic security for > distributed modules. Yes, if you use the same methods you use in C++, > it's "much harder". But by the same token, if you tried to use the > methods you'd use in a Python program in C++, you'd find that the C++ > version was "much harder". > > Of course, as Alex pointed out, all of these are just keeping honest > people honest. The crooks have all the advantages in this game, so you > really can't expect to win. Funny you should mention Half-Life 2. I actually went out and bought Half-Life 2 from the store instead of waiting for a crack to be released (the unique scheme they used meant that crackers will take a little longer than usual). I really wanted to play this game (i.e., it's very popular) and couldn't wait. My brother is bugged by Civilization IV's copy protection. A couple of days ago, after consulting me on what other options he could try, he finally said in frustration, "Maybe I should go buy the game." This is a personal anecdote, but I'm sure it applies to at least some people. Obviously I'm not an honest person. But I'm not so against spending money on software that I won't buy it if there's a pretty good copy protection system on it. The "keeping honest people honest" argument is simplistic and as Ben said, "black and white thinking". Ben's analogy of the house is not a perfect example, but it's still a fair one. You know that if some one really wants to break into your house, he will get in, regardless of your sophisticated laser trip wire system, ex-SAS guards, and genetically-engineered guard dogs. But as long as the cost of protection is less than the cost of the item you're protecting (multiplied by the relevant probabilities, factoring recurring costs, etc), it's worthwhile to spend money on protection. If that fails, then you will of course fall back on the law, but you still try to prevent it from happening in the first place. I do believe that code obfuscation and copy protection measures work, to a limited extent. Few software companies believe that their copy protection will be uncrackable (though their marketing droids may say otherwise), but are most willing to invest in it to at least temporarily stave off the piracy. Distribution of python modules as compiled bytecode is a limited form of obfuscation. Some believe it's enough. But if there's a free obfuscator out there than can increase the difficulty of reverse engineering, why not use that too? Costs you nothing, and may get you a customer or two more before some one manages to crack that. Obfuscation has it's place. It's not the final solution for software protection (and there probably isn't one), but it is one more lock you can use to deter or delay theives. You can't expect to win against determined theives, but you can remove as many advantages that they have. > Now, both of these programs require verification (phone and/or web) to > be used. The only truly secure method of assuring that they're not > used in ways you don't intend is to require the user to contact you to > use it, and that's a deal with the devil. One you might need to make > if security is that important to you, as Microsoft and Valve have > decided it is, but it's a deal with the devil nonetheless. This seems to be opposite to what you said in the previous paragraph. Contacting and verifying with the company every time you use the software is obviously not "the only truly secure method", since there are cracks and keys floating around. It is also not quite as evil as it may seem, since authorization is only required on initial use (and online gaming). From donn at u.washington.edu Thu Nov 10 16:16:19 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 10 Nov 2005 13:16:19 -0800 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> Message-ID: In article <863bm46zbh.fsf at bhuda.mired.org>, Mike Meyer wrote: ... > Most OO languages do the name/variable thing, but some of the popular > ones aren't consistent about it, giving some types "special" status, > so that sometimes "a = b" causes b to be copied onto a, and sometimes > it causes a to become a pointer to b. I find a consistent approach is > preferable. Who wouldn't. > Most OO languages also have the mutable/immutable object thing. The > set of which objects are immutable changes from language to > language. It's really only relevant in this case because the solution > to "I want to change an alias" issue involves using a mutable object. Yes, and furthermore it's only vaguely relevant. I mean, it really requires a particular kind of mutability, where one object can store a reference to another. That's easy to find in core object types, and of course it is a kind of mutability, but it isn't the definition of mutable. So we drag out this terminology, that neither clearly nor accurately describes the functionality we have in mind, and then we make some vague or even wrong statement about its relationship to the issue. It has been going on for years, usually I believe from people who understand quite well how it really works. Donn Cave, donn at u.washington.edu From bonono at gmail.com Sat Nov 5 05:39:09 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 5 Nov 2005 02:39:09 -0800 Subject: Using Which Version of Linux In-Reply-To: References: Message-ID: <1131187149.913377.251590@z14g2000cwz.googlegroups.com> They are all the same as you don't have specific requirements mentioned. Based on the way you ask, I would say some debian derivative like ubuntu. debian is not programmer friendly but admin friendly I would say. In general programmer friendly distro to me would mean install everything one can possiblity think of by default so everything is at hand for use. Never tried the new solaris so I have no idea but I had some problem when installed their old x86 a few years back however things may have changed a lot. I tried briefly with fedora but its packaging system is not up to par, comparing with debian. However, you get newer things in fedora, in general. Fedora has the advantage that it works better with commercial stuff like Oracle/Sybase. I had problem making Sybase installed under debian(the reason why I tried fedora). blah at blah.blah wrote: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. > -- > * Posted with NewsLeecher v3.0 Beta 7 > * http://www.newsleecher.com/?usenet From fredrik at pythonware.com Sat Nov 12 12:31:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Nov 2005 18:31:38 +0100 Subject: newbie how do I interpret this? References: <1131815443.308190.198850@g14g2000cwa.googlegroups.com> Message-ID: bobueland at yahoo.com wrote: > >>> help(m.groups) > Help on built-in function groups: > > groups(...) > > >>> > > My question is. How do I interpret the hiven help info > groups(...) > > alt1. Tough luck. There's no help. People are to busy to write > reference manuals. they're busy writing reference manuals, you mean: http://docs.python.org/lib/match-objects.html > alt 2. There are no parameters. The only possibility is m.groups() in this case, that happens to be the most common way to use the method. > alt3. Something else the words "built-in function" means that the function is im- plemented in C, and is therefore outside the reach of Python's introspection mechanisms. In this case, there don't seem to be any custom docstring associated with this method, so the above is all help() can tell you at the moment. This may of course change in future releases. From mwm at mired.org Thu Nov 10 15:08:18 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 15:08:18 -0500 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> Message-ID: <863bm46zbh.fsf@bhuda.mired.org> [Context recovered from top posting.] "bonono at gmail.com" writes: > Daniel Crespo wrote: >> Well, I hope that newcomers to Python don't confuse himselves :) > This mutable/immutable object and name/variable is confusing. Only if you have to overcome a conviction that variables behave in a different way. If you've never seen them behave another way, or have already gotten used to this model from another language (it dates back to the 60s, if not the late 50s), then it's no problem. I'm sure the problem exists in the opposite direction, except that few people travel that route. Most OO languages do the name/variable thing, but some of the popular ones aren't consistent about it, giving some types "special" status, so that sometimes "a = b" causes b to be copied onto a, and sometimes it causes a to become a pointer to b. I find a consistent approach is preferable. Most OO languages also have the mutable/immutable object thing. The set of which objects are immutable changes from language to language. It's really only relevant in this case because the solution to "I want to change an alias" issue involves using a mutable object. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From grig.gheorghiu at gmail.com Thu Nov 10 10:36:26 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 10 Nov 2005 07:36:26 -0800 Subject: python + ODBC + Oracle + MySQL - money In-Reply-To: <1131631172.260603.201050@o13g2000cwo.googlegroups.com> References: <1131631172.260603.201050@o13g2000cwo.googlegroups.com> Message-ID: <1131636986.824373.178720@g43g2000cwa.googlegroups.com> In my testing, I need to connect to Oracle, SQL Server and DB2 on various platforms. I have a base class with all the common code, and derived classes for each specific database type using specific database modules such as cxOracle, mxODBC and pyDB2. The derived classes are pretty thin, containing only some syntax peculiarities for a given database type. The code is clean and portable. Grig From steve at holdenweb.com Wed Nov 30 12:05:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 Nov 2005 17:05:28 +0000 Subject: python speed In-Reply-To: <438db382$0$67257$157c6196@dreader2.cybercity.dk> References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133358884.407477.219560@g47g2000cwa.googlegroups.com> <438db382$0$67257$157c6196@dreader2.cybercity.dk> Message-ID: David Rasmussen wrote: > Harald Armin Massa wrote: > >>Dr. Armin Rigo has some mathematical proof, that High Level Languages >>like esp. Python are able to be faster than low level code like >>Fortran, C or assembly. >> > > > Faster than assembly? LOL... :) > I don't see why this is so funny. A good C compiler with optimization typically produces better code than an equivalent assembly language program. As compilation techniques improve this gap is likely to widen. There's less and less reason to use assembler language with each passing year. 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 cito at online.de Tue Nov 22 04:06:07 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 10:06:07 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <4382592b.411391199@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> Message-ID: Bengt Richter schrieb: > Ok, so if not in the standard library, what is the problem? Can't find what > you want with google and PyPI etc.? Or haven't really settled on what your > _requirements_ are? That seems to be the primary problem people who complain > with "why no sprollificator mode?" questions. What I don't understand is why legitimate questions such as "why are there no ordered dictionaries" are immediately interpreted as *complaints* and not just as questions. If I ask such a question, I am not complaining but trying to simply figure out *why* there is no such thing. Probably there are reasons and all I want to know is find these reasons and learn a little bit more about Python in doing so. Why can't such questions be discussed in a factual, calm and friendly way? > They don't know what they really mean when it comes down to a DYFR > (Define Your Felicitous Requirements) challenge. I don't think that this was true in this case, and even if this is the outcome, those who asked the question will have learned something. I think a discussion group is not there for only presenting mature, sophisticated thoughts and concepts, but also for "thinking loud" together with other about these issues. We all know that clarifying our thoughts works often best if you discuss them with others. And I think that's one purpose of discussion lists. Asking questions should not be immediately be discouraged, even silly questions. If it is really a FAQ, you can simply point to the FAQ or add the answer in the FAQ list if it is missing there. -- Chris From cito at online.de Wed Nov 23 16:34:28 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 22:34:28 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: >> I think it would be probably the best to hide the keys list from the >> public, but to provide list methods for reordering them (sorting, >> slicing etc.). Tom Anderson wrote: > I'm not too keen on this - there is conceptually a list here, even if > it's one with unusual constraints, so there should be a list i can > manipulate in code, and which should of course be bound by those > constraints. Think of it similar as the case of an ordinary dictionary: There is conceptually a set here (the set of keys), but you cannot manipulate it directly, but only through the according dictionary methods. For an ordedred dictionary, there is conceptually a list (or more specifically a unique list). Again you should not manipulate it directly, but only through methods of the ordered dictionary. This sounds at first more complicated, but is in reality more easy. For instance, if I want to put the last two keys of an ordered dict d at the beginning, I would do it as d = d[:-2] + d[-2:]. With the list attribute (called "sequence" in odict, you would have to write: d.sequence = d.sequence[:-2] + d.sequence[-2:]. This is not only longer to write down, but you also have to know that the name of the attribute is "sequence". Python's strength is that you don't have to keep many details in mind because it has a small "basic vocabulary" and orthogonal use. I prefer the ordered dictionary does not introduce new concepts or attributes if everything can be done intuitively with the existing Python methods and operators. -- Christoph From kent37 at tds.net Tue Nov 1 22:35:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 01 Nov 2005 22:35:16 -0500 Subject: Object-Relational Mapping API for Python In-Reply-To: <1130872943.306455.129550@g47g2000cwa.googlegroups.com> References: <1130872943.306455.129550@g47g2000cwa.googlegroups.com> Message-ID: <436831af$1_2@newspeer2.tds.net> Aquarius wrote: > I explored Java's Hibernate a bit and I was intrigued by how you can > map entity objects to database tables, preserving all the relations and > constraits. I am interested if there is something like this for Python > - I noticed some APIs in the "Cheeseshop", but most of them were alpha, > better, or seemed to be forsaken a long time ago. Can you recommend me > anything? > SQLObject, PyDO, Durus and Django's database API. Kent From s99999999s2003 at yahoo.com Fri Nov 11 02:45:54 2005 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 10 Nov 2005 23:45:54 -0800 Subject: modify dictionary while iterating Message-ID: <1131695154.274238.113690@f14g2000cwb.googlegroups.com> hi I wish to pop/del some items out of dictionary while iterating over it. a = { 'a':1, 'b':2 } for k, v in a.iteritems(): if v==2: del a[k] the output say RuntimeError: dictionary changed size during iteration how can i suppress this message in an actual script and still get the final value of the dict? is it something like try/except/else statment? try: for v,k in a.iteritems(): if v==something: del a[k] except RuntimeError: < don't know what to do here> else: < should i include this part ? > what other ways can i do this ? thanks for any help. From johnandsarah at estragon.freeserve.co.uk Tue Nov 22 13:09:44 2005 From: johnandsarah at estragon.freeserve.co.uk (John Perks and Sarah Mount) Date: Tue, 22 Nov 2005 18:09:44 -0000 Subject: wxPython Licence vs GPL Message-ID: we have some Python code we're planning to GPL. However, bits of it were cut&pasted from some wxPython-licenced code to use as a starting point for implementation. It is possible that some fragments of this code remains unchanged at the end. How should we refer to this in terms of copyright statements and bundled Licence files? Is there, say, a standard wording to be appended to the GPL header in each source file? Does the original author need to be named as one of the copyright holders, or that ours is a derivative work from his? Which of these would be required under the terms of the Licence, and which by standard practice / courtesy? (This assumes the wxPython Licence is compatible with the GPL -- if not, do we just cosmetically change any remaining lines, so none remain from the orignal?) Thanks John From __peter__ at web.de Wed Nov 23 04:45:36 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Nov 2005 10:45:36 +0100 Subject: sort the list References: <1132737773.874155.322600@g47g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Duncan Booth wrote: >> e.g. it is stable when you reverse the order: >> >> >>> lst = [[4,1],[4,2],[9,3],[5,4],[2,5]] >> >>> list(reversed([ x[-1] for x in sorted([ (x[0],x) for x in lst ]) ])) >> [[9, 3], [5, 4], [4, 2], [4, 1], [2, 5]] >> >>> l1 = list(lst) >> >>> l1.sort(key=operator.itemgetter(0), reverse=True) >> >>> l1 >> [[9, 3], [5, 4], [4, 1], [4, 2], [2, 5]] >> > Just curious, which one is supposed to be the right answer ? and why > the second one is preferable over the first one(if both is right, > assume we only care about x[0]). > > Of course, there is no reason to DIY when the built-in can do the job. "Stability" means items with the same key preserve their relative position. In the original list of the example [4, 1] and [4, 2] both have the same key. Therefore [4, 1] should stay before [4, 2], so the second is the "right" answer. The practical advantage is that if e. g. you sort items first by color and then by size, items of the same size will appear sorted by color. In particular, sorting a list by the same key a second time does not change the list. Peter From aahz at pythoncraft.com Mon Nov 7 23:21:24 2005 From: aahz at pythoncraft.com (Aahz) Date: Mon, 7 Nov 2005 20:21:24 -0800 Subject: BayPIGgies: November 10, 7:30pm (Google) Message-ID: <20051108042124.GA245@panix.com> The next meeting of BayPIGgies will be Thurs, November at 7:30pm at Google (Bldg 43, room Tunis). Hasan Diwan will demonstrate a prototype GPS system written in Python. Let's all work to convince him that he doesn't need to rewrite it in Java! BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://www.baypiggies.net/ Before the meeting, we sometimes meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: The meeting agenda for December 8 has been set. Please send e-mail to baypiggies at baypiggies.net if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair From guy.lateur at b-b.be Thu Nov 24 11:19:34 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 24 Nov 2005 16:19:34 GMT Subject: Locking a file under Windows References: Message-ID: Thank you, Tim. The portalocker code seems to prevent reading while the file is locked for writing, but it doesn't seem to prevent multiple writes (nor multiple exclusive locks, for that matter). I guess it'd be better if I use the second suggestion, i.e. temporarily renaming the file for writing, and renaming it back to unlock it. Cheers, g "Tim Golden" schreef in bericht news:mailman.1160.1132845093.18701.python-list at python.org... Might be worth looking in the Python Cookbook area. I seem to remember several recipes to do this kind of thing cross-platform. eg, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 Also the pywin32 docs come with a flock-style example. Hope one of the two can help you. TJG From casevh at comcast.net Tue Nov 8 00:16:06 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 7 Nov 2005 21:16:06 -0800 Subject: gmpy 1.01 rc near... anybody wanna test> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> <1131349548.589908.164300@o13g2000cwo.googlegroups.com> <1h5nbma.125lez717a1zj2N%aleax@mail.comcast.net> Message-ID: <1131426966.939823.231830@z14g2000cwz.googlegroups.com> Everything works fine with v1.16. I'm sure I was doing something wrong. I shouldn't be testing that late at night. ;-) It looks like the warning about "tp_compare" has been fixed. I will try to build a version for Windows, but that may take me a day or two. Thanks for the updates to gmpy! Case From christopherlmarshall at yahoo.com Thu Nov 10 17:53:04 2005 From: christopherlmarshall at yahoo.com (christopherlmarshall at yahoo.com) Date: 10 Nov 2005 14:53:04 -0800 Subject: derived / base class name conflicts Message-ID: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> Suppose you want to write a subclass of some existing class you are importing from a module you didn't write and that you don't want to study the internals of, and you want to define a data member i in your constructor. As in the following: from module1 import A class B(A): def __init__(self): A.__init__(self) self.i= 0 b= B() Now, 'i' might have already been defined by A or by the call to A.__init__() so if you define it without knowing that, you could be changing the behavior of A's methods in unknown ways, which is obviously a bad thing. One way to avoid this is to run the following program to clear the name 'i' first: from module1 import A a= A() print a.i If you get an AttributeError, you know the name 'i' is safe to use. If you actually get some sort of report from the print statement, then you will know that 'i' is not safe to use. This strikes me as a rather odd procedure to go through, but I don't see any way around it. It there some other way to handle this issue? Do I actually need to study the sources for / implementation of Tkinter.Canvas before I can safely subclass it (and assign attributes to an instance of the subclass) or clear attribute names as I outlined above? Chris Marshall From twic at urchin.earth.li Fri Nov 25 14:37:01 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 25 Nov 2005 19:37:01 +0000 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> Message-ID: On Wed, 23 Nov 2005, Christoph Zwerschke wrote: > Alex Martelli wrote: > >> However, since Christoph himself just misclassified C++'s std::map as >> "ordered" (it would be "sorted" in this new terminology he's now >> introducing), it seems obvious that the terminological confusion is >> rife. > > Speaking about "ordered" and "sorted" in the context of collections is > not a new terminology I am introducing, but seems to be pretty common in > computer science This is quite true. I haven't seen any evidence for 'rife' misunderstanding of these terms. That said ... > Perhaps Pythonists are not used to that terminology, since they use the > term "list" for an "ordered collection". An ordered dictionary is a > dictionary whose keys are a (unique) list. Sometimes it is also called a > "sequence" Maybe we should call it a 'sequenced dictionary' to fit better with pythonic terminology? tom -- YOU HAVE NO CHANCE TO ARRIVE MAKE ALTERNATIVE TRAVEL ARRANGEMENTS. -- Robin May From steve at holdenweb.com Mon Nov 7 08:10:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 Nov 2005 13:10:32 +0000 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > Op 2005-11-05, Steven D'Aprano schreef : > >>On Fri, 04 Nov 2005 12:10:11 +0000, Antoon Pardon wrote: >> >> >>>>There are good usage cases for the current inheritance behaviour. I asked >>>>before what usage case or cases you have for your desired behaviour, and >>>>you haven't answered. Perhaps you missed the question? Perhaps you haven't >>>>had a chance to reply yet? Or perhaps you have no usage case for the >>>>behaviour you want. >>> >>>There are good use cases for a lot of things python doesn't provide. >>>There are good use cases for writable closures, but python doesn't >>>provide it, shrug, I can live with that. Use cases is a red herring >>>here. >> >>Is that a round-about way of saying that you really have no idea of >>whether, how or when your proposed behaviour would be useful? > > > I am not proposing specific behaviour. Because if I do, you will > just try to argue how much worst my proposed behaviour is. > > Whether or not I can come up with a better proposal is irrelevant > to how sane the current behaviour is. > If you can't provide a superior alternative then you have little right to be questioning the present behavior. Honestly, you are like a child with a whistle who keeps blowing the whistle to the annoyance of all around it simply because it likes being able to make the noise, and causing the annoyance. > >>Personally, I think that when you are proposing a major change to a >>language that would break the way inheritance works, there should be more >>benefits to the new way than the old way. > > > How many times do I have to repeat myself. I'm not proposing a change > to the language. > So you have a clear impression that Python's current behavior is unsatisfactory enough to be called "unsane" which, when challenged, you insist simply means not at the extreme end of some imaginary sanity scale you have constructed for the purpose if bending English to your will. And you refuse to propose anything further towards the sane end of the scale because people will try to argue that your proposal would be worse than the existing behavior. Good grief, I though I was dealing with an adult here, but I must be mistaken. > >>>>Some things are a matter of taste: should CPython prefer <> or != for not >>>>equal? Some things are a matter of objective fact: should CPython use a >>>>byte-code compiler and virtual machine, or a 1970s style interpreter that >>>>interprets the source code directly? >>>> >>>>The behaviour you are calling "insane" is partly a matter of taste, but it >>>>is mostly a matter of objective fact. I believe that the standard >>>>model for inheritance that you call insane is rational because it is >>>>useful in far more potential and actual pieces of code than the behaviour >>>>you prefer -- and the designers of (almost?) all OO languages seem to >>>>agree with me. >>> >>>I didn't call the model for inheritance insane. >> Well you are repeatedly call one aspect of the Python inheritance model insane. You appear to feel that repetition of an argument will make it more true, which is sadly not the case. >>Antoon, I've been pedanted at by experts, and you ain't one. The behaviour >>which you repeatedly described as not sane implements the model for >>inheritance. The fact that you never explicitly said "the standard OO >>model of inheritance" cuts no ice with me, not when you've written >>multiple posts saying that the behaviour of that standard inheritance >>model is not sane. > > > I haven't written that once. You may think that you can imply it from > what I wrote, but then that is your inferance and not my words. > Nonsense. > >>>>The standard behaviour makes it easy for code to do the right thing in >>>>more cases, without the developer taking any special steps, and in the >>>>few cases where it doesn't do the right thing (e.g. when the behaviour >>>>you want is for all instances to share state) it is easy to work >>>>around. By contrast, the behaviour you want seems to be of very limited >>>>usefulness, and it makes it difficult to do the expected thing in >>>>almost all cases, and work-arounds are complex and easy to get wrong. >>> >>>Please don't make this about what I *want*. I don't want anything. I >>>just noted that one and the same reference can be processed multiple >>>times by the python machinery, resulting in that same reference >>>referencing differnt variables at the same time and stated that that was >>>unsane behaviour. >> But you clearly don't perceive this as being related to Python's inheritance mechanism, presumably because you aren't prepared to accept that an instance inherits names from its class just like a class inherits names from its superclass. >>"Unsane" now? >> >>Heaven forbid that I should criticise people for inventing new words, but >>how precisely is unsane different from insane? In standard English, >>something which is not sane is insane. > > > Well maybe English works differently from dutch, but I thought there > were a whole lot of gradation between sane and insane. And not being > sane IMO just means not being at one end of the extreme while being > insane meant to be at the other end of the extreme. > > So when something doesn't make complete sense, instead of it making > no sense at all, I would think that wording it as unsane instead of > insane resembles best what I intended to mean. > Ah, so Python isn't the only language you find insufficiently expressive. I normally give some leeway to those whose first language isn't English, but this particular bloody-mindedness has gone on long enough. I'd call your behavior imhelpful here. So, are we talking about 0.1% insane, 10% insane or 90% insane. For someone who is so pedantic you are being insanely vague here. You can hardly blame people for concluding you just like the sound of your own voice (metaphorically speaking). > >>If you're just trolling, you've done a great job of it because you fooled >>me well and good. But if you are serious in your criticism about the >>behaviour, then stop mucking about and tell us what the behaviour should >>be. Otherwise your criticism isn't going to have any practical effect on >>the language at all. > > > I wasn't trolling. I just threw in an off hand remark. That you got so > heated up about that remark is not my responsibility. I'm not trolling > because I'm willing to defend my remark and I don't intend to get > people to get heated up about it. I just don't hold back because > people may get heated up about it. > The defense of your original remark implies very strongly that it wasn't offhand, and that you are indeed trolling. Hence the reduction in the frequency of my replies. You make it more and more difficult to take you seriously. Particularly since you have now resorted to a defense which involves refusing to define a non-existent word in any but the vaguest terms - you are trying to specify a position on the imaginary continuum of sanity, but you don't say how close to which end you are trying to specify. This puts you somewhere between "barmy" and "crackpot" on my own personal scale. > >>If you are serious about wanting the behaviour changed, and not just >>whining, then somebody has to come up with an alternative behaviour that >>is better. > > > If I would be whining I would want the behaviour changed. I would just > keep complaining about it until someone else would have changed it. > Instead you just keep complaining about it, full stop. Since we are all now fully aware of your opinions, couldn't you just shut up, or do we have to send you to your room without any supper? Whine, whine, whine. > Sure I would prefer it changed, but it is not that I *want* it to > change. I'll happily continue with python if it doesn't change. > That's sort of a pity. At this stage I'd recommend Ruby just to be rid of the incessant twaddle you come up with to defend your throwaway ideas. > Maybe when someone mentions something negative about python, > you shouldn't translate that into someone demanding a change > in python. > > >>If not you, then who? Most of the folks who have commented on >>this thread seem to like the existing behaviour. > > > Well fine, in that case it won't even change if I do come up with > an alternative proposal. So why should I bother? > Absolutely no reason at all. It's already transparently obvious that you don't have a better alternative and you continue to troll simply because it validates your particular (and increasingly peculiar) needs. Every time I reply to you my spell checker looks at your name and shows me a dialog with an "ignore all" button on it. I have this increasing suspicion that it's trying to tell me something. 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 jstroud at mbi.ucla.edu Tue Nov 8 00:03:24 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 7 Nov 2005 21:03:24 -0800 Subject: overloading *something In-Reply-To: <1h5obt1.ml6ib01swfdhbN%aleax@mail.comcast.net> References: <1h5obt1.ml6ib01swfdhbN%aleax@mail.comcast.net> Message-ID: <200511072103.24805.jstroud@mbi.ucla.edu> On Monday 07 November 2005 20:36, Alex Martelli wrote: > > > I've looked at getitem, getslice, and iter. What is it if not one of > > > these? > > Obviously James hadn't looked at __iter__ in the RIGHT way! I was attempting to re-define iter of a subclassed list, to find the "magic" method, but it didn't work. I'm not sure if "wrong" and "right" apply here: py> class NewList(list): ... def __iter__(self): ... return iter([8,9,10]) ... py> py> n = NewList([1,2,3]) py> py> def doit(*args): ... print args ... py> doit(*n) (1, 2, 3) py> for x in iter(n): ... print x ... 8 9 10 -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fredrik at pythonware.com Wed Nov 16 08:13:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 14:13:34 +0100 Subject: initialising a list of lists References: Message-ID: Peter Kleiweg wrote: > This does not what I want it to do: > > >>> a = [[]] * 6 > >>> a[3].append('X') > >>> a > [['X'], ['X'], ['X'], ['X'], ['X'], ['X']] > > This does what I want: > > >>> b = [[] for _ in range(6)] > >>> b[3].append('X') > >>> b > [[], [], [], ['X'], [], []] > > The first is clear and wrong. The second is hairy and right. > Is there a way to do it clear and right? http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list From rrr at ronadam.com Tue Nov 8 19:57:35 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 09 Nov 2005 00:57:35 GMT Subject: which feature of python do you like most? In-Reply-To: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: <3Qbcf.186717$xl6.41652@tornado.tampabay.rr.com> zelzel.zsu at gmail.com wrote: > which feature of python do you like most? > > I've heard from people that python is very useful. > Many people switch from perl to python because they like it more. > > I am quite familiar with perl, I've don't lots of code in perl. > Now, I was curious and interested in the python people. > They certainly made their best choice from perl to python. I wrote a few programs in perl that I thought were quite nice. I loved the flexibility and powerful expressions. But then when I went back to those programs several months later, I couldn't (easily) figure out what I did. That was enough to turn me off of perl. > but i have no interesting python experence before, thought i've read a > few chapters > of a python tutorial book. The things are much like the perl one. > > I have no idea why people are so facinating with python. > So I post this question: What do you use in your dairy work with > python? > what is the thing that python makes you happy? What I like most about Python is how many times the best way to solve a problem turns out to be how I thought of doing it in the first place. For example, instead of using index's and arrays and defining structures for handling data, I can usually just iterate through a list of stuff and make changes as I go. Which is most likely how .... see above. ;-) > I certainly don't want to miss a language if it's so great! > can anyone share your happy experence with python? > From steve at holdenweb.com Wed Nov 2 11:57:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Nov 2005 16:57:05 +0000 Subject: About the Python Expert In-Reply-To: References: Message-ID: <4368EFE1.1080405@holdenweb.com> blah at blah.blah wrote: > Hey, i didnt say i need an expert. wel i did... anyways, i m just > saying that Fan is not a good python programmer, he doesnt know enough > python to help those who have joined his group, i know its askin a > lot, and i m not askin for a private tutor, just someone(s), to pop > into the group, see the discussions and help the people. but it is ur > decision. If the guy who started the group isn't an appropriate mentor then a more advanced programmer would probably find it irritating to have to correct his mistakes. I'd still recommend that you direct the members to the tutor list rather than trying to shore up an ineffective initiative. Good luck either way. 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 bokr at oz.net Tue Nov 29 13:37:14 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 29 Nov 2005 18:37:14 GMT Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> <438c2f4f.211175043@news.oz.net> Message-ID: <438c915a.236274514@news.oz.net> On Tue, 29 Nov 2005 09:26:53 -0600, jepler at unpythonic.net wrote: > >--cvVnyQ+4j833TQvp >Content-Type: text/plain; charset=us-ascii >Content-Disposition: inline > >On Tue, Nov 29, 2005 at 10:41:13AM +0000, Bengt Richter wrote: >> Seems like str.__mod__ could take an arbitary (BTW, matching length, necessarily? >> Or just long enough?) iterable in place of a tuple, just like it can take >> an arbitrary mapping object in place of a dict for e.g. '%(name)s'% {'name':''} > >What, and break reams of perfectly working code? > There you go again ;-) There I went again, d'oh ;-/ >s = set([1, 2, 3]) >t = [4, 5, 6] >u = "qwerty" >v = iter([None]) >print "The set is: %s" % s >print "The list is: %s" % t >print "The string is: %s" % u >print "The iterable is: %s" % v I guess I could argue for an iterable with a next method in single-arg form just having its next method called to get successive arguments. If you wanted the above effect for v, you would have to do the same as you now do to print a single tuple argument, i.e., you wrap it in a 1-tuple like (v,) This might even let you define an object that has both __getitem__ and next methods for mixing formats like '%(first)s %s %(third)s' % map_n_next_object reminder... >>> tup = (1, 2, 3) >>> print "The tuple is: %s" % tup Traceback (most recent call last): File "", line 1, in ? TypeError: not all arguments converted during string formatting >>> print "The tuple is: %s" % tup, Traceback (most recent call last): File "", line 1, in ? TypeError: not all arguments converted during string formatting >>> print "The tuple is: %s" % (tup,) The tuple is: (1, 2, 3) But, yeah, it is handy to pass a single non-tuple arg. But iterables as iterators have possibilities too, e.g. maybe it = iter(seq) print 'From %s: %s' % (it,) print 'Unpacked: %s %s' % it # as if (it.next(). it.next()) print 'Next two: %s %s' % it # ditto You will get StopIteration if you run out of args though, so maybe str.__mod__ should catch that and convert it to its "TypeError: not enough arguments for format string" when/if it finally happens. Regards, Bengt Richter From kent37 at tds.net Mon Nov 7 19:13:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 19:13:31 -0500 Subject: Regular expression question -- exclude substring In-Reply-To: <1131405834.093144.206510@g43g2000cwa.googlegroups.com> References: <1131405834.093144.206510@g43g2000cwa.googlegroups.com> Message-ID: <436feb4b$1_2@newspeer2.tds.net> dreamerbin at gmail.com wrote: > Hi, > > I'm having trouble extracting substrings using regular expression. Here > is my problem: > > Want to find the substring that is immediately before a given > substring. For example: from > "00 noise1 01 noise2 00 target 01 target_mark", > want to get > "00 target 01" > which is before > "target_mark". > My regular expression > "(00.*?01) target_mark" > will extract > "00 noise1 01 noise2 00 target 01". If there is a character that can't appear in the bit between the numbers then use everything-but-that instead of . - for example if spaces can only appear as you show them, use "(00 [^ ]* 01) target_mark" or "(00 \S* 01) target_mark" Kent From Dmytro.Lesnyak at xtract.fi Thu Nov 17 08:43:44 2005 From: Dmytro.Lesnyak at xtract.fi (Dmytro Lesnyak) Date: Thu, 17 Nov 2005 15:43:44 +0200 Subject: How to - import code not in current directory Message-ID: <662DD8E0B9B5064EB60F7F8ED573CC39024E66@ANTHRAX.xtract-hq.local> Yes, you can. Try this: import sys sys.path.append('c:\some\other\directory\') import bar Good luck! -----Original Message----- From: python-list-bounces+dima=xtract.fi at python.org [mailto:python-list-bounces+dima=xtract.fi at python.org] On Behalf Of py Sent: 17. marraskuuta 2005 15:19 To: python-list at python.org Subject: How to - import code not in current directory I have a python script that I want to test/debug. It contains a class which extends from some other class which is located in some other python file in a different directory. For example: [script to test] c:\python_code\foo.py [needed python files] c:\some\other\directory\bar.py ...so I want to test/debug foo.py, which needs bar.py. foo.py imports bar.py ...but in order to test out foo (in the python shell) I normally copy bar.py into the same directory as foo.py...but this is painful. Is there some way that I can have python know about the directory where bar.py is located, like a system variable, etc? If so, how do I set that up? Thanks. -- http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Sat Nov 26 20:34:29 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 26 Nov 2005 17:34:29 -0800 Subject: 2d array slicing problem In-Reply-To: <1664596.post@talk.nabble.com> References: <1128704653.953332.218930@g47g2000cwa.googlegroups.com> <20051007190144.GA19288@unpythonic.net> <1664596.post@talk.nabble.com> Message-ID: Tune Kamae (sent by Nabble.com) wrote: > I am thinking to upgrade my desktop to 64bit cpu with 16GB memory to handle > large astronomical images and data. I wonder if > 1) the latest numarry (besides 2d slicing) has been tested with one or more > 64 bit CPU and Linux distributions Certainly. > 2) with 64 bit address space, will numarray be able to handle larger arrays > and matrices (many 3d-arrays 100x100x100 and matrices 50k x 50k)? > (with 32 bit CPU I was limited by the memory.) > > I would appreciate knowing about your experience. You'll probably want to ask on the appropriate mailing list[1], but since you ask here, I will say that there are limitations that prevent numarray from fully utilizing 64-bit systems. numarray uses the Python buffer interface which is addressed by 32-bit integers even on 64-bit platforms[2]. There has been some work on numarray's replacement, scipy_core, to address this deficiency, but more work needs to be done and more volunteers with 64-bit systems are needed. 100x100x100 arrays should work with numarray; 50000x50000 perhaps not. You could always try and let us know. [1] http://lists.sourceforge.net/lists/listinfo/numpy-discussion [2] http://permalink.gmane.org/gmane.comp.python.numeric.general/2690 -- 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 bruce.tieche at usmtm.sppn.af.mil Thu Nov 3 03:22:37 2005 From: bruce.tieche at usmtm.sppn.af.mil (Tieche Bruce A MSgt USMTM/AFD) Date: Thu, 3 Nov 2005 11:22:37 +0300 Subject: when and how do you use Self? Message-ID: <3C5387E42DA62B4EA1F1EBD2DB498381596DE7@usmtm-emh3.USMTM.SPPN.AF.MIL> I am new to python, Could someone explain (in English) how and when to use self? I have been reading, and haven't found a good example/explanation Bruce Tieche (bruce.tieche at usmtm.sppn.af.mil) From fredrik at pythonware.com Tue Nov 22 05:12:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 11:12:41 +0100 Subject: about sort and dictionary References: <1132651818.348370.117450@g49g2000cwa.googlegroups.com> <1132653873.855348.265740@g47g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > > so what would an entry-level Python programmer expect from this > > piece of code? > > > > for item in a.reverse(): > > print item > > for item in a.reverse(): > > print item > > > I would expect it to first print a in reverse then a as it was. > > a=[1,2,3] > > I expect it to print > > 3 > 2 > 1 > 1 > 2 > 3 really? wouldn't 3 2 1 3 2 1 make a lot more sense ? From apardon at forel.vub.ac.be Fri Nov 4 09:58:38 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 14:58:38 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Op 2005-11-04, Christopher Subich schreef : > Antoon Pardon wrote: >> Op 2005-11-03, Stefan Arentz schreef : >>>The model makes sense in my opinion. If you don't like it then there are >>>plenty of other languages to choose from that have decided to implement >>>things differently. >> >> >> And again this argument. Like it or leave it, as if one can't in general >> like the language, without being blind for a number of shortcomings. >> >> It is this kind of recations that make me think a number of people is >> blindly devoted to the language to the point that any criticism of >> the language becomes intollerable. > > No, it's just that a goodly number of people actually -like- the > relatively simple conceputal model of Python. > > Why /shouldn't/ > > >>>a.x = foo > > correspond exactly to > > >>>setattr(a,'x',foo) #? > > Similarly, why shouldn't > > >>>foo = a.x > > correspond exactly to > > >>>foo = getattr(a,'x') #? > > With that in mind, the logical action for > > >>>a.x = f(a.x) > > is > > >>>setattr(a,'x',f(a,'x')) #, > > and since > > >>>a.x += foo > > is equal to > > >>>a.x = A.__iadd__(a.x,foo) # (at least for new-style classes > >>> # that have __iadd__ defined. Otherwise, it falls back on > >>> # __add__(self,other) to return a new object, making this > >>> # evern more clear), > > why shouldn't this translate into > > >>>setattr(a,'x',A.__iadd__(getattr(a,'x'),foo)) #? Well maybe because as far as I understand the same kind of logic can be applied to something like lst[f()] += foo In order to decide that this should be equivallent to lst[f()] = lst[f()] + foo. But that isn't the case. So it seems applying augmented operators is not a matter of just substituting straight translations to get the right result. > Looking at it this way, it's obvious that the setattr and getattr may do > different things, if the programmer understands that "instances (can) > look up object attributes, and (always) set instance attributes." In > fact, it is always the case (so far as I can quickly check) that += ends > up setting an instance attribute. Consider this code: Looking at lists in a similar way, it would be obvious that the __setitem__ and __getitem__ can do different things and so we should expect lst[f()] += foo to behave exactly as lst[f()] = lst[f()] + foo. -- Antoon Pardon From saint.infidel at gmail.com Thu Nov 10 17:34:41 2005 From: saint.infidel at gmail.com (infidel) Date: 10 Nov 2005 14:34:41 -0800 Subject: CherryPy not playing nicely with win32com? Message-ID: <1131662081.774161.33450@g49g2000cwa.googlegroups.com> I've been trying to get my CherryPy server to authenticate users against our network. I've managed to cobble together a simple function that uses our LDAP server to validate the username and password entered by the user: # ldap.py from win32com.client import GetObject ADS_SECURE_AUTHENTICATION = 1 def login_valid(username, password): ldap = GetObject("LDAP:") try: ldap.OpenDSObject( 'LDAP://XXXXXXXX.US', 'XXXXXXXX\\' + username, password, ADS_SECURE_AUTHENTICATION ) return True except: return False This function works great if I call it from the interactive prompt: >>> import ldap >>> ldap.login_valid('mylogin', 'XXXXXXXX') # pass incorrect network password False >>> ldap.login_valid('mylogin', 'XXXXXXXX') # pass correct network password True But as soon as I have my CherryPy filter call this exact same function, I get an "invalid syntax" COM error: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\cherrypy\_cphttptools.py", line 77, in _run applyFilters('beforeMain') File "C:\Python24\Lib\site-packages\cherrypy\_cphttptools.py", line 461, in applyFilters method() File "filters\authenticate.py", line 29, in beforeMain if ldap.login_valid(username, password): File "K:\src\py\XXXXXXXX\filters\ldap.py", line 6, in login_valid ldap = GetObject("LDAP:") File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 73, in GetObject return Moniker(Pathname, clsctx) File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 88, in Moniker moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname) com_error: (-2147221020, 'Invalid syntax', None, None) I don't get it. How can it be ok at the >>> prompt but invalid under CherryPy? From david.rasmussen at gmx.net Wed Nov 30 06:59:25 2005 From: david.rasmussen at gmx.net (David Rasmussen) Date: Wed, 30 Nov 2005 12:59:25 +0100 Subject: python speed In-Reply-To: References: Message-ID: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> Frithiof Andreas Jensen wrote: > > From the speed requirement: Is that correspondance chess by any chance?? > Regular chess at tournament time controls requires speed too. Any pure Python chess program would lose badly to the best C/C++ programs out there now. I would also like to see Half Life 2 in pure Python. /David From sybrenUSE at YOURthirdtower.com.imagination Thu Nov 17 07:37:42 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 17 Nov 2005 13:37:42 +0100 Subject: Python gui References: <436e3916$0$22284$4fafbaef@reader1.news.tin.it> <1131307703.160659.267170@g44g2000cwa.googlegroups.com> Message-ID: batfree enlightened us with: > Now GTK can use the local theme.You can choose the local theme to > make your application windows style on Winodws and Mac likely on mac > os. But why do that yourself, when you can use a GUI toolkit that does it for 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 *firstname*nlsnews at georgea*lastname*.com Tue Nov 29 15:50:12 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Tue, 29 Nov 2005 20:50:12 GMT Subject: ncurses' Dark Devilry References: Message-ID: <*firstname*nlsnews-8F0080.15501829112005@news.verizon.net> In article , Jeremy Moles wrote: > I'm working on a project using ncurses w/ Python. As an aside, I > implemented addchstr in the cursesmodule.c file in Python SVN, if anyone > wants me to try and get that made permanent. > > AT ANY RATE... > > I was wondering--and this is more a general curses question rather than > a Python one, but I know there are some old-timers here who have made > curses obey before--is there a way to "repaint" a portion of screen > without stealing the "cursor?" That is: > > I have a focus "wheel" of sorts that allows the user to do input on > various wigets and windows and whatnot. However, if I want to quickly > call addstr somewhere else in the application I have to: > > 1. Store the YX coords of the cursor currently > 2. Use the cursor in the "current" action > 3. Restore the old cursor location > > I know there are ways around this as I have seen curses apps that, for > example, have a clock that updates every second without stealing > "focus." > > I tried implementing/using addchstr (mentioned above) to no success. > > Any ideas? Is this just the plain wrong place to ask this? :) I've only tried to read the Python Library Curses docs, but I thought that the Window object method addstr() would do what you want. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From spe.stani.be at gmail.com Wed Nov 2 15:25:54 2005 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 2 Nov 2005 12:25:54 -0800 Subject: SPE 0.7.5.e - Python IDE with improved uml, debugger & unicode support Message-ID: <1130963154.402924.146160@z14g2000cwz.googlegroups.com> What's new? SPE now creates backup files and can insert your standard signature (with for example license and copyright information) in your code. A bug that prevented SPE to start on Linux has been fixed and also a lot of bugfixes were implemented, especially for unicode. You can read more on the SPE news blog. If you like SPE, please contribute by coding, writing documentation or donating. Spread the word on blogs, ... It would be nice if some (experienced) Mac users would subscribe to the developers mailing list to speed up the Mac port for SPE. I expect my new Mac any moment. Spe is a python IDE with auto-indentation, auto completion, call tips, syntax coloring, uml viewer, syntax highlighting, class explorer, source index, auto todo list, sticky notes, integrated pycrust shell, python file browser, recent file browser, drag&drop, context help, ... Special is its blender support with a blender 3d object browser and its ability to run interactively inside blender. Spe ships with wxGlade (gui designer), PyChecker (source code doctor) and Kiki (regular expression console). Spe is extensible with wxGlade. Stani -- http://pythonide.stani.be http://pythonide.stani.be/manual/html/manual.html From kylotan at gmail.com Wed Nov 2 05:18:58 2005 From: kylotan at gmail.com (Ben Sizer) Date: 2 Nov 2005 02:18:58 -0800 Subject: Python's website does a great disservice to the language In-Reply-To: References: Message-ID: <1130926738.909385.138190@g49g2000cwa.googlegroups.com> CppNewB wrote: > But the logos look like they were done in Paint and maybe a > readable default font is in order. I can't believe you think the font there is unreadable. It's left to the browser default, which is usually set to a simple serif font, which in turn is presumably the default because the majority of all books, magazines, and newspapers in existence use it, and have found it perfectly readable up to now. With the ability of the user to customise their font size, surely this is by definition more readable than any arbitrarily chosen typeface and size which cannot possibly suit everybody? You can append "body { font-family: sans-serif; font-size: 10pt; }" to the CSS and make it look 'professional' but it doesn't make it more readable. Really this just comes down to preconceptions over how a site 'should' look based on other sites, not on any tangible difference. -- Ben Sizer From usenet at marduk.letterboxes.org Tue Nov 15 14:26:27 2005 From: usenet at marduk.letterboxes.org (marduk) Date: Tue, 15 Nov 2005 19:26:27 GMT Subject: is parameter an iterable? In-Reply-To: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> Message-ID: <1132082786.2300.2.camel@blackwidow> On Tue, 2005-11-15 at 11:01 -0800, py wrote: > I have function which takes an argument. My code needs that argument > to be an iterable (something i can loop over)...so I dont care if its a > list, tuple, etc. So I need a way to make sure that the argument is an > iterable before using it. I know I could do... > > def foo(inputVal): > if isinstance(inputVal, (list, tuple)): > for val in inputVal: > # do stuff > > ...however I want to cover any iterable since i just need to loop over > it. > > any suggestions? > You could probably get away with if hasattr(inputVal, '__getitem__') From mwm at mired.org Tue Nov 8 00:18:50 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 00:18:50 -0500 Subject: problem generating rows in table References: <1131424393.303923.263380@g43g2000cwa.googlegroups.com> Message-ID: <86ek5r90p1.fsf@bhuda.mired.org> s99999999s2003 at yahoo.com writes: > hi > i wish to generate a table using cgi > toprint = [('nickname', 'justme', 'someplace')] > print ''' > > > > > > > ''' > > for i in range(0,len(toprint)-1): > for j in range(0,len(toprint[0])-1): > print "" % toprint[i][j] > > print ''' >
UserNameAddress
%s
''' > > but it only prints out a table with "User | Name | address" > it didn't print out the values of toprint > > is there mistake in code? please advise You're not calling range right. It's designed for dealing with lists, so range(n) returns [0, ..., n - 1], and range(to, bottom) returns [top, ..., bottom - 1]. len(toprint) is 1, so len(toprint) - 1 is 0, so you're calling range(0, 0), which is an empty list. So you make no passes through the outer loop. Those two calls to range should be range(len(toprint)) and range(len(toprint[i])) (n.b.: i, not 0, is the index). Of course, for is for walking elements of a list. You don't need the indices at all. The pythonic way to write this loop would be: for tup in toprint: for el in tup: print " %s " % el But your HTML is also broken. The loop as you have it will print one row containing all the elements in toprint concatenated together. You need to put each tuple in toprint into a separate row, like so: for tup in toprint: print "" for el in tup: print " %s " % el print "" print "" and of course leave out the trailing in the print statement that precedes the loop. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tim.golden at viacom-outdoor.co.uk Thu Nov 10 11:43:22 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 10 Nov 2005 16:43:22 -0000 Subject: IE Temporary Internet Files & Python Message-ID: <9A28C052FF32734DACB0A288A3533991044D230E@vogbs009.gb.vo.local> [rtilley] > Below is a script that recursively deletes files from a directory. It > works well on the two directories that I'm currently using it on: > C:\Documents and Settings\user\Cookies > C:\Documents and Settings\user\Temp > However, I'd like to use it on this directory as well: > C:\Documents and Settings\user\Temporary Internet Files > The script does not seem to work when used on Temporary Internet Files. > I've googled around a bit, but haven't found any tips... thought I'd > trouble the list for an answer or at least some explanations. > Feel free to critiqe the script as well. Perhaps it's a programmer error. Temporary Internet Files is one of those special shell folders and, I suspect, isn't really a folder at all in the normal sense: it just presents itself as one to the O/S. (Might be wrong there). Probably means you have to use shell functions to access it. Quick trial with SHFileOperation works up to a point, but ultimately fails with a file-in-use error. This article: http://www.codeguru.com/Cpp/I-N/ieprogram/article.php/c1245/ uses a very different technique. The APIs in question aren't wrapped in pywin32. You could probably get at them via ctypes. Don't have time to try it myself at the moment. TJG PS Probably doesn't matter at the mo, but for general purpose use, those folders aren't always where your script hardwires them to be. You might need to look at the shell functions around SHGetPathFromIDList and SHGetSpecialFolderLocation. Tim ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From fredrik at pythonware.com Wed Nov 16 17:25:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Nov 2005 23:25:14 +0100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com><1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: > Alex has already posted the right way to do this. can you please stop posting crappy non-solutions to a problem that has a very simple solution (split things up), that should be obvious to anyone who didn't sleep through exceptions 101. From bonono at gmail.com Wed Nov 23 10:31:56 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 07:31:56 -0800 Subject: best cumulative sum In-Reply-To: References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <1132708265.941224.186550@g44g2000cwa.googlegroups.com> Message-ID: <1132759916.884111.215010@g14g2000cwa.googlegroups.com> David Isaac wrote: > > Michael Spencer wrote: > > > This can be written more concisely as a generator: > > > wrote in message > news:1132708265.941224.186550 at g44g2000cwa.googlegroups.com... > > If iterable has no elements, I believe the behaviour should be [init], > > there is also the case of init=None that needs to be handled. > > Right. So it is "more concise" only by being incomplete, right? > What other advantages might it have? > > > otherwise, that is more or less what I wrote for my scanl/scanl1. > > I didn't see a post with that code. > > Alan Isaac def scanl1(func, seq): def my_func(x): my_func.init = func(my_func.init, x) return my_func.init i = iter(seq) try: my_func.init = i.next() except StopIteration: return [] return (chain([my_func.init], (my_func(y) for y in i))) def scanl(func, seq, init): def my_func(x): my_func.init = func(my_func.init, x) return my_func.init my_func.init = init return (chain([my_func.init], (my_func(y) for y in seq))) From ralfgb at gmx.de Thu Nov 17 15:24:48 2005 From: ralfgb at gmx.de (RalfGB) Date: 17 Nov 2005 12:24:48 -0800 Subject: best way to discover this process's current memory usage, cross-platform? References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132037126.467573.184300@o13g2000cwo.googlegroups.com> <1h6283c.11rnxzy16xusl2N%aleax@mail.comcast.net> <1132089400.289778.229920@g47g2000cwa.googlegroups.com> <1h62mth.18oycmq13n80kfN%aleax@mail.comcast.net> Message-ID: <1132259088.314874.280430@o13g2000cwo.googlegroups.com> Alex Martelli schrieb: > MrJean1 wrote: > > > This may work on MacOS X. An initial, simple test does yield credible > > values. > > Definitely looks promising, thanks for the pointer. > > > However, I am not a MacOS X expert. It is unclear which field of the > > malloc_statistics_t struct to use and how malloc_zone_statistics with > > zone NULL accumulates the stats for all zones. > > It appears that all of this stuff is barely documented (if at all), not > just online but also in books on advanced MacOS X programming. Still, I > can research it further, since, after all, the opendarwin sources ARE > online. Thanks again! > > > Alex "mallinfo" is available on most UNIX-like systems(Linux, Solaris, QNX, etc.) and is also included in the dlmalloc library (which works on win32). There is a small C extension module at http://hathawaymix.org/Software/Sketches/ which should give access to mallinfo() and thus byte accurate memory usage information. I have to admit, that I did not tried it myself... From aleax at mail.comcast.net Sat Nov 26 21:06:33 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 26 Nov 2005 18:06:33 -0800 Subject: Comparison problem References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: <1h6n9xq.19fe66e17zfnokN%aleax@mail.comcast.net> Tom Anderson wrote: ... > But, more importantly, egad! What's the thinking behind having slicing > behave like that? Anyone got any ideas? What's the use case, as seems to > be the fashionable way of putting it these days? :) Slicing has always been "soft" (it's OK to specify slice indices beyond the boundaries) while indexing has always been "hard" (specifying an index beyond the boundaries raises an exception). It does allow simpler and more concise expression of conditions on slices, without requiring you to guard the test on the slice with another test on the sequence's length. For example, to say "those sublists of lists-of-lists bigL that don't end in [...1,2,3]" you can code [L for L in bigL if L[-3:] != [1,2,3]] instead of [L for L in bigL if len(L) < 3 or L[-3:] != [1,2,3]] Introducing the endswith and startswith string methods lowered the usefulness of soft slicing for such tests on strings (since it subtracted some specific use cases), but not all sequences have such specialized methods, and not all use cases of soft slicing are tests. E.g., "remove the last character of s (if any)" can be compactly expressed with "s=s[:-1]" rather than "s=s and s[:-1]" or more expansive testing. No big deal, but then again I don't recall any situation in which getting an exception from slicing (as opposed to indexing) would have helped me catch a bug faster. Alex From mcfletch at rogers.com Tue Nov 29 20:51:37 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 29 Nov 2005 20:51:37 -0500 Subject: 3d Transformation In-Reply-To: References: Message-ID: <438D05A9.9080401@rogers.com> Tyler Eaves wrote: >Got a 3d algorithmns question. Algorithmn will be implemented in python, >so a library would be great if it works on windows. Basically my function >would be defined as such. > >Problem is one of coordinate transformation. Give a 3d vector, which >reprents the +z axis in the source coordinate system, and a rotation value >around that axis for determinging the x and y axises, I wish to translate >a point from that geometry into "world" geometry, or in other words >absolute coordinates. Input data is a 3d path with banking data that will >be sampled at regular points for purposes of building other geometry. > > You can find code for doing this in the OpenGLContext project. The lowest-level code is in the vrml.vrml97.transformmatrix module, which just generates matrices for the various transformations, rotations and scales. You can find the module here: http://cvs.sourceforge.net/viewcvs.py/pyopengl/vrml/vrml97/transformmatrix.py?view=markup the module also allows for generating inverse arrays (what you use for transforming from outer coordinates to inner, instead of inner to outer), and has an accelerator C module for much of the functionality. The higher levels in OpenGLContext support compositing multiple transformations in a containment hierarchy for a scenegraph. See e.g. OpenGLContext/scenegraph/transform and OpenGLContext/scenegraph/nodepath module for that higher-level stuff. Anyway, hope this helps, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From robert.kern at gmail.com Fri Nov 18 14:24:59 2005 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 18 Nov 2005 11:24:59 -0800 Subject: Web-based client code execution In-Reply-To: <3u6ngeFvh3v1U1@individual.net> References: <3u6ngeFvh3v1U1@individual.net> Message-ID: Paul Watson wrote: > I have read some about AJAX. Is there an APAX coming for Python? Not until browsers have embedded Python interpreters. There's been talk about doing this in Mozilla, but I don't think the talk has turned into usable code, yet. -- 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 dakman at gmail.com Tue Nov 8 09:46:26 2005 From: dakman at gmail.com (dakman at gmail.com) Date: 8 Nov 2005 06:46:26 -0800 Subject: XML GUI In-Reply-To: <1131457704.275657.237970@g49g2000cwa.googlegroups.com> References: <1131457704.275657.237970@g49g2000cwa.googlegroups.com> Message-ID: <1131461186.068052.81270@g14g2000cwa.googlegroups.com> I had to do something like this for a project I was working on a while ago, it was a program based on alota plugins that would use a config file that looked sorta like an Xorg configuration, it seemed kinda hard at the time but it's acctually pretty fun and easy, the hard part is functionality you wanna make sure that you have everything planed out before tackling this, as for bindings and whatnot all I did was type the method I want to call in the config, and then I would use eval() to call it up, kinda sloppy but it worked fine. From simon.brunning at gmail.com Fri Nov 18 09:37:49 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 18 Nov 2005 14:37:49 +0000 Subject: Adding through recursion In-Reply-To: <1132324258.091428.287910@g44g2000cwa.googlegroups.com> References: <1132320167.127338.92460@g47g2000cwa.googlegroups.com> <1132324258.091428.287910@g44g2000cwa.googlegroups.com> Message-ID: <8c7f10c60511180637o373b29a6x@mail.gmail.com> On 18 Nov 2005 06:30:58 -0800, martin.clausen at gmail.com wrote: > I still don't get it. I tried to test with x = 0 and found that to > work. How come since the value of y is right and it is printed right it > "turns into" None when returned by the return statement ? There is no return statement in your else block. That's where the Nones are coming from. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From smcg4191zz at friizz.RimoovAllZZs.com Sun Nov 13 18:10:19 2005 From: smcg4191zz at friizz.RimoovAllZZs.com (Stuart McGraw) Date: Sun, 13 Nov 2005 16:10:19 -0700 Subject: Python Book References: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> <11nfdv67tfvt246@corp.supernews.com> Message-ID: <11nfhv5c9a1sc60@corp.supernews.com> "Stuart McGraw" wrote in message news:11nfdv67tfvt246 at corp.supernews.com... > David Beasley's Essential Python (New Riders). It's a little dated > now (covers only up to version 2.2) [...] Oops, that should be "Beazley", "Python Essential Reference", and version 2.1. From m.kramm at quiss.org Sun Nov 27 08:03:30 2005 From: m.kramm at quiss.org (Matthias Kramm) Date: 27 Nov 2005 05:03:30 -0800 Subject: The imp module and cyclic imports References: <1132864414.261663.306290@g43g2000cwa.googlegroups.com> Message-ID: <1133096610.027080.16710@f14g2000cwb.googlegroups.com> > the problem you're seeing appears also if you use "import web.one" > or "from web import one" or "__import__('web.one')". Thanks for the hint. You're right. This isn't actually imp related. The standard import also fails. > if you replace the "from web import" statements with plain imports, > everything will work as expected. just change > > from web import one > > to > > import one Unfortunately, this fails if one.py and two.py are in different directories/packages. With a setup like web1/one.py web2/two.py there doesn't seem to be any way to make one.py and two.py reference each other via (non-delayed) imports. It's interesting, though, that cyclic imports work when using the plain "import foo" import, but not with the "from package import foo" style. Especially since the former also used to fail (google for "python cyclic imports" on groups.google.com). I wonder whether the "from" style imports were overlooked when the cyclic problem was fixed. Greetings Matthias From bearophileHUGS at lycos.com Sun Nov 13 13:01:00 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Nov 2005 10:01:00 -0800 Subject: D foreach Message-ID: <1131904860.125509.150090@g49g2000cwa.googlegroups.com> The Digital Mars D compiler is a kind of "improved c++", it contains a "foreach" statement: http://www.digitalmars.com/d/statement.html#foreach Usage example: foreach(int i, inout int p; v1) p = i; Is equal to Python: for i in xrange(len(v)): v[i] = i That is: v1 = range(len(v1)) (Some people use something like this in Python to scan a list of lists, so p become a reference to a list, that can be modified in place, but it's not much explicit way of doing things.) Another example: foreach(int i, int p; v2) v1[i] = p; Is equal to Python: for i,p in enumerate(v2): v1[i] = p So the variable p contains (scans) the elements of the given iterable object, but if you assign p with a value, that value becomes copied inside the mutable iterable too. Those are little examples, but I think it can be quite useful in more complex code. Bye, bearophile From fredrik at pythonware.com Wed Nov 23 07:29:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 13:29:41 +0100 Subject: user-defined operators: a very modest proposal References: <4383C386.5040909@kzoo.edu> <8c7f10c60511230414w7547f2d7m@mail.gmail.com> Message-ID: Simon Brunning wrote: >> What do you mean by unicode operators? Link? > > http://fishbowl.pastiche.org/2003/03/19/jsr666_extended_operator_set see also: http://www.brunningonline.net/simon/blog/archives/000666.html http://www.python.org/peps/pep-0666.html From tundra at tundraware.com Thu Nov 3 14:56:44 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 03 Nov 2005 14:56:44 EST Subject: OT - Re: Microsoft Hatred FAQ In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Thu, 03 Nov 2005 04:34:20 -0500, Tim Daneliuk wrote: > > > >>A) I don't much care if people wander off topic from time to time - >> that's what filters are for. But as a matter of general courtesy >> is it too much to ask that the subject line be so marked? > > > Fair enough. > > >>B) Rhetoric is not Reality. "Crime" has a very specific definition. >> It always has one or more of Fraud, Force, or Threat. > > > Nonsense. > > Jaywalking is a crime. So is littering. So is merely belonging to certain > organisations, such as the German Nazi party or any number of allegedly > terrorist groups. Walking around naked in public is a crime, and in many > places in the world, including the USA, you then become a "registered sex > offender" for the rest of your life. (So much for doing time and wiping > the slate clean.) > > Possession of many substances is a crime in the USA, and not just drugs > of addiction. There is no Fraud, Force or Threat involved in growing > cannabis in your backyard, or selling pornography to teenagers, or driving > without a licence. > > Possession of banned books is a crime in many countries, and yes even in > the 21st century there are many, many banned books. If legislation being > urged on the US Senate by the MPAA is passed, manufacturing, selling and > possibly even possession of analog to digital devices will become a crime > -- not just a civil offense, or a misdemeanor, but a felony. There is a difference between what is *illegal* and what constitutes a *crime*. There are many things that are illegal that ought not to be (you mention several) becauase they do *not* meet the standard of Fraud/Force/Threat. These are laws that are inflicted by the majority upon the minority because most people are nosey and want to tell everyone else what to do. Anti-trust laws also fit in this category. > >>Just because *you* >> don't like market outcomes doesn't make it a "crime". > > > In civilizations that believe in freedom for human beings, freedom is not > unlimited. There are actions which remain forbidden, even though that > limits individual freedom. Bill Gates is not permitted to lock you up > against your will: his freedom to restrict others' freedoms is severely > curtailed. > > In civilizations that believe in free markets, freedom is also not > unlimited. There are actions which are forbidden, because those actions That's right - you cannot use fraud/force/threat. The rest is nobody's business. But your claim that government mut place restrictions on free markets is bogus. It likely springs from a polluted understanding of just what the role of government ought to be and how markets actually work. > > >>C) Hate Microsoft all you want. But those of us old enough to have >> actually done this for than 10 minutes recall the days where every single >> hardware vendor was also a unique software and systems vendor. >> Absent a Microsoft/Intel-style de facto standard, you'd never have >> seen the ascent of Linux or Open Source as it exists today. > > > Nonsense again. > > Real standards, like TCP/IP which is the backbone of the Internet, aren't TCP/IP was NOT an open standard originally. It came into being at the hands of a monopoly (government) and at the point of a gun (forced taxation). > controlled by any one company. Anyone can create a TCP stack. Nobody but > Microsoft can create a competing version of Windows. TCP/IP became a So what? This does not make Microsoft a monopolist. It makes it a sole source vendor. What gives Microsoft their market power is *their customers* who feel they are getting a good deal. No one forces their customers to buy the products, and there are real alternatives available. Just why, do you suppose, people continue to use Windows is large numbers when Linux/BSD is *free*? Because they hate Windows? Because Microsoft is overcharging or cheating them? Get a grip. Microsoft succeeds because it serves its customer base. They do it on a scale that makes everyone else jealous and instead of outcompeting Microsoft, they go whining to the DOJ about how unfair the world is. > standard long before Microsoft even acknowledged it's existence. So did > ASCII, the IBM BIOS, and serial ports, to name just a few. Does the term > "ISO standard" mean anything to you? I have been a member of many standards committees including POSIX, ANSI, and X/OPEN. Standards committees do not *set* standards, they codify existing common practice - well the successful standards do. That's why POSIX 1003.1 is an embraced standard and X/Open is a footnote in technology history. Durable standards are always set by *practice* first. This usually means some interesting combination of users and vendors solving problems. Microsoft helped standardize the PC platform and thus set de facto standards because in the early days people wanted to sell hardware and considered OSs a nuisance. So, they built their hardware achitectures to best take advantage of MS-DOS and then Windows. To argue that Microsoft had no influence on the commoditization and standardization of hardware is utterly absurd. P.S. Unlike you (it sounds like), I actually worked in the industry during the evolution from Altairs to TRS-80s/Apples to PCs. Microsoft was and enormous accelerant to the growth and acceptance of PCs in business and non-technical settings. As I said, I prefer Unix, but everyone in this profession owed Microsoft an enormous debt. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From mde at micah.elliott.name Tue Nov 15 23:35:38 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Tue, 15 Nov 2005 20:35:38 -0800 Subject: Function - Empty list as default parameter - not acting local? In-Reply-To: <312cfe2b0511151944k1c7928acv74f6b6223a6f07de@mail.gmail.com> References: <312cfe2b0511151944k1c7928acv74f6b6223a6f07de@mail.gmail.com> Message-ID: <20051116043538.GA30817@kitchen.client.attbi.com> On Nov 15, Gregory Pi?ero wrote: > Hey guys, could anyone explain this behavior to me. It doesn't > seem right :-( > def testfunc(parm1,parm2={}): > print 'parm2',parm2 > parm2['key1']=5 > >>testfunc('greg') > parm2 {} > >>testfunc('greg') > parm2 {'key1': 5} http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From tuvas21 at gmail.com Fri Nov 11 01:05:06 2005 From: tuvas21 at gmail.com (Tuvas) Date: 10 Nov 2005 22:05:06 -0800 Subject: LARGE numbers Message-ID: <1131689106.652488.319580@g47g2000cwa.googlegroups.com> I've been thinking about writing a program to generate the world's largest prime numbers, just for the fun of it. This would require being able to hold an 8000000 digit number into memory (25 megabits, or a little over 3 megs of memory for just one variable...) I would also need several smaller variables. This came about as I optimised a prime number generator more and more, until I came with the idea to try to find the largest ever, using python. Any ideas? I'll probably try to run this on a mainframe eventually, although they might not like it very much... I'll run it on my home computer to first test it. Anyways, let me know if there's a way to make python support numbers so high. Thanks! From roccomoretti at hotpop.com Mon Nov 28 13:40:07 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 28 Nov 2005 12:40:07 -0600 Subject: Which License Should I Use? In-Reply-To: References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 25 Nov 2005 11:30:46 -0800, mojosam wrote: > >>I guess I don't care too much about how other people use it. > > Then probably the best licence to use is just to follow the lead of > Python. For that sort of small program of limited value, I put something > like this in the code: > > Copyright (c) 2005 Steven D'Aprano. > Released under the same license as used by Python 2.3.2 itself. > See http://www.python.org/psf/license.html for details, and > http://www.python.org/2.3.2/license.html for the full text of the license. Gaak! No! The Python license you point to contains horrible amounts of cruft due to the ownership ping-pong game. (And just using the hyperlink like you did leaves it vauge as to who is doing the liscensing - Steven D'Aprano? the PSF? BeOpen? CNRI? Stichting Mathematisch Centrum?) As I understand it, the PSF's official position is that the Python license (even just the top most one) is not appropriate for any program besides Python itself. http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq Note that the Python license is not even appropriate for third party code that's intended to be contributed to the Python standard library or core! If you want a "like Python" license, try the MIT or "new-BSD" license instead: http://www.opensource.org/licenses/mit-license.php http://www.opensource.org/licenses/bsd-license.php From avnit7 at gmail.com Sat Nov 5 15:38:20 2005 From: avnit7 at gmail.com (avnit) Date: 5 Nov 2005 12:38:20 -0800 Subject: Print to printer In-Reply-To: References: <1130528702.908172.189990@g47g2000cwa.googlegroups.com> Message-ID: <1131223100.228028.29420@g47g2000cwa.googlegroups.com> Do you know if there's a way to print a file? I'm trying to print an HTML file, so your solution is good, but doesn't really work for me. Just reading the HTML file and the printing the content obviously wouldn't work. I also tried: >>> printer.write(file('path/to/file.ext')) but apparently this function only takes strings as parameters. Thanks. From rbt at athop1.ath.vt.edu Thu Nov 10 09:37:18 2005 From: rbt at athop1.ath.vt.edu (rtilley) Date: Thu, 10 Nov 2005 09:37:18 -0500 Subject: IE Temporary Internet Files & Python Message-ID: A bit off-topic, but Python related. Below is a script that recursively deletes files from a directory. It works well on the two directories that I'm currently using it on: C:\Documents and Settings\user\Cookies C:\Documents and Settings\user\Temp However, I'd like to use it on this directory as well: C:\Documents and Settings\user\Temporary Internet Files The script does not seem to work when used on Temporary Internet Files. I've googled around a bit, but haven't found any tips... thought I'd trouble the list for an answer or at least some explanations. Feel free to critiqe the script as well. Perhaps it's a programmer error. rbt ---------------------------------------- import os import os.path userpath = 'C:/Documents and Settings/' userlist = os.listdir(userpath) # Make sure that userlist only contains directories, no files. for u in userlist[:]: if os.path.isdir(userpath+u): pass else: userlist.remove(u) def remove_files(target_dir): fp = file('remove_temp_files.txt', 'a') for root, dirs, files in os.walk(target_dir): for f in files: try: os.unlink(os.path.join(root, f)) print >> fp, "Removed:", os.path.join(root,f) except OSError: pass fp.close() # Remove 'Local Settings|Temp' files for username in userlist: target_dir = userpath+username+'/Local Settings/Temp/' #print target_dir remove_files(target_dir) # Remove IE Cookies for username in userlist: target_dir = userpath+username+'/Cookies/' #print target_dir remove_files(target_dir) --------------------------------------------------- From grante at visi.com Tue Nov 15 09:59:26 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Nov 2005 14:59:26 -0000 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <11ni1sddrhsm03d@corp.supernews.com> <1132048673.702127.307450@g47g2000cwa.googlegroups.com> Message-ID: <11njtue1d4kdi06@corp.supernews.com> On 2005-11-15, Ben Sizer wrote: > Grant Edwards wrote: >> In the situations described, I always use strings >> and have never felt the need for something else: > > ... > >> I don't think I even understand what the objection is. What is >> needed is a code fragment that shows how the use of strings is >> untenable. > > myObject.value = 'value1' > > #... 100 lines of code elided... > > if myObject.value == 'Value1': > do_right_thing() > else: > do_wrong_thing() > > I don't actually think string use is 'untenable', but it is > definitely more error-prone. With some sort of named object on > the right hand side you will at least get a helpful NameError. I don't see how that's an argument in favor of the proposal being discussed. Aren't $Value1 and $value1 both legal and distinct symbols in the proposed syntax? Won't you have the exact same issue that you do with mis-typing strings? -- Grant Edwards grante Yow! .. Do you like at "TENDER VITTLES?"? visi.com From samrobertsmith at gmail.com Sun Nov 20 08:36:04 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 05:36:04 -0800 Subject: about lambda Message-ID: <1d987df30511200536g1f2b9388t5aa13b9e921dc747@mail.gmail.com> what does the following code mean? It is said to be used in the calculation of the overlaid area size between two polygons. map(lambda x:b.setdefault(x,[]),a) Thanks! From bobueland at yahoo.com Thu Nov 17 13:12:09 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 17 Nov 2005 10:12:09 -0800 Subject: IDLE question References: <1132217965.434209.122200@f14g2000cwb.googlegroups.com> <3u3186FvbckvU1@individual.net> <1132221788.888868.8370@f14g2000cwb.googlegroups.com> <3u34abFv24c5U1@individual.net> <1132225335.948524.162190@g43g2000cwa.googlegroups.com> <3u3899Fv3vulU1@individual.net> <3u393bFtovgcU1@individual.net> <1132230637.099278.295980@z14g2000cwz.googlegroups.com> <3u3fddFurbi3U1@individual.net> Message-ID: <1132251129.869372.39760@g43g2000cwa.googlegroups.com> I made bat file called startidle.bat which I put in C:\Python24 directory. This is how it looks @echo off start C:\Python24\pythonw.exe C:\Python24\Lib\idlelib\idle.py -r C:\Python24\sitecustomize.py exit Now I put a shortcut of startidle.bat in Quick Launch. The only thing I have to do now is to click on the shortcut icon in the Quick Launch and I'm up and running. Alla Tua Salute Claudio Bob From niclane at oakcom.co.nz Tue Nov 22 11:17:46 2005 From: niclane at oakcom.co.nz (niclane) Date: 22 Nov 2005 08:17:46 -0800 Subject: port script to embedded device - decompile pyinstaller exe? Message-ID: <1132676266.874856.215840@g49g2000cwa.googlegroups.com> Hi, I have some python scripts, I need to run a netgear router, i have a cross compilation setup that works for c code no problem. the python interpreter doesn't appear to have been successfully cross compiled to this netgear router although others have tried. what i'd like to do is get these scripts to run on the router. i saw pyinstaller creates exes that can be run on a standard x86 linux desktop. what i thought i could do was create an exe, decompile it to c and then do a cross compile for the device. there must be a better way... any suggestions? can I get pyinstaller to make a exe for the router directly? or is there a process to create c source from a python script? is there an easy way to wrap the python perhaps in a c source? alternatively will my suggestion work? as you'd have gathered I don't have much experience in this type of thing so any help the community out there can provide would be greatly appreciated. the routers are all netgear wgt634u models, running a slight variant of openwrt called openwgt. the tool chain is mipsel-linux. thanks for your help. nic From bonono at gmail.com Mon Nov 14 05:11:52 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 14 Nov 2005 02:11:52 -0800 Subject: Clone an object In-Reply-To: References: Message-ID: <1131963112.937257.139360@o13g2000cwo.googlegroups.com> http://docs.python.org/lib/module-copy.html I would assume you want deep/shallow copy. Yves Glodt wrote: > Hello, > > how can I clone a class instance? > I have trouble finding that in the documentation... > > thanks and best regards, > Yves From deets at nospam.web.de Sun Nov 20 06:53:23 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Nov 2005 12:53:23 +0100 Subject: custom xml pretty print In-Reply-To: <1132486894.734291.34400@o13g2000cwo.googlegroups.com> References: <1132486894.734291.34400@o13g2000cwo.googlegroups.com> Message-ID: <3ub6deF10iginU1@uni-berlin.de> akbar wrote: > Hi, > > I have Document. If I print it like this: > > print doc.toprettyxml(" ") > > I will get this: > > > > blablablabla > > > > > What do I have to do if I want to print it like this: > > > blablablabla > > Use a SAX-Handler, parse it yourself and pretty-print your own. You _could_ use DOM, but I don't think its needed here. Diez From mwm at mired.org Thu Nov 10 01:25:44 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Nov 2005 01:25:44 -0500 Subject: ANN: P(x) 0.2 applet builder Message-ID: <86br0t6mtz.fsf@bhuda.mired.org> P(x) is hard to describe. It might be called a "Framework", but that's a grandiose word for a couple of hundred lines of code. It might be called a programmable calculator, but it has none of the things one associates with calculators. It might be called a programming language, but it's just Python some extra builtins. So I settled on "applet builder". A P(x) applet has a set of input variables, a set of output variables, and a function that calculates the latter from the former. P(x) provides the GUI to let the user enter input variables and read and copy output variables. The current implementation restricts the variables to integers, strings and floats. Examples include temperature converters and a numerical integration tool. The tarball can be found at . http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steven.bethard at gmail.com Thu Nov 3 13:57:51 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 03 Nov 2005 11:57:51 -0700 Subject: __slots__ and class attributes In-Reply-To: References: Message-ID: Ewald R. de Wit wrote: > I'm running into a something unexpected for a new-style class > that has both a class attribute and __slots__ defined. If the > name of the class attribute also exists in __slots__, Python > throws an AttributeError. Is this by design (if so, why)? > > class A( object ): > __slots__ = ( 'value', ) > value = 1 > > def __init__( self, value = None ): > self.value = value or A.value > > a = A() > print a.value > > > Traceback (most recent call last): > File "t1.py", line 8, in ? > a = A() > File "t1.py", line 6, in __init__ > self.value = value or A.value > AttributeError: 'A' object attribute 'value' is read-only Check the documentation on __slots__[1]: __slots__ are implemented at the class level by creating descriptors (3.3.2) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment. I agree that the error you get is a bit confusing. I think this has to do with how the descriptor machinery works. When you write something like a.value where a is a class instance, Python tries to invoke something like: type(a).value.__get__(a) Here's an example of that, working normallly: py> class A(object): ... __slots__ = ['value'] ... def __init__(self): ... self.value = 1 ... py> a = A() py> type(a).value py> type(a).value.__get__ py> type(a).value.__get__(a) 1 Now when you add a class attribute called 'value', you overwrite the descriptor. So when Python tries to do the same thing (because your definition of __slots__ makes it assume that 'value' is a descriptor), the descriptor machinery raises an AttributeError: py> class A(object): ... __slots__ = ['value'] ... value = 1 ... py> a = A() py> type(a).value 1 py> type(a).value.__get__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'int' object has no attribute '__get__' This AttributeError must be somehow caught by the __slots__ machinery and interpreted to mean that you tried to write to a read-only attribute. The resulting error message is probably not what you want, but I don't know the source well enough to figure out whether or not a better error message could be given. But why do you want a class level attribute with the same name as an instance level attribute? I would have written your class as: class A(object): __slots__ = ['value'] def __init__(self, value=1): self.value = value where the default value you put in the class is simply expressed as a default value to the __init__ parameter. Steve [1]http://docs.python.org/ref/slots.html From *firstname*nlsnews at georgea*lastname*.com Tue Nov 29 15:52:43 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Tue, 29 Nov 2005 20:52:43 GMT Subject: wxPython : getting started References: <438c8dc4$1@epflnews.epfl.ch> Message-ID: <*firstname*nlsnews-23918B.15522529112005@news.verizon.net> In article <438c8dc4$1 at epflnews.epfl.ch>, David Sulc wrote: > Hi ! > > I've looked all over (internet, books, etc.) and I haven't found a very > good ressource to get started with wxPython (yes, I've been through > their tutorial). > > What I would basically like to do for starters is to be able to define > the main panel being displayed. For example : > 1. wxFrame contains a wxPanel (call it mainPanel). > 2. mainPanel contains another panel (childPanelA) > 3. another panel has been defined (childPanelB) but is not displayed > (the user can only see childPanelA inside mainPanel) > 4. by clicking on a menu entry (for example), the displayed panel is now > childPanelA (which is inside mainPanel) > > So how do I do this ? I realize it's a very basic question, but it's > been driving me mad... ... I don't know or use wxWidgets, and I've just learned GTK, but I think one good answer is the same as with GTK: use a wxNotebook. You may be able to hide the tabs, or you may just decide they're a good thing to have. To do what you asked, see the wxWindow method Show(), which you would call for each or A and B etc. in response to the command. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From kylotan at gmail.com Thu Nov 17 04:29:23 2005 From: kylotan at gmail.com (Ben Sizer) Date: 17 Nov 2005 01:29:23 -0800 Subject: Python obfuscation In-Reply-To: <86u0ecnxjk.fsf@bhuda.mired.org> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <86fypxr82g.fsf@bhuda.mired.org> <1132133826.129889.97630@g47g2000cwa.googlegroups.com> <86u0ecnxjk.fsf@bhuda.mired.org> Message-ID: <1132219763.382329.260260@g44g2000cwa.googlegroups.com> Mike Meyer wrote: > > Are you claiming therefore that it's more acceptable to you to have to > > access the data remotely every time you use the software than once per > > install? > > Alex's solution doesn't require special treatment for disaster > recovery and/or planning, and as such is a valid answer to the > question. It may be unacceptable for *other* reasons, but it beats > dictating a disaster recovery plan for your software to the end user > hands down on that basis. Sorry, I just don't see this as being a significant difference that makes 'access-always' acceptable and 'access rarely' unacceptable. > > No, I am just pointing out that you are mixing up the concept of an > > actual 'right' such as one embodied in a state's constitution, with an > > implied 'right' that is just an exemption from committing an offence. > > The term 'right' does not even appear in the relevant part of US > > copyright law, except to state that it is a limitation on the copyright > > holder's rights. > > You're still just playing semantic games. The common usage is "fair > use rights." If you mean "... without infringing on the end users > rights, except for fair use rights", then you should say that. Call it what you like; still, I cannot be infringing on your right when such a right does not exist to be infringed. If you want to term it a 'right', feel free, but that's not what you're granted under US law or the Berne Convention. The 'common usage' here leads to a misinterpretation of what you're entitled to. What is actually stated is a limitation on the copyright holder's exclusive rights, which is a very different matter. -- Ben Sizer From eurleif at ecritters.biz Fri Nov 18 12:49:50 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 18 Nov 2005 17:49:50 GMT Subject: How to convert a "long in a string" to a "long"? In-Reply-To: References: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> Message-ID: <2voff.857$Nd.317876@newshog.newsread.com> Sion Arrowsmith wrote: > Steven Bethard wrote: > >>ondekoza at gmail.com wrote: >> >>>s = long("0xffffffffL") >>>ValueError: invalid literal for long(): 0xffffffffL >>> >>>>>int("0xffffffff", 0) >> >>4294967295L > > So why does the base argument to int() (or long()) default to > 10 and not 0? Because it's designed for numbers normal people provide, not for numbers programmers provide. Normal people see 0123 as being equal to 123, not 83. From deepankar.sharma at gmail.com Wed Nov 30 21:43:30 2005 From: deepankar.sharma at gmail.com (Deep) Date: 30 Nov 2005 18:43:30 -0800 Subject: How to list currently defined classes, methods etc In-Reply-To: References: <1133401234.314572.315550@g47g2000cwa.googlegroups.com> Message-ID: <1133405010.479773.10050@g14g2000cwa.googlegroups.com> yes that works. but, it gives one list, which contains everything. now about inferring types? :) From bonono at gmail.com Tue Nov 22 08:56:35 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 05:56:35 -0800 Subject: about sort and dictionary In-Reply-To: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> Message-ID: <1132667795.525317.25980@g14g2000cwa.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > > so what would an entry-level Python programmer expect from this > > piece of code? > > > > for item in a.reverse(): > > print item > > for item in a.reverse(): > > print item > > > > I would expect it to first print a in reverse then a as it was. > > > > a=[1,2,3] > > > > I expect it to print > > > > 3 > > 2 > > 1 > > 1 > > 2 > > 3 > > > really? wouldn't > > 3 > 2 > 1 > 3 > 2 > 1 > > make a lot more sense ? Still don't see why even you ask it again. May be you can enlight me a bit. If this is Haskell, I would expect the result you posted. From robert.kern at gmail.com Tue Nov 8 10:30:25 2005 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 08 Nov 2005 07:30:25 -0800 Subject: any python module to calculate sin, cos, arctan? In-Reply-To: <2se1n1tnel5rdc1eu48njb2ansvbghun3o@4ax.com> References: <2se1n1tnel5rdc1eu48njb2ansvbghun3o@4ax.com> Message-ID: Matt Feinstein wrote: > On Tue, 08 Nov 2005 06:43:51 -0800, Robert Kern > wrote: > >>Matt Feinstein wrote: >> >>>On Tue, 08 Nov 2005 12:30:35 GMT, "Raymond L. Buvel" >>> wrote: >> >>>>http://calcrpnpy.sourceforge.net/clnumManual.html >>> >>>Unless you're using Windows. >> >>Why? Have you tried compiling it and failed? > > Copied from the linked site: > > "Windows is not supported but it may be possible to get this module to > work. You will need to use the GNU tools and figure out how to build > the CLN library. Then you need to figure out how to compile and link > the clnum extension module for the standard Python. If anyone gets > this to work and wants to contribute the results, contact me at > rlbuvel at gmail dot com." > > Note: "may be possible", "you need to figure out", "if anyone gets > this to work". > > The message seems clear to me-- 'If you want this capability, you can > either-- 1) install all the development tools, 2) compile all the > relevant libraries, and then 3) link and compile the Python extension > module at your own risk and on your own (or on your company's) time-- > or, use Linux. Personally, I'd use Linux. On the other hand, not > everyone has that option, & it seems reasonable to me to point out > that there's a non-trivial difficulty here. Okay. I thought you might be adding something substantive more than what was plainly stated on the linked page. Guess not. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fredrik at pythonware.com Tue Nov 8 03:46:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Nov 2005 09:46:39 +0100 Subject: image References: <1d987df30511080018h1111aaa0t79e885438f8e2956@mail.gmail.com> Message-ID: Shi Mu wrote: > why the following code report the error: > Traceback (most recent call last): > File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Python23\Examples\AppB\text.py", line 24, in ? > text.image_create(END, image=photo) > File "C:\Python23\lib\lib-tk\Tkinter.py", line 2882, in image_create > return self.tk.call( > TclError: image "pyimage4" doesn't exist works for me, when running it from a stock CPython interpreter. have you tried running the script outside the pywin environment? From sigzero at gmail.com Tue Nov 8 21:22:47 2005 From: sigzero at gmail.com (Robert Hicks) Date: 8 Nov 2005 18:22:47 -0800 Subject: A Tcl/Tk programmer learns Python--any advice? In-Reply-To: References: Message-ID: <1131502967.138632.94840@g47g2000cwa.googlegroups.com> Ah, another one leaves the fold... : \ Robert From fredrik at pythonware.com Sun Nov 20 09:07:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 15:07:02 +0100 Subject: Type-checking unpickled objects References: Message-ID: Gordon Airporte wrote: >I have this class, and I've been pickling it's objects as a file format > for my program, which works great. The problems are a.) how to handle > things when the user tries to load a non-pickled file, and b.) when they > load a pickled file of the wrong class. > > a. I can handle with a general exception I guess. I just tried to > pickle.load() a .pyc and it failed with a 'KeyError' exception - however > that works. It might do that every time, it might not. I hope you're aware of the fact that pickle is not suitable for applications where you cannot trust the source; see e.g. http://www.livejournal.com/users/jcalderone/15864.html (one of the comments show how to place restrictions on what can be loaded from a given pickle) > Regarding b., if I type check I simply get the 'instance' type, which > doesn't get me all of the way there because I might have an instance of > the wrong class. I can't find any sort of __type__ attribute to set in > the objects. Perhaps I should use __str__? how about a plain obj = cPickle.load(...) if not isinstance(obj, Class): print "expected a Class instance" From mkonrad at syr.edu Fri Nov 11 23:38:39 2005 From: mkonrad at syr.edu (Michael Konrad) Date: Sat, 12 Nov 2005 04:38:39 GMT Subject: directory listing In-Reply-To: References: <14cltzqwyklwl.17i7f7qnfnlh0$.dlg@40tude.net><192B1E05-3AB1-481D-9568-3632313F31E6%mkonrad@syr.edu><1d987df30511111423o572172eay36870d09220233d7@mail.gmail.com><1d987df30511111444m1ddfaca2qcf0acc32e49fc108@mail.gmail.com> <1d987df30511111500j57418032p12c5f30b85aaa594@mail.gmail.com> Message-ID: <437571CF.8010401@syr.edu> This is what I decided on for a solution. I haven't tested it cross-platform yet. import os def dirListing(directory='/Users/mkonrad'): """Returns a list of directories.""" #variables dirs = [] #list of directories #list of directories and files listing = os.listdir(directory) #get just the directories for x in listing: if os.path.isdir(directory+os.sep+x): dirs.append(x) return dirs Fredrik Lundh wrote: > "Shi Mu" wrote: > >> print buildList() gets lots of stuffs from my temp directory(there do >> exist lots of files). >> But why "print x' has nothing? > > C:\>more script.py > import os > > def buildList( directory='c:\TEMP' ): > dirs = [ ] > listing = os.listdir(directory) > for x in listing: > x = os.path.join(directory, x) > print x > if os.path.isdir(x): > dirs.append(x) > return dirs > > print buildList() > > C:\>dir temp > ... > > 2005-11-12 00:00 . > 2005-11-12 00:00 .. > 2005-11-12 00:00 20 bacon.dat > 2005-11-12 00:00 egg > 2005-11-12 00:00 20 spam.txt > 2 fil(er) 40 byte > 3 katalog(er) 9 818 021 888 byte ledigt > > C:\>python script.py > c:\TEMP\bacon.dat > c:\TEMP\egg > c:\TEMP\spam.txt > ['c:\\TEMP\\egg'] > > > > > From martin.witte at gmail.com Wed Nov 2 14:53:37 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 2 Nov 2005 11:53:37 -0800 Subject: Threading In-Reply-To: <1130959652.003475.26650@o13g2000cwo.googlegroups.com> References: <1130959652.003475.26650@o13g2000cwo.googlegroups.com> Message-ID: <1130961217.848546.68450@g14g2000cwa.googlegroups.com> How do you use threads? With threading.Thread objects? Then this recipe might help, it did it for me. For further assistance please post your code. From steve at holdenweb.com Tue Nov 8 10:50:43 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 Nov 2005 15:50:43 +0000 Subject: [OTAnn] Feedback In-Reply-To: <24267576.601131397871466.JavaMail.tomcat5@slave1.roomity.com> References: <24267576.601131397871466.JavaMail.tomcat5@slave1.roomity.com> Message-ID: <4370C953.9010101@holdenweb.com> shenanigans wrote: > I was interested in getting feedback from current mail group users. > > We have mirrored your mail list in a new application that provides a more aggregated and safe environment which utilizes the power of broadband. > > Roomity.com v 1.5 is a web 2.01 community webapp. Our newest version adds broadcast video and social networking such as favorite authors and an html editor. > > It?s free to join and any feedback would be appreciated. > Well, my feedback would be "stop spamming mailing lists". Especially since you clearly aren't even good at spamming and have very few clues about mailing lists. 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 graham.abbott at gmail.com Thu Nov 3 01:51:16 2005 From: graham.abbott at gmail.com (Graham) Date: 2 Nov 2005 22:51:16 -0800 Subject: how can I run python interactively? In-Reply-To: <1130998605.892334.70810@g49g2000cwa.googlegroups.com> References: <1130998605.892334.70810@g49g2000cwa.googlegroups.com> Message-ID: <1131000676.637907.115220@g14g2000cwa.googlegroups.com> You could use either: s = raw_input("Please Hit a Key...") s being the string they typed before hitting enter. or you could use print "Please hit a key..." s = sys.stdin.readline() the only reason i recommend the second is because i believe i saw in a PEP that raw_input was being depreciated at some point, however i may be wrong on that. (correction anyone?) From bignose+hates-spam at benfinney.id.au Mon Nov 28 16:45:15 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Nov 2005 08:45:15 +1100 (EST) Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: Rocco Moretti wrote: > One point that frequently gets ignored in licensing debates: > > The value of a license is directly proportional to the amount of > time, effort, and money you are willing to spend enforcing it. That's a very important factor, yes. > It doesn't matter how fancy the legal wording is - it is up to you, > as the copyright holder, to bring legal action This is true as far as it goes. What is sought, though, is not "fancy legal wording", but clarity of intent. The wording is *extremely* important, since it must express, as clearly and unambiguously as possible, the intent of the license granter. Legal action and judicial interpretation will play their part, but the clearer you can make the license text, the less guesswork is needed on both sides to determine what is and is not permitted in the license terms. The GNU GPL, and the Expat license (n?e X11, MIT, 2-clause BSD, etc.), are popular in part because the intent of their terms is expressed very clearly. -- \ "He who wonders discovers that this in itself is wonder." -- | `\ Maurits Cornelis Escher | _o__) | Ben Finney From fredrik at pythonware.com Sun Nov 20 13:23:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 19:23:50 +0100 Subject: PATH environment variable References: <1132451443.807757.251540@g43g2000cwa.googlegroups.com><7p%ff.3253$3o6.852573@twister.southeast.rr.com> <1132510146.835670.97990@o13g2000cwo.googlegroups.com> Message-ID: mirandacascade at yahoo.com wrote: > Do these observations fit with what is stated in section 6.1.1 of the > Python Library Reference? yes. what part of your observations makes you think that the environment isn't "captured" (i.e. copied from the process environ- ment) when the os module is imported ? (hint: when you start a new process, it gets a *copy* of the current environment. changes to the original won't affect this copy. all modern operating systems work the same way). From steve at holdenweb.com Thu Nov 3 07:20:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Nov 2005 12:20:06 +0000 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: Antoon Pardon wrote: > Op 2005-11-03, Steven D'Aprano schreef : > > >>>There are two possible fixes, either by prohibiting instance variables >>>with the same name as class variables, which would allow any reference >>>to an instance of the class assign/read the value of the variable. Or >>>to only allow class variables to be accessed via the class name itself. >> >>There is also a third fix: understand Python's OO model, especially >>inheritance, so that normal behaviour no longer surprises you. > > > No matter wat the OO model is, I don't think the following code > exhibits sane behaviour: > > class A: > a = 1 > > b = A() > b.a += 2 > print b.a > print A.a > > Which results in > > 3 > 1 > I don't suppose you'd care to enlighten us on what you'd regard as the superior outcome? 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 fredrik at pythonware.com Sun Nov 6 03:31:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 6 Nov 2005 09:31:54 +0100 Subject: Instead of obsessing over the library *reference*, why not use other documentation? References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com><1131192936.228280.150530@g44g2000cwa.googlegroups.com> Message-ID: Charlton Wilbur wrote: > This is one of the places where Apple's Cocoa documentation shines: > there are frequently snippets of code accompanying more complicated > methods, which is nice, but there are a couple dozen small sample > programs that demonstrate how to use particular aspects of the > framework, available with full source code. There is no shortage of code examples for Python modules either, thanks to people who've worked hard to prepare cookbooks and example collections. If people began using those instead of complaining about the library reference or their own inability to use the help() command, everybody would save a lot of time. (this would also make it easier for less ignorant "newbies" to find the examples: when Xah first complained about gzip, googling for "python gzip example" brought up a full page of examples. If you do the same search today, you'll still find examples, but 5 of the top 10 hits are references to Xah's problems with the library reference. A few more rounds, and people will have to start adding -xah to their Python searches to get quality results.) From grante at visi.com Wed Nov 9 19:30:49 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 10 Nov 2005 00:30:49 -0000 Subject: Floating numbers and str References: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> <11n4lkg3hlboq08@corp.supernews.com> <1131582008.936061.299280@f14g2000cwb.googlegroups.com> Message-ID: <11n555pkejle360@corp.supernews.com> On 2005-11-10, Dan Bishop wrote: > Grant Edwards wrote: >> On 2005-11-09, Tuvas wrote: >> >> > I would like to limit a floating variable to 4 signifigant digits, when >> > running thorugh a str command. >> >> Sorry, that's not possible. > > Technically, it is. Ah well, I assumed that by "floating variable" he meant the built-in "float" type. -- Grant Edwards grante Yow! I always wanted a at NOSE JOB!! visi.com From sybrenUSE at YOURthirdtower.com.imagination Fri Nov 4 05:09:41 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 4 Nov 2005 11:09:41 +0100 Subject: I Need Motivation Part 2 References: Message-ID: blahman (blah at blah.blah) enlightened us with: > i m losing my motivation with python because there are sooo many > modules, that i cant just learn them all, this deters from c or c++ > in which there are only a limited number of header files. There are over 2800 header files on my system in /usr/include. What do you mean "a limited number of header files"? 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 fredrik at pythonware.com Wed Nov 23 11:55:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 17:55:35 +0100 Subject: defining the behavior of zip(it, it) (WAS: Converting a flatlist...) References: <1132708467.045227.284000@z14g2000cwz.googlegroups.com> Message-ID: Steven Bethard wrote: > Then why document itertools.izip() as it is? The documentation there is > explicit enough to know that izip(it, it) will work as intended. Should > we make the documentation there less explicit to discourage people from > using the izip(it, it) idiom? depends on whether you interpret "equivalent" as "having similar effects" or "corresponding or virtually identical especially in effect or function" or if you prefer some other dictionary definition... because there are of course plenty of subtle differences between a Python generator C type implementation. let's see... >>> from itertools import izip as izip1 >>> from library documentation import izip as izip2 >>> izip1 >>> izip2 alright, close enough. >>> izip1.func_name Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'itertools.izip' has no attribute 'func_name' >>> izip2.func_name 'izip' hmm. >>> class myiter: ... def next(self): ... raise ValueError("oops!") ... >>> izip2(myiter()) >>> izip1(myiter()) Traceback (most recent call last): File "", line 1, in ? TypeError: izip argument #1 must support iteration oops. >>> class myiter: ... def __iter__(self): ... return self ... def next(self): ... raise ValueError("oops!") ... >>> izip1(myiter()) >>> izip2(myiter()) that's better. now let's run it: >>> list(izip1(myiter())) Traceback (most recent call last): File "", line 1, in ? File "", line 5, in next ValueError: oops! >>> list(izip2(myiter())) Traceback (most recent call last): File "", line 1, in ? File "i.py", line 6, in izip2 result = [i.next() for i in iterables] File "", line 5, in next ValueError: oops! different stack depths. hmm. so how equivalent must something be to be equivalent? From mikael at isy.liu.se Thu Nov 17 05:29:21 2005 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 17 Nov 2005 11:29:21 +0100 Subject: newbie - How do I import automatically? In-Reply-To: References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> <3u0el9Fum367U1@individual.net> <1132154531.395649.168870@g14g2000cwa.googlegroups.com> <1132219559.826657.209940@f14g2000cwb.googlegroups.com> Message-ID: bobueland at yahoo.com wrote: >> I tried to do it on my computer (win XP). I put an extra line in >> PyShell.py >> [snip] >> # test >> sys.modules['__main__'].__dict__['os'] = os >> [snip] >> Then when I start idle I get >> >> IDLE 1.1.1 >> >>>>> dir() >> >> >> ['__builtins__', '__doc__', '__name__'] >> >> >> So I don't see 'os' >> >> Do you see 'os' on your computer. If yes, what could be the difference? > > I answered: > Yes, I do. [snip details] I have to step back a bit. IDLE seems to work differently depending on how it is started. My comments above hold when I start IDLE by right-clicking on a python-file and choosing "Edit with IDLE". If I instead start IDLE itself (from the windows start-menu) I get the same behaviour as you do, namely no os around. Another difference, which I've noted before is that shell restart is only available when IDLE has been started this way. All this seems to be handled in PyShell.py, but I do not have the time to trace that in any detail. Regards /MiO From bonono at gmail.com Thu Nov 10 13:16:41 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 10:16:41 -0800 Subject: help make it faster please In-Reply-To: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> Message-ID: <1131646601.299316.166570@g47g2000cwa.googlegroups.com> why reload wordlist and sort it after each word processing ? seems that it can be done after the for loop. pkilambi at gmail.com wrote: > I wrote this function which does the following: > after readling lines from file.It splits and finds the word occurences > through a hash table...for some reason this is quite slow..can some one > help me make it faster... > f = open(filename) > lines = f.readlines() > def create_words(lines): > cnt = 0 > spl_set = '[",;<>{}_&?!():-[\.=+*\t\n\r]+' > for content in lines: > words=content.split() > countDict={} > wordlist = [] > for w in words: > w=string.lower(w) > if w[-1] in spl_set: w = w[:-1] > if w != '': > if countDict.has_key(w): > countDict[w]=countDict[w]+1 > else: > countDict[w]=1 > wordlist = countDict.keys() > wordlist.sort() > cnt += 1 > if countDict != {}: > for word in wordlist: print (word+' '+ > str(countDict[word])+'\n') From bobueland at yahoo.com Tue Nov 15 16:55:27 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 15 Nov 2005 13:55:27 -0800 Subject: newbie - How do I import automatically? References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> Message-ID: <1132091727.774849.95480@o13g2000cwo.googlegroups.com> I've tried as you said but it doesn't work. I'm working with Windows XP. I right click at my computer go to Advanced, choose Environment Variables and set PYTHONSTARTUP variable to C:\Python24\binit.py. It looks like this # binit.py from btools import * I've restarted the computer and started IDLE but I only get IDLE 1.1.1 >>> dir() ['__builtins__', '__doc__', '__name__'] >>> What could be wrong? From steve at REMOVETHIScyber.com.au Fri Nov 4 21:59:24 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 13:59:24 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> <86wtjof19j.fsf@bhuda.mired.org> Message-ID: On Fri, 04 Nov 2005 18:20:56 -0500, Mike Meyer wrote: > Steven D'Aprano writes: >> equal? Some things are a matter of objective fact: should CPython use a >> byte-code compiler and virtual machine, or a 1970s style interpreter that >> interprets the source code directly? > > For the record, I've only seen one interpreter that actually > interpreted the source directly. Pretty much all of the rest of them > do a lexical analysis, turning keywords into magic tokens (dare I say > "byte codes") and removing as much white space as possible. Or maybe > that's what you meant? We could argue about details of a throw away line for hours :-) What I meant was, there is the way Python does it, and then there are (or were) interpreters that when faced with a block like this: for i in range(10): print i parses "print i" ten times. It doesn't really matter whether any interpreters back in the 1970s were actually that bad, or just toy interpreters as taught about in undergrad university courses. -- Steven. From http Mon Nov 28 00:43:44 2005 From: http (Paul Rubin) Date: 27 Nov 2005 21:43:44 -0800 Subject: General question about Python design goals References: Message-ID: <7xr791wcmn.fsf@ruckus.brouhaha.com> Jean-Paul Calderone writes: > >I can't think of a single use case for the addition (+) operator > >working where either of the operands happens to be the number > >0x15f1ef02d9f0c2297e37d44236d8e8ddde4a34c96a8200561de00492cb94b82 (a > >random number I just got out of /dev/urandom). > > If you seriously believe what you just wrote, you have failed to > understand the phrase "use case" (and possibly a lot of other > things related to programming ;) Heh, you must not remember the famous Pentium FDIV bug, where the Pentium gave incorrect results for floating point division with certain rare combinations of operands. Intel at first refused to acknowledge that the bug was a real problem (although it had already been found and quietly fixed in later steppings), then refused to replace people CPU's unless they could explain their use case where the error could cause them a practical problem. My school's biology lab got its Pentiums exchanged by claiming it was using them to model some kind of experimental drug treatment (I don't know whether the claim was true) but other people just got told: sorry, but what you're doing doesn't need correct FDIV results. Intel of course eventually had to back down and exchange everyone's cpu's after a huge public outcry. > However (fortunately for you) I suspect you don't. If you really > did, you may want to pick up one of those platitude-filled XP books > and give it a careful read. You may find there's more there than > you were previously aware. I've read some of the XP stuff. I see it mostly as a way of explaining normal programmers' instincts to PHB's. If the books did some good in reducing PHB interference in some projects, that's nice; however, while I felt that the general approach to programming running through them was good, the specific practices and the type of following they got bordered on cultish. From joewong at mango.cc Wed Nov 23 21:11:34 2005 From: joewong at mango.cc (Joe Wong (Mango)) Date: Thu, 24 Nov 2005 10:11:34 +0800 Subject: single process instance Message-ID: <014201c5f09c$65018510$7f00a8c0@scl01.siliconcreation.com> Dear all, Is there any library / function that I can put in my process to make sure he is the one and only one instance running in the box? Best regards, - Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From evenprimes at gmail.com Thu Nov 10 12:10:31 2005 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 10 Nov 2005 12:10:31 -0500 Subject: wxPython newbie question, creating "mega widgets" , and DnD In-Reply-To: <1131635970.831338.109280@g49g2000cwa.googlegroups.com> References: <1131635970.831338.109280@g49g2000cwa.googlegroups.com> Message-ID: On 10 Nov 2005 07:19:30 -0800, akameswaran at gmail.com wrote: > I've made the switch from tKinter to wxPython. I'm slowly trying to > learn it, but I had a question - what is the appropriate object to > subclass to create a "mega widget" ie A listbox with it's add/delete > buttons already built in? > > wxPanel seems a possibility - any thoughts? When I've created this type of thing I usually start with a wx.Panel. It will depend on how you plan to use your new mega-widget, but I suspect that the wx.Panel gives you the most flexibility. You can throw a panel pretty much anywhere and it seems to work just fine. :) PS: Congrats on giving wxPython a try. It's far from the perfect framework, but it seems the most Pythonic to me and lets me get the most accomplished with the least setup. YMMV. -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From aum at spam.me.please Tue Nov 8 01:02:01 2005 From: aum at spam.me.please (aum) Date: Tue, 08 Nov 2005 19:02:01 +1300 Subject: ANN: C++ support for Pyrex Message-ID: Hi, Many Pyrex users are grateful for the ability to seamlessly integrate Python and C code without the menial tedium of hand-coding extensions in pure C. However, Pyrex has a frustrating lack of C++ support, something its esteemed author doesn't yet have the time to fix. As an interim solution, I've just released a first cut of 'pyrexembed', a system that lets you embed C++ code directly into your Pyrex sources. More info, download etc at http://www.freenet.org.nz/python/pyrexembed -- Cheers Aum From fredrik at pythonware.com Fri Nov 11 16:37:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 22:37:39 +0100 Subject: directory listing References: Message-ID: "SU News Server" wrote: > I've struggled with this for quite a while and I'm am just not sure > what is going on. I have the following code > import os > > def buildList( directory='/Users/mkonrad' ) > > dirs = [ ] > > listing = os.listdir(directory) > > for x in listing: > if os.path.isdir(x): > dirs.append(x) > > return dirs > > This always returns an empty list. > Now if I change it so that directory='.' or directory=os.getcwd() > Then it returns a list of directories. hint: if you're not sure what's going on in your program, adding a print statement or two is an easy way to figure it out. like, say: for x in listing: print x if os.path.isdir(x): dirs.append(x) (try this before you continue) : : : the problem is that os.listdir returns a list of filenames, without the preceeding directory name. you can add an os.path.join for x in listing: x = os.path.join(directory, x) if os.path.isdir(x): dirs.append(x) or use the glob module instead: listing = glob.glob(os.path.join(directory, "*")) hope this helps! From bokr at oz.net Tue Nov 22 12:52:12 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 17:52:12 GMT Subject: Why are there no ordered dictionaries? References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> Message-ID: <43835452.475686410@news.oz.net> On Tue, 22 Nov 2005 10:06:07 +0100, Christoph Zwerschke wrote: >Bengt Richter schrieb: >> Ok, so if not in the standard library, what is the problem? Can't find what >> you want with google and PyPI etc.? Or haven't really settled on what your >> _requirements_ are? That seems to be the primary problem people who complain >> with "why no sprollificator mode?" questions. > >What I don't understand is why legitimate questions such as "why are >there no ordered dictionaries" are immediately interpreted as >*complaints* and not just as questions. If I ask such a question, I am >not complaining but trying to simply figure out *why* there is no such >thing. Probably there are reasons and all I want to know is find these >reasons and learn a little bit more about Python in doing so. > >Why can't such questions be discussed in a factual, calm and friendly way? Sorry, I was tired and vented some impatience. I'm mostly friendly ;-) I took the "why" in a different sense than it was meant, I guess. Sort of like hearing "why haven't I been served yet" in a restaurant, and having to say, "I don't work here, you'll have to ask the waiter." > > > They don't know what they really mean when it comes down to a DYFR > > (Define Your Felicitous Requirements) challenge. > >I don't think that this was true in this case, and even if this is the >outcome, those who asked the question will have learned something. I agree again. > >I think a discussion group is not there for only presenting mature, >sophisticated thoughts and concepts, but also for "thinking loud" >together with other about these issues. We all know that clarifying our >thoughts works often best if you discuss them with others. And I think >that's one purpose of discussion lists. Asking questions should not be >immediately be discouraged, even silly questions. If it is really a FAQ, >you can simply point to the FAQ or add the answer in the FAQ list if it >is missing there. Agreed again. Thank you for your nice reply. Regards, Bengt Richter From kehilanyas at hotmail.com Wed Nov 16 09:50:36 2005 From: kehilanyas at hotmail.com (Gary Kshepitzki) Date: Wed, 16 Nov 2005 14:50:36 -0000 Subject: How to write an API for a Python application? References: <437af434@news.bezeqint.net> <1132144040.194283.285890@o13g2000cwo.googlegroups.com> Message-ID: <437b2924$1@news.bezeqint.net> Thanks Its an interesting solution but I need a more closely coupled solution, with real time events, so the communication really has to be 2 ways, and not by polling. Thanks for putting the time and though. Gary wrote in message news:1132144040.194283.285890 at o13g2000cwo.googlegroups.com... > While not sure of the behavior you are trying to achieve, XML-RPC comes > to mind. But it's based on HTTP protocol in which the client puts > request to the server which has to respond. The server cannot initiate > interactions. > XML-RPC is both widely avalaible, and very easy to implement. > > NOTE: in order for the server to raise events in the client, the client > needs only raise periodically a *need-anything-from-me* type of request > which permits the server to return its request in response to the > client. Naturally this solution makes superfluous calls takes some > bandwidth, so it might not be appropriate in every circumstance. > From uche.ogbuji at gmail.com Fri Nov 4 11:37:03 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 4 Nov 2005 08:37:03 -0800 Subject: XML DOM: XML/XHTML inside a text node In-Reply-To: <1130994355.266863.264890@g14g2000cwa.googlegroups.com> References: <1130994355.266863.264890@g14g2000cwa.googlegroups.com> Message-ID: <1131122223.062401.256790@z14g2000cwz.googlegroups.com> """ In my program, I get input from the user and insert it into an XHTML document. Sometimes, this input will contain XHTML, but since I'm inserting it as a text node, xml.dom.minidom escapes the angle brackets ('<' becomes '<', '>' becomes '>'). I want to be able to override this behavior cleanly. I know I could pipe the input through a SAX parser and create nodes to insert into the tree, but that seems kind of messy. Is there a better way? """ Amara 1.1.6 supports inserting an XML fragment into a document or element object. Many short examples here: http://copia.ogbuji.net/blog/2005-09-21/Dare_s_XLI excerpt: Adding a element as a child of the element' contacts.xml_append_fragment('%s'%'206-555-0168' http://uche.ogbuji.net/tech/4suite/amara -- 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 finite.automaton at gmail.com Fri Nov 4 20:27:58 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 4 Nov 2005 17:27:58 -0800 Subject: C extension + libm oddity [fmod(2.0, 2.0) == nan ?!] In-Reply-To: <7x4q6roq15.fsf@ruckus.brouhaha.com> References: <1131152542.351552.255140@g44g2000cwa.googlegroups.com> <7x4q6roq15.fsf@ruckus.brouhaha.com> Message-ID: <1131154078.499355.81260@o13g2000cwo.googlegroups.com> > Have you compiled the C extension with all optimization turned off? Yes. The C extension's objects are compiled only with the debugging flag and -fPIC for position indepdendent code, necessary for shared objects. No optimization. The only things that have any optimization are Python and glibc (using -O2) I guess I should try glibc without optimization too... ick. > I suggest disassembling it and stepping through it instruction by instruction if you haven't done that. Unfortunately I think you are correct ;-) From larry.bates at websafe.com Wed Nov 30 12:10:15 2005 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 30 Nov 2005 11:10:15 -0600 Subject: import Excel csv - files In-Reply-To: References: <000001c5f584$f90e7690$6106a8c0@samsungx30> Message-ID: <2fOdnb1W29ufQBDeRVn-iA@comcast.com> You should actually explain what you mean by "export". Excel has a Save As HTML that would save everything out to HTML or you can do Save As .CSV. Hard to tell what you want. I suspect that to get to the cell comments you will need to go through COM interface to Excel. -Larry Bates Micah Elliott wrote: > On Nov 30, J?rgen Kemeter wrote: > >> My actual Problem: >> The Excel workbook contains several spreadsheets. These are >> linked through Hyperlinks, and contain several cell comments. How >> can I export these comments and Hyperlinks using Python? > > > Are you just wanting read a .xls file with Python? pyExcelerator > can > do that job. Documentation is non-existent AFAICT, but the tools > directory has good examples. > > I don't know how comments/hyperlinks are treated but you can try and > find out. > From noway at nospam.com Tue Nov 1 16:23:23 2005 From: noway at nospam.com (CppNewB) Date: Tue, 01 Nov 2005 21:23:23 GMT Subject: Python's website does a great disservice to the language References: <1130879955.704130.183770@f14g2000cwb.googlegroups.com> Message-ID: wrote in message news:1130879955.704130.183770 at f14g2000cwb.googlegroups.com... > CppNewB>and maybe a readable default font is in order.< > > That font looks fine to me, maybe there's a problem in the default font > of your browser, you can probably fix your problem... > "Explicit is better than implicit" I know how to change my default, you know how to change your default font, but not everyone else does. If there's a more readable, default solution, it should be utilized. From steven.bethard at gmail.com Thu Nov 17 15:01:39 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Nov 2005 13:01:39 -0700 Subject: how to organize a module that requires a data file In-Reply-To: References: Message-ID: <85mdnVqt99QAfOHeRVn-pQ@comcast.com> Terry Hancock wrote: > On Thu, 17 Nov 2005 12:18:51 -0700 > Steven Bethard wrote: > >>My problem is with the text file. Where should I keep it? >> >>I can only think of a few obvious places where I could >>find the text file at import time -- in the same >>directory as the module (e.g. lib/site-packages), in the >>user's home directory, or in a directory indicated by an >>environment variable. > > > Why don't you search those places in order for it? > > Check ~/.mymod/myfile, then /etc/mymod/myfile, then > /lib/site-packages/mymod/myfile or whatever. It won't take > long, just do the existence checks on import of the module. > If you don't find it after checking those places, *then* > raise an exception. > > You don't say what this data file is or whether it is > subject to change or customization. If it is, then there is > a real justification for this approach, because an > individual user might want to shadow the system install with > his own version of the data. The file is a lookup table of word stems distributed by the University of Pennsylvania. It doesn't really make sense for users to customize it, because it's not a configuration file, but it is possible that UPenn would distribute a new version at some point. That's what I meant when I said "it's not a per-user configuration - it's a data file shared by all users". So there should be exactly one copy of the file, so I shouldn't have to deal with shadowing. Of course, even with only one copy of the file, that doesn't mean that I couldn't search a few places. Maybe I could by default put it in lib/site-packages, but allow an option to setup.py to put it somewhere else for anyone who was worried about putting 10MB into lib/site-packages. Those folks would then have to use an environment variable, say $MORPH_FLAT, to identify the directory they . At module import I would just check both locations... I'll have to think about this some more... STeVe From steve at REMOVEMEcyber.com.au Mon Nov 14 21:50:04 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 15 Nov 2005 13:50:04 +1100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> <87psp2ao7s.fsf@lucien.dreaming> Message-ID: <43794CDC.6000006@REMOVEMEcyber.com.au> Bj?rn Lindstr?m wrote: > So, I guess no one read my explanation of why this an issue about more > than implementing enums (which is fairly trivial, as we have seen). I read it. I don't see that it is an issue, and I especially don't see why it is relevent to Pierre's usage of symbols. In your earlier post, you say: "The problem with that is that you can't pass around the names of objects that are used for other things." That's demonstrably not true. If you know that the name of something is Parrot, then you can pass the string "Parrot" and use it in many ways: print obj.__getattribute__["Parrot"] instance.__dict__["Parrot"] = 42 I'm not aware of anything that you can do to a name/object binding that can't also be done by a string. Perhaps I've missed something -- anyone? If you don't know the name, well, how did it get into your program in the first case? Where did it come from? If it came from user input, then surely that is a string, yes? You also suggested: "Being able to do that precludes the need for converting going back and forth between strings and method names when you need to do things like keeping a list of function names, even when you need to be able to change what those function names point to." I'm not convinced. Instead of keeping a list of function names, just keep a list of functions -- functions are first-class objects in Python. If you need to change what the function names point to, simply rebind the list item to another function. The only benefit I can see for being able to refer to functions by name would be if you are writing a formula evaluator, it might be useful to have "sin"(0) evaluate directly. But I don't like the idea of making strings aliases to executables, except through a single well-understood mechanism. I'd much rather accept one intermediate layer than create a second mechanism of function execution: table = {"sin": math.sin, "cos": math.cos} # easy to modify table["sin"] = my_better_sine_function result = table["sin"](0) If I have missed a usage case, perhaps you should give at specific example. -- Steven. From mwm at mired.org Fri Nov 18 20:48:06 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 18 Nov 2005 20:48:06 -0500 Subject: Importing a class without knowing the module References: <867jb6n7cw.fsf@bhuda.mired.org> <86veyqlnrn.fsf@bhuda.mired.org> <1h66rw8.wlp7nb19e5629N%aleax@mail.comcast.net> <86k6f6lgvy.fsf@bhuda.mired.org> <1h66w9j.1d82do2qfe2b1N%aleax@mail.comcast.net> <86zmo2jvsw.fsf@bhuda.mired.org> <1h67qx0.1y62ktrcq00pbN%aleax@mail.comcast.net> <86psoxkcgb.fsf@bhuda.mired.org> <1h686or.1t4dvb17nsb8wN%aleax@mail.comcast.net> <86d5kxk0wd.fsf@bhuda.mired.org> <1h68bs9.1rc6hd71wb4wt2N%aleax@mail.comcast.net> Message-ID: <86r79dif1l.fsf@bhuda.mired.org> aleax at mail.comcast.net (Alex Martelli) writes: > You did help me to better understand some of the roots of your many > mistaken assertions in this thread, from your first "How about adding > Foo.__file__" proposal onwards, yes -- thank you. I claim I haven't made a single mistaken assertion in this thread. Referencing class.__file__ instead of module.__file__ was a mistake, but not an assertion. In fact, when I did that, I asked the OP what was wrong with it. You have read into some of the things I've written assertions which simply weren't there. For instance, I said "you may not have the module name", which led you to ask for an example of a class without an __module__ attribute. I never asserted that you could get a class without a __module__ attribute, merely that you could get classes where the module name wasn't useful. if you had spent your time reading the text a bit more carefully, you might have saved us both some time. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martin at v.loewis.de Wed Nov 2 17:23:42 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 Nov 2005 23:23:42 +0100 Subject: urlencode with high characters In-Reply-To: <1130963461.180637.224910@g43g2000cwa.googlegroups.com> References: <1130963461.180637.224910@g43g2000cwa.googlegroups.com> Message-ID: <43693c6e$0$11842$9b622d9e@news.freenet.de> Jim wrote: > My understanding is that I am supposed to be able to urlencode anything > up to the top half of latin-1 -- decimal 128-255. I believe your understanding is incorrect. Without being able to quote RFCs precisely, I think your understanding should be this: - the URL literal syntax only allows for ASCII characters - bytes with no meaning in ASCII can be quoted through %hh in URLs - the precise meaning of such bytes in the URL is defined in the URL scheme, and may vary from URL scheme to URL scheme - the http scheme does not specify any interpretation of the bytes, but apparantly assumes that they denote characters, and follow some encoding - which encoding is something that the web server defines, when mapping URLs to resources. If you get the impression that this is underspecified: your impression is correct; it is underspecified indeed. There is a recent attempt to tighten the specification through IRIs. The IRI RFC defines a mapping between IRIs and URIs, and it uses UTF-8 as the encoding, not latin-1. Regards, Martin From fredrik at pythonware.com Sun Nov 6 09:38:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 6 Nov 2005 15:38:58 +0100 Subject: Can't instantiate class References: <436E124B.7000003@dbmdata.com> Message-ID: David Mitchell wrote: > Here is a very basic question, but it is frustrating me to no end > nonetheless. > > I have one file called addLink.py. In a method in this file I am trying > to instantiate a class and call a method from that class. Here is the code: > > def getCategories(): > # instantiate the DataUtil class > db = DataUtil() > # and call the getConnection() method > connection = db.getConnection() > > ... > > At the top of this file I am importing the DataUtil module (named > DataUtil.py) with this line: > > import DataUtil > When I execute the getCategories() method above I get the following error: > > File "C:\Apache2\htdocs\Intranet\addLink.py", line 42, in getCategories > db = DataUtil() > > TypeError: 'module' object is not callable > > Any idea what I'm doing wrong? the error message contains the full story: when you do "import DataUtil", you get an object named "DataUtil" that represents the module. (import is not an include statement). and modules are not callable. to access the DataUtil object *inside* the DataUtil module, use import DataUtil db = DataUtil.DataUtil() or from DataUtil import DataUtil db = DataUtil() also see: http://effbot.org/zone/import-confusion.htm From eurleif at ecritters.biz Fri Nov 11 21:18:11 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 12 Nov 2005 02:18:11 GMT Subject: list of lambda In-Reply-To: References: Message-ID: jena wrote: > hello, > when i create list of lambdas: > l=[lambda:x.upper() for x in ['a','b','c']] > then l[0]() returns 'C', i think, it should be 'A' Fredrik Lundh provided the general solution, but in this specific case, the simplest solution is: l = [x.upper for x in ['a', 'b', 'c']] From steve at holdenweb.com Fri Nov 25 10:31:14 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Nov 2005 15:31:14 +0000 Subject: Help need In-Reply-To: References: Message-ID: sr_sutar wrote: > HI group, > > During doing some codeing with python i got the inline error, > > > def my_word( offset ): > try: > j = ord(t[offset]) + 256*ord(t[offset+1])# + 65536*ord(t > [offset+2]) + 16777216*ord(t[offset+3]) > #return j > except IndexError: > # print "Exception" > return j > def my_bpp( mode ): > if mode & 0xF8000000: > return 1 << ( ( (mode >> 27) & 31 ) - 1 ) > if mode==20 or mode==27: > return 4 > return 0 > > > > File "../../../source/ant//tools/scripts/python/sprites.py", line 31 > j = ord(t[offset]) + 256*ord(t[offset+1])# + 65536*ord(t > [offset+2]) + 16777216*ord(t[offset+3]) > ^ > IndentationError: expected an indented block > make[2]: *** [swapped.out] Error 1 > make[1]: *** [ant_final_target] Error 2 > make: *** [rest] Error 2 > > > Any Help? > The "except" clause requires an indented suite, which you've commented out. You might also want to look at the struct modlue if you want to convert 4 bytes into an integer. 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 mensanator at aol.com Wed Nov 23 13:27:08 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 23 Nov 2005 10:27:08 -0800 Subject: hex string to hex value In-Reply-To: References: <1132703785.938991.11090@z14g2000cwz.googlegroups.com> Message-ID: <1132770428.812345.311030@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > mensanator at aol.com wrote: > > > Fredrik Lundh's solution works if the hex string starts with "0x" > > that's what "interpret [it] as a Python literal" meant. I know from personal experience that the implications of that sometimes go right over the head of a newbie. Did I do something wrong by pointing out exactly what that means? Isn't it better to have the OP understand the problem than simply solve it for him? > > > (which it will when the string is created with the hex function). > > > > >>> int(hex(m),0) > > 66 > > > > But it won't work without the "0x". > > > > >>> int('0x1A',0) > > 26 > > >>> int('0x1A',16) > > 26 > > >>> int('1A',16) > > 26 > > >>> int('1A',0) > > > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > int('1A',0) > > ValueError: invalid literal for int(): 1A > > as the error message says, 1A isn't a valid literal. Yes, not all strings of valid hex characters are valid literals. But surely you're not suggesting that the user simply give up when faced with that situation? > > From bonono at gmail.com Thu Nov 10 07:56:34 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 04:56:34 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> Message-ID: <1131627394.890394.200070@g44g2000cwa.googlegroups.com> Peter Hansen wrote: > (I say "readable or somehow better" since you stated in another post "I > just try to use list/generator expression when possible" but you didn't > explain your reason for doing so. I assume you have some reason other > than arbitrary whim.) The reason is simple: I found it easier to read for me and using list/generator expression helped me uncover a number of subtle bugs comparing with an imperative approach. on its own : takewhile(lambda x: condition(x), some_generator) is not very much difference than(well, still more things to type) (x for x in some_generator when condition(x)) but when I have a number of them in the same expression, the takewhile/dropwhile becomes to add up. From saint.infidel at gmail.com Wed Nov 9 09:46:29 2005 From: saint.infidel at gmail.com (Lao Tzu) Date: Wed, 9 Nov 2005 07:46:29 -0700 Subject: cx_Oracle callproc output parameters In-Reply-To: <4371E94B.5010308@ghaering.de> References: <1131486799.092340.72120@g43g2000cwa.googlegroups.com> <4371E94B.5010308@ghaering.de> Message-ID: Thanks! On 11/9/05, Gerhard H?ring wrote: > infidel wrote: > > I have a stored procedure that has a single output parameter. Why do I > > have to pass it a string big enough to hold the value it is to receive? > > Why can't I pass an empty string or None? > > [...] > > Am I missing something obvious here? > > You have to use variable objects to the callproc() that will hold the > output values. This is an example using three VARCHAR output parameters. > > HTH, > > -- Gerhard > > > import cx_Oracle > > con = cx_Oracle.connect("user/password at my_conn") > cur = con.cursor() > > l_SchemaName = cur.var(cx_Oracle.STRING) > l_DbName = cur.var(cx_Oracle.STRING) > l_DomainName = cur.var(cx_Oracle.STRING) > > cur.callproc("TP_Lookup.GetSchema", (l_SchemaName, l_DbName, l_DomainName)) > > print "You are connected to", > print "the schema", l_SchemaName.getvalue(), > print "at %s.%s" % (l_DbName.getvalue(), l_DomainName.getvalue()) > > From ptmcg at austin.rr._bogus_.com Wed Nov 2 18:07:06 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 02 Nov 2005 23:07:06 GMT Subject: Getting a function name from string References: <436943e0$0$2083$edfadb0f@dtext02.news.tele.dk> Message-ID: "David Rasmussen" wrote in message news:436943e0$0$2083$edfadb0f at dtext02.news.tele.dk... > If I have a string that contains the name of a function, can I call it? > As in: > > def someFunction(): > print "Hello" > > s = "someFunction" > s() # I know this is wrong, but you get the idea... > > /David Lookup the function in the vars() dictionary. >>> def fn(x): ... return x*x ... >>> vars()['fn'] >>> vars()['fn'](100) 10000 -- Paul From pje at telecommunity.com Fri Nov 18 13:19:20 2005 From: pje at telecommunity.com (Phillip J. Eby) Date: 18 Nov 2005 10:19:20 -0800 Subject: Reinvent no more forever In-Reply-To: References: <1132279615.605498.258140@o13g2000cwo.googlegroups.com> Message-ID: <1132337960.249586.150140@o13g2000cwo.googlegroups.com> Dave Hansen wrote: > On 17 Nov 2005 18:06:55 -0800 in comp.lang.python, "Phillip J. Eby" > wrote: > > [...] > > > >Okay, so call yours "SuperEnum" or "PowerEnum" or "UltraEnum" or > >"BetterEnum", "Enum-O-Matic", "Symbolitron"... > > ITYM "EnumOMatic" or "Enum_O_Matic". "Enum-O-Matic" is a syntax > error. Or worse... Not in a PyPI project name, it isn't. Project names aren't limited to being Python identifiers. From pkilambi at gmail.com Mon Nov 21 16:59:12 2005 From: pkilambi at gmail.com (pkilambi at gmail.com) Date: 21 Nov 2005 13:59:12 -0800 Subject: ignore specific data In-Reply-To: References: <1132596504.619762.237610@g47g2000cwa.googlegroups.com> Message-ID: <1132610352.116663.118360@g44g2000cwa.googlegroups.com> I tried the solutions you provided..these are not as robust as i thought would be... may be i should put the problem more clearly... here it goes.... I have a bunch of documents and each document has a header which is common to all files. I read each file process it and compute the frequency of words in each file. now I want to ignore the header in each file. It is easy if the header is always at the top. but apparently its not. it could be at the bottom as well. So I want a function which goes through the file content and ignores the common header and return the remaining text to compute the frequencies..Also the header is not just one line..it includes licences and all other stuff and may be 50 to 60 lines as well..This "remove_header" has to be much more efficient as the files may be huge. As this is a very small part of the whole problem i dont want this to slow down my entire code... From pkilambi at gmail.com Thu Nov 10 13:28:52 2005 From: pkilambi at gmail.com (pkilambi at gmail.com) Date: 10 Nov 2005 10:28:52 -0800 Subject: help make it faster please In-Reply-To: <1131646601.299316.166570@g47g2000cwa.googlegroups.com> References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> <1131646601.299316.166570@g47g2000cwa.googlegroups.com> Message-ID: <1131647332.797580.138890@g49g2000cwa.googlegroups.com> Actually I create a seperate wordlist for each so called line.Here line I mean would be a paragraph in future...so I will have to recreate the wordlist for each loop From tinman31337 at gmail.com Wed Nov 23 07:42:11 2005 From: tinman31337 at gmail.com (Tin Gherdanarra) Date: Wed, 23 Nov 2005 04:42:11 -0800 Subject: Missing /usr/lib/python2.3/config In-Reply-To: References: <3uj0jiF118p56U1@individual.net> Message-ID: <3uj6d4F11caanU1@individual.net> Zoli wrote: > Hi. > > >>when trying to run the script ez_setup.py, I fail >>with >> >> unable to open /usr/lib/python2.3/config/Makefile >> >>This is true. There is no /usr/lib/python2.3/config >>directory. A check on groups.google revealed that >>this is a bug in my debian distro or something. Is >>this true? Is there a work-around? I can't reinstall >>debian because it is not my server. > > > Install the python-dev package: > > apt-get install python-dev > This did it, thanks. Tin From ashokagk at gmail.com Wed Nov 30 11:27:34 2005 From: ashokagk at gmail.com (ash) Date: 30 Nov 2005 08:27:34 -0800 Subject: UnicodeDecodeError Message-ID: <1133368054.944179.150920@f14g2000cwb.googlegroups.com> hi, one of the modules in my programs stopped wroking after i upgraded from python 2.3 to 2.4. I also changed my wxPython to unicode supported one during the process. what the module essentially does is search for a stirng pattern form a list of strings. this is the function: def srchqu(self): for i in range(1,len(qu)):#qu is the list of strings if qu[i][0].lower().find(self.query)==-1: pass else: #do some stuff here I get this error message on calling the function: Traceback (most recent call last): File "E:\mdi\search.py", line 86, in OnSrchButton self.srchqu() File "E:\mdi\search.py", line 97, in srchqu if qu[i][0].lower().find(self.query)==-1: UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 66: ordinal not in range(128) what is the problem and the solution? thanks in advance for any help. Ashoka From mwm at mired.org Wed Nov 16 15:20:14 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 16 Nov 2005 15:20:14 -0500 Subject: using openurl to log into Yahoo services References: Message-ID: <86y83ony4h.fsf@bhuda.mired.org> "joe_public34" writes: > Hello all, > > I'm trying to write a script to log into Yahoo! (mail, groups, etc), I don't have an answer to your problem but I *do* have a script that logs into yahoo. It's ugly, but it works. I'm refactoring it - if I ever get back to it. I've appended the crucial code, but haven't tried running this excerpt. If you have problems or questions, feel free to ask. = 5: handle_bogus(page, 'To many login attempts') # Never returns while 1: metas = page.fetch('meta', {'http-equiv': 'Refresh'}) if not metas: return page # Sigh. It's redirect page that didn't get handled by the library. page = meta_redirect(metas[0]['content']) return page def handle_login(soup, password): """Parse a page for login information, and hand back the result of logging in. Returns None if there is no login form.""" # Get the login page, scrape the form, and log in! forms = soup.fetch('form', {'name': 'login_form'}) if not forms: return None form = forms[0] postdata = [] for intag in form.fetchNext('input'): if intag['type'] == 'hidden': postdata.append((intag['name'], intag['value'])) elif intag['type'] == 'password': postdata.append((intag['name'], password)) elif intag['type'] == 'checkbox': postdata.append((intag['name'], 'n')) elif intag['type'] == 'text' and intag['name'] == 'login': postdata.append(('login', myYahooID)) elif intag['type'] == 'submit': if intag.has_key(['name']): postdata.append((intag['name'], intag['value'])) else: postdata.append(('submit', intag['value'])) else: print "Login form had unrecognized input tag:", str(intag) out = BeautifulSoup(urlopen(form['action'], urlencode(postdata)).read()) out.done() return out def meta_redirect(value): """Handle a http-equiv redirect, since the library isn't reliable.""" for spam in value.split(';'): stuff = spam.strip().split('=') if stuff and stuff[0] == 'url': out = BeautifulSoup(urlopen(stuff[1]).read()) out.done() return out -- Mike Meyer http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mwm at mired.org Thu Nov 24 16:00:29 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 16:00:29 -0500 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> Message-ID: <86oe49wyky.fsf@bhuda.mired.org> "Martin P. Hellwig" writes: > Those who can not afford the software are excluded for that end > product even though they may have worked on the source where 99,99% of > the restricted licensed software is based on. Well, they chose to make it available to others for reuse. But software "unavailable to those who can't afford it" is better than "no software at all" > However I make a poor defender for the GPL because, as you can read in > my previous posts, I don't really believe in it. The question is wether or not it believes in you :-) I believe in GPL'ed software - I use it regularly. On the other hand, I don't believe that it represents the best license to release software if the goal is to improve the lot of humanity. The restrictions are on "distribution", not on use, so it doesn't really keep people from using said software commercially. For instance, one or more of your examples may have been worth developing for internal use. They then decided there was a profit to be made in distributing it commercially, and proceeded to do so because they could. Without the profit motive, they may not have done the extra work involved in preparing the IP for distribution and doing the distribution. Personally, I release stuff under a BSD-like license, historically having included requirements that I be notified of bug fixes, and/or that I be given copies of commercial software that included my code. I eventually gave up on them as unenforceable. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From robert.dowell at gmail.com Wed Nov 2 13:55:13 2005 From: robert.dowell at gmail.com (robert.dowell at gmail.com) Date: 2 Nov 2005 10:55:13 -0800 Subject: where to download md5.py? In-Reply-To: References: Message-ID: <1130957713.669667.110260@g43g2000cwa.googlegroups.com> So when you type this into an interactive session: >>> import sha >>> help(sha) You get an error? From bearophileHUGS at lycos.com Mon Nov 21 01:45:39 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 20 Nov 2005 22:45:39 -0800 Subject: Underscores in Python numbers In-Reply-To: References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: <1132555539.902994.200300@f14g2000cwb.googlegroups.com> Peter Hansen>Or maybe one should instead interpret this as "numeric literals need more bells and whistles, and I don't care which of these two we add, but we have to do *something*!". :-) The purpose of my words was: when you think about adding a new syntax/functionality to a language, you have to think well if the same syntax can be used for something more important or more natural for it, so later you can avoid later problems and silly compromises. Bye, bearophile From mwm at mired.org Tue Nov 8 17:23:41 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 17:23:41 -0500 Subject: Web automation References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> <1131397945.832762.71070@g47g2000cwa.googlegroups.com> <86k6fk9k6v.fsf@bhuda.mired.org> <1131415131.676626.7730@g49g2000cwa.googlegroups.com> <86r79r96qh.fsf@bhuda.mired.org> <1131454589.455288.195540@g47g2000cwa.googlegroups.com> Message-ID: <86y83y7p8y.fsf@bhuda.mired.org> "Paul Boddie" writes: > Mike Meyer wrote: >> "Paul Boddie" writes: >> > The problem on non-Windows systems is the lack of a common (or >> > enforced) technology for exposing application object models >> OS X has AppleScript. VM/CMS has Rexx. The Amiga had ARexx when MS was >> still peddling DOS. Plan 9 has files. > I knew I should have written "UNIX systems" or "non-Windows but still > mainstream systems". ;-) Except OS X is Unix, non-Windows, and still mainstream. Maybe "non-GUI-intensive systems"? >> I don't think any of them are "enforced" - then again, I don't think anything enforces >> exporting objects from Windows applications, either. > No, but COM is the obvious choice for doing so on Windows. Combine that > with the component developer mindset and it's likely that some kind of > object model will be exposed by an application. I think I pointed out that the real thing all those system have is they come bundled with a way of exporting objects from applications. Generally, one that's better than embedding an interpreter in the application, too. There are patches for Linux that provide the system functionality needed for Plan 9's filesystem export facilities. If those ever go mainstream, I'll seriously consider switching to Linux. > Still, I wouldn't say that automation is necessarily "ass-backwards": > sometimes you want the additional baggage that the browser can give you > - witness the occasional comp.lang.python thread about working with > JavaScript-laden pages - and it's not necessarily automation involving > the activation of coincidental user interface components (find the > "Register Later" button in the "Register Now?" pop-up dialogue and > click on it") that's involved here either. You know, I recently automated a web task that invovled framed, JavaScript heavy pages. The pages had a link to a "no javascript" version, but that just returned a server error. Pretty hopeless, right? Turns out my script doesn't need any of that. I drilled down through the Frames to access the pages with real forms on them, and examineed the javascript source to figure out what it was doing - then did the appropriate POSTs by hand, and it all works quite nicely. > Yes, the very architecture of the Web should have made automation tasks > a lot more open and convenient, but sometimes there's a need for a > "complete" browser to get at the data. Well, there are two options to that. One is to find a modern browser with a good scripting interface. The other is to provide a scripting facility with the capabilities of a good browser - which mostly means JavaScript. CSS is a non-issue, and plugins aren't frequent enough to be a real problem. Especially since you may not be able to run the proprietary plugins on your system anyway, so even a full-blown browser won't help :-(. For JavaScript - there are standalone implementations available. If I ever run into a case where I actually have to run JavaScript to deal with a web automation task, I'll check them out. That no one has wrapped one for use in Python scripts tends to indicate that the JavaScript problem isn't as bad as it appears at first. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fairwinds at eastlink.ca Mon Nov 14 00:55:05 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Mon, 14 Nov 2005 01:55:05 -0400 Subject: Dictionary of tuples from query question Message-ID: <347B5862-54D3-11DA-AE36-000A27B3B070@eastlink.ca> Hi. I am interested in having results from a db query in the following form. {1: (value0, value1, value2,), 2: (value0, value1, value2,), 3: (value0, value1, value2,)} so I generate a dictionary of tuples (field values) dynamically so if I queried a table with five fields I would have five fields in my tuple and if I had 20 fields in my query, I would have 20 fields in my tuple, etc. Note that the dict starts at 1 and not zero. From the code below, the structure I have currently is: {1: {0:value0, 1:value1, 2:value2}, 2: {0:value0, 1:value1, 2:value2}, 3: {0:value0, 1:value1, 2:value2}} My code so far. I guess my problem is how to generate a tuple dynamically when it is immutable? Many thanks David cursor = db.cursor() cursor.execute(""" SELECT * FROM countries; """) rows = cursor.fetchall() vdict = {} for row in range(len(rows)): col_dict = {} for col in range(len(rows[row])): value = rows[row][col] col_dict[col] = value vdict[row + 1] = col_dict print vdict -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 1136 bytes Desc: not available URL: From mwm at mired.org Fri Nov 4 05:15:27 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 04 Nov 2005 05:15:27 -0500 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> Message-ID: <86irv8hg74.fsf@bhuda.mired.org> Antoon Pardon writes: > Op 2005-11-03, Mike Meyer schreef : >> Antoon Pardon writes: >>>> What would you expect to get if you wrote b.a = b.a + 2? >>> I would expect a result consistent with the fact that both times >>> b.a would refer to the same object. >> Except they *don't*. This happens in any language that resolves >> references at run time. > Python doesn't resolve references at run time. If it did the following > should work. You left out a key word: "all". > a = 1 > def f(): > a = a + 1 > > f() If Python didn't resolve references at run time, the following wouldn't work: >>> def f(): ... global a ... a = a + 1 ... >>> a = 1 >>> f() >>> > But letting that aside. There is still a difference between resolving > reference at run time and having the same reference resolved twice > with each resolution a different result. The second is a direct result of the first. The environment can change between the references, so they resolve to different results. >> Changing that would be changing a fundamental >> - and *important* - feature of Python. Arbitrary restrictions to >> prevent a single case of this from doing something people who aren't >> used to suvh behavior are kludges, and would constitute a wart on the >> language, pure and simple. > Python already has its warts. If you want to argue that fixing this > would make a bigger wart then the wart it is now. Fine I will accept > that. I've already argued that the kludges suggested to "solve" this problem create worse problems than this. This is a simple case of something being unexpected to those used to less dynamic languages. The other solutions break useful functionality, and require adding special cases to the language - which aren't special enough to break the rules. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From alex.greif at gmail.com Mon Nov 14 07:56:59 2005 From: alex.greif at gmail.com (alex.greif at gmail.com) Date: 14 Nov 2005 04:56:59 -0800 Subject: want some python ide In-Reply-To: References: <1131890689.729009.63430@g14g2000cwa.googlegroups.com> Message-ID: <1131973019.144981.183790@o13g2000cwo.googlegroups.com> Hi, look for SciTE http://www.scintilla.org/SciTE.html it is small, fast and lightweight Alex Greif ________________________________________ http://www.fotobuch-xxl.de/ D H wrote: > prolibertine at gmail.com wrote: > > i want some python ide use pygtk > > eric3 is good for me ,but i like gtk,so i want some pygtk ide look like > > eric3 > > wing is a good python ide,but i can not download it > > some other python ide(must use pygtk) > > thx > > > > You can just use a text editor like jedit with gazpacho or glade > http://gazpacho.sicem.biz/ > They are not as easy to use at QT Designer though for building interfaces. From against at spam.pl Thu Nov 3 02:45:57 2005 From: against at spam.pl (=?UTF-8?B?R3J6ZWdvcnogxZpsdXNhcmVr?=) Date: Thu, 03 Nov 2005 08:45:57 +0100 Subject: Python and Lotus Notes In-Reply-To: <1130941469.353649.195200@g14g2000cwa.googlegroups.com> References: <1130941469.353649.195200@g14g2000cwa.googlegroups.com> Message-ID: thank you Graham Now I know how to get it thru And i have last question is it possible send mail from Lotus via Python/COM? Once Again Thanks From twic at urchin.earth.li Tue Nov 22 20:06:15 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 23 Nov 2005 01:06:15 +0000 Subject: user-defined operators: a very modest proposal In-Reply-To: References: Message-ID: On Tue, 22 Nov 2005, Steve R. Hastings wrote: > User-defined operators could be defined like the following: ]+[ Eeek. That really doesn't look right. Could you remind me of the reason we can't say [+]? It seems to me that an operator can never be a legal filling for an array literal or a subscript, so there wouldn't be ambiguity. We could even just say that [?] is an array version of whatever operator ? is, and let python do the heavy lifting (excuse the pun) of looping it over the operands. [[?]] would obviously be a doubly-lifted version. Although that would mean [*] is a componentwise product, rather than an outer product, which wouldn't really help you very much! Maybe we could define {?} as the generalised outer/tensor version of the ? operator ... > For improved readability, Python could even enforce a requirement that > there should be white space on either side of a user-defined operator. I > don't really think that's necessary. Indeed, it would be extremely wrong - normal operators don't require that, and special cases aren't special enough to break the rules. Reminds me of my idea for using spaces instead of parentheses for grouping in expressions, so a+b * c+d evaluates as (a+b)*(c+d) - one of my worst ideas ever, i'd say, up there with gin milkshakes. > Also, there should be a way to declare what kind of precedence the > user-defined operators use. Can't be done - different uses of the same operator symbol on different classes could have different precedence, right? So python would need to know what the class of the receiver is before it can work out the evaluation order of the expression; python does evaluation order at compile time, but only knows classes at execute time, so no dice. Also, i'm pretty sure you could cook up a situation where you could exploit differing precedences of different definitions of one symbol to generate ambiguous cases, but i'm not in a twisted enough mood to actually work out a concrete example! And now for something completely different. For Py4k, i think we should allow any sequence of characters that doesn't mean something else to be an operator, supported with one special method to rule them all, __oper__(self, ator, and), so: a + b Becomes: a.__oper__("+", b) And: a --{--@ b Becomes: a.__oper__("--{--@", b) # Euler's 'single rose' operator Etc. We need to be able to distinguish a + -b from a +- b, but this is where i can bring my grouping-by-whitespace idea into play, requiring whitespace separating operands and operators - after all, if it's good enough for grouping statements (as it evidently is at present), it's good enough for expressions. The character ']' would be treated as whitespace, so a[b] would be handled as a.__oper__("[", b). Naturally, the . operator would also be handled through __oper__. Jeff Epler's proposal to use unicode operators would synergise most excellently with this, allowing python to finally reach, and even surpass, the level of expressiveness found in languages such as perl, APL and INTERCAL. tom -- I DO IT WRONG!!! From timothy at open-networks.net Wed Nov 30 04:04:58 2005 From: timothy at open-networks.net (Timothy Smith) Date: Wed, 30 Nov 2005 19:04:58 +1000 Subject: an intriguing wifi http server mystery...please help In-Reply-To: <438D3186.2070800@ulmcnett.com> References: <1133324893.968023.79050@z14g2000cwz.googlegroups.com> <438D3186.2070800@ulmcnett.com> Message-ID: <438D6B3A.3090208@open-networks.net> Paul McNett wrote: >jojoba at gmail.com wrote: > > >>1) >>Laptop wired, client >>Desktop wired, server >>GREAT! >>webpage served in 2 seconds >> >>2) >>Laptop wired, server >>Deskop wired, client >>GREAT! >>webpage served in 2 seconds >> >>3) >>Laptop wireless, client >>Desktop wireless, server >>GREAT! >>webpage served in 2 seconds >> >>4) >>Laptop wireless, server >>Desktop wireless, client >>CRAP! >>webpage served in 90 seconds >> >> >>What the heck is happening? >> >> > >Please post your routing tables and, if you are referencing your server machine >by name, your name server addresses (/etc/resolv.conf on Linux). > > > > i'm inclined to agree, your client and server might be taking totally different routes to get to each other and hence the 90ms From lycka at carmen.se Wed Nov 2 13:50:31 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 02 Nov 2005 19:50:31 +0100 Subject: Forcing the position of scroll bars on a wxTextCtrl In-Reply-To: <1130950032.605129.194930@g14g2000cwa.googlegroups.com> References: <1130950032.605129.194930@g14g2000cwa.googlegroups.com> Message-ID: Someone who's probably not really called Clans Of Intrigue wrote: > Hello, this is my first post here so apologies if it's in the wrong > place, inappropriate or embarrassingly stupid - please let me know :) No, that's ok. The wxpython mailing list might give better answers though. > My problem seems quite simple - I've redirected stdout to a wxTextCtrl, > so that any trace messages appear in a log window at the bottom of my > app. The problem is that whenever I update the text, the scrollbar > resets to the top - i.e. to the earliest log message. What I really > want it to do is reset to the bottom, so that the most recent log > messages are on screen. It's a few years since I coded wx, but I guess you should do something along the lines of: self._ctrl.ShowPosition(self._ctrl.GetLastPosition()) Don't mess manually with the scroll bars (I think). (I know I've gone through this once...) From joeyjwc at gmail.com Sat Nov 19 11:27:19 2005 From: joeyjwc at gmail.com (Joey C.) Date: 19 Nov 2005 08:27:19 -0800 Subject: Using win32ui.CreateFileDialog() to get the name of a file. Message-ID: <1132417639.273376.27820@g47g2000cwa.googlegroups.com> Hello. I'm writing a program that creates a series of batch operations to convert movies to be used on iPodLinux. The programs that do the encoding and conversions are seperate from mine and all mine does is use os.system() to call the program. However, it needs to get an input file and an output file. Originally I was using just raw input, but I got adventuresome and decided to try win32ui.CreateFileDialog(). But this will only open or save a file and its output will be either 1 or a failure. How might I go about using it to get the _file name_ of a file. For example. Box appears asking user to find a file they want. They double click on the file. Let's call it C:\Video.avi Then another dialog box appears asking them where to save it. They save it at C:\iPodVideo.avi. Now the Python program extracts the name of these files and then uses os.system() to run: mencoder.exe -[parameters] C:\Video.avi -o C:\iPodVideo.avi Note that I'm not actually inputting the contents of the file, I'm just passing the file name along. How might I do this? Thanks. From aisaac0 at verizon.net Fri Nov 25 11:39:42 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 25 Nov 2005 16:39:42 GMT Subject: FTP over TLS References: Message-ID: "Carl Waldbieser" wrote in message news:dm2sc0$4i2$1 at domitilla.aioe.org... > Does anyone know of any good examples for writing client side code to upload > files over a secure FTP connection? http://trevp.net/tlslite/ Alan Isaac From gene.tani at gmail.com Fri Nov 18 14:39:19 2005 From: gene.tani at gmail.com (gene tani) Date: 18 Nov 2005 11:39:19 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: <86hda9kbso.fsf@bhuda.mired.org> References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <86hda9kbso.fsf@bhuda.mired.org> Message-ID: <1132342759.030683.136840@z14g2000cwz.googlegroups.com> Mike Meyer wrote: > "Daniel Crespo" writes: > > > Hi! > > > > I would like to know how can I do the PHP ternary operator/statement > > (... ? ... : ...) in Python... > > > > I want to something like: > > > > a = {'Huge': (quantity>90) ? True : False} > > > > Any suggestions? > > Lots of ways, depending on your exact needs. What's best for what you > suggest is "a = {Huge : (False, True)[quantity > 90]}". Googling the http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator From steve at REMOVEMEcyber.com.au Tue Nov 1 20:37:56 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 02 Nov 2005 12:37:56 +1100 Subject: Scanning a file References: <1130497567.764104.125110@g44g2000cwa.googlegroups.com> <7xek65nal0.fsf@ruckus.brouhaha.com> <1130505731.850947.68690@o13g2000cwo.googlegroups.com> <4363fdd4$0$2107$edfadb0f@dtext02.news.tele.dk> <4367c368$0$2100$edfadb0f@dtext02.news.tele.dk> Message-ID: <43681874.7040702@REMOVEMEcyber.com.au> David Rasmussen wrote: > Lasse V?gs?ther Karlsen wrote: > >> David Rasmussen wrote: >> >> >>> If you must know, the above one-liner actually counts the number of >>> frames in an MPEG2 file. I want to know this number for a number of >>> files for various reasons. I don't want it to take forever. >> >> >> Don't you risk getting more "frames" than the file actually have? What >> if the encoded data happens to have the magic byte values for >> something else? >> > > I am not too sure about the details, but I've been told from a reliable > source that 0x00000100 only occurs as a "begin frame" marker, and not > anywhere else. So far, it has been true on the files I have tried it on. Not too reliable then. 0x00000100 is one of a number of unique start codes in the MPEG2 standard. It is guaranteed to be unique in the video stream, however when searching for codes within the video stream, make sure you're in the video stream! See, for example, http://forum.doom9.org/archive/index.php/t-29262.html "Actually, one easy way (DVD specific) is to look for 00 00 01 e0 at byte offset 00e of the pack. Then look at byte 016, it contains the size of the extension. Resume your scan at 017 + contents of 016." Right. Glad that's the easy way. I really suspect that you need a proper MPEG2 parser, and not just blindly counting bytes -- at least if you want reliable, accurate counts and not just "number of frames, plus some file-specific random number". And heaven help you if you want to support MPEGs that are slightly broken... (It has to be said, depending on your ultimate needs, "close enough" may very well be, um, close enough.) Good luck! -- Steven. From danb_83 at yahoo.com Wed Nov 9 19:20:08 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Nov 2005 16:20:08 -0800 Subject: Floating numbers and str References: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> <11n4lkg3hlboq08@corp.supernews.com> Message-ID: <1131582008.936061.299280@f14g2000cwb.googlegroups.com> Grant Edwards wrote: > On 2005-11-09, Tuvas wrote: > > > I would like to limit a floating variable to 4 signifigant digits, when > > running thorugh a str command. > > Sorry, that's not possible. Technically, it is. >>> class Float4(float): ... def __str__(self): ... return '%.4g' % self ... >>> x = Float4(1.23456789) >>> str(x) '1.235' But, of course, I'd recommend just using '%.4g'%x directly. From mde at micah.elliott.name Wed Nov 30 12:39:46 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Wed, 30 Nov 2005 09:39:46 -0800 Subject: import Excel csv - files In-Reply-To: <000001c5f584$f90e7690$6106a8c0@samsungx30> References: <000001c5f584$f90e7690$6106a8c0@samsungx30> Message-ID: <20051130173946.GB15633@kitchen.client.attbi.com> On Nov 30, J?rgen Kemeter wrote: > My actual Problem: > The Excel workbook contains several spreadsheets. These are > linked through Hyperlinks, and contain several cell comments. How > can I export these comments and Hyperlinks using Python? Are you just wanting read a .xls file with Python? pyExcelerator can do that job. Documentation is non-existent AFAICT, but the tools directory has good examples. I don't know how comments/hyperlinks are treated but you can try and find out. -- _ _ ___ |V|icah |- lliott <>< mde at micah.elliott.name " " """ From fredrik at pythonware.com Mon Nov 14 11:12:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Nov 2005 17:12:18 +0100 Subject: Dictionary of tuples from query question References: Message-ID: David Pratt wrote: > Hi Fredrik. Many thanks for your reply and for the tuple tip. The > cursor.fetchall returns a list of lists in this instance with each list > in the main list containing the field values. With the tip, I > simplified my code to: > > vlist_dict = {} > record_count = 0 > for record in cursor.fetchall(): > record_count += 1 > vlist_dict[record_count] = tuple(record) > print vlist_dict > > That's much better! I meant to write d = {} for index, record in enumerate(cursor.fetchall()): d[index+1] = tuple(record) which can be shorted to d = dict((k+1, tuple(v)) for k, v in enumerate(x)) in recent versions of Python. From getkaizer at gmail.com Mon Nov 28 00:25:39 2005 From: getkaizer at gmail.com (getkaizer at gmail.com) Date: 27 Nov 2005 21:25:39 -0800 Subject: Newbie question: Tab key giving different output Message-ID: <1133155539.865554.216610@g14g2000cwa.googlegroups.com> Hello, I'm a newbie to python. I run python under Manddrake Linux 10.2 from a terminal. While in the interactive mode, i need to use the tab key to indent my code. However, i get a message "List all 174 possibilities? (Y/N)" instead of an indent. So i use spaces. How do i tell python to give me indents? Thanks in advance! Have a great day, Kaizer. From __peter__ at web.de Fri Nov 4 06:47:49 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Nov 2005 12:47:49 +0100 Subject: help converting some perl code to python References: <1131094909.984993.32330@z14g2000cwz.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > i need help with converting a piece of perl code to python > the problem is the '..' operator in perl. Is there any equivalent in > python? Here is a class that emulates the .. operator: import sys import re start, files, end = map(re.escape, ["[start]", "[files]", "[end]"]) class Section(object): def __init__(self, start, end): self.start = re.compile(start).match self.end = re.compile(end).match self.inside = False def __contains__(self, line): result = self.inside if result: if self.end(line): self.inside = False else: if self.start(line): result = self.inside = True return result first = Section(start, files) second = Section(files, end) for line in sys.stdin: line = line[:-1] if line in first: # your code if line in second: # your code However, the simpler #untested import sys start, files, end = "[start]", "[files]", "[end]" keys = set([start, files, end]) key = None for line in sys.stdin: line = line[:-1] if line in keys: key = line elif key == start: # your code elif key == files: # your code might work even better because 'your code' doesn't get to see the sections' begin/end markers. Peter From steve at holdenweb.com Fri Nov 4 20:40:51 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 05 Nov 2005 01:40:51 +0000 Subject: Calling Class' Child Methods In-Reply-To: <436bf7f2$0$6007$4fafbaef@reader4.news.tin.it> References: <436bf7f2$0$6007$4fafbaef@reader4.news.tin.it> Message-ID: Andrea Gavana wrote: > Hello NG, > > this may seem a stupid (or even impossible) question, but my knowlegde > of Python is quite limited. I have basically a simple graphical user > interface that contains a Panel, another panel (child of the main panel) and > a custom widget (child of the main panel). Basically is something like (only > some small code, is in wxPython but the question is more Python-related): > > class MainClass(wx.Panel): > > def __init__(self, *args, **kwds): > > wx.Panel.__init__(self, *args, **kwds) > > self.childpanel = wx.Panel(self, -1) > self.customwidget = Custom(self, -1) > > layoutsizer = wx.BoxSizer(wx.VERTICAL) > layoutsizer.Add(self.childpanel, 1) > layoutsizer.Add(self.customwidget) > layoutsizer.Layout() > > > The class "Custom" has a lot of methods (functions), but the user won't call > directly this class, he/she will call the MainClass class to construct the > GUI app. However, all the methods that the user can call refer to the > "Custom" class, not the MainClass class. That is, the methods that the user > call should propagate to the "Custom" class. However, I know I can do: > > # Inside MainClass > def SomeMethod(self, param): > self.customwidget.SomeMethod(param) > It seems that what you need is a generic delegation. This pattern (in Python, anyway) makes use of the fact that if the interpreter can't find a method or other attribute for an object it will call the object's __getattr__() method. So, what yo need to do is define MainClass.__getattr__() so it returns the appropariate attribute from self.customwidget. You'll find in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 a discussion and examples dating from before new-style classes ("types") were introduced into Python, but Alex Martelli's exposition is hard top beat. > But the "Custom" class has *a lot* of methods, so I will end up in rewriting > all the "SomeMethods" in the MainClass just to pass the parameters/settings > to self.customwidget. Moreover, I know I can do (in the __init__ method of > MainClass): > > def __init__(self, *args, **kwds): > > wx.Panel.__init__(self, *args, **kwds) > Custom.__init__(self, parent, -1) > > In order to make MainClass knowing about the Custom methods. But the I will > not be able (I suppose) to add self.customwidget to a layoutsizer. How can I > write: > > layoutsizer = wx.BoxSizer(wx.VERTICAL) > layoutsizer.Add(self.childpanel, 1) > layoutsizer.Add(self) # <=== That's impossible > layoutsizer.Layout() > > ? > > So (and I am very sorry for the long and maybe complex to understand post, > english is not my mother tongue and I am still trying to figure out how to > solve this problem), how can I let MainClass knowing about the Custom > methods without rewriting all the Custom functions inside MainClass and then > pass the parameters to Custom? Is there a way to "propagate" the methods to > the child class (Custom)? > > Thanks for every suggestion, and sorry for the long post. > > Andrea. 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 erdewit at d-e-l-e-t-e.zonnet.nl Fri Nov 4 09:35:35 2005 From: erdewit at d-e-l-e-t-e.zonnet.nl (Ewald R. de Wit) Date: Fri, 04 Nov 2005 08:35:35 -0600 Subject: __slots__ and class attributes References: Message-ID: Steven Bethard wrote: > But why do you want a class level attribute with the same name as an > instance level attribute? I would have written your class as: > > class A(object): > __slots__ = ['value'] > def __init__(self, value=1): > self.value = value > > where the default value you put in the class is simply expressed as a > default value to the __init__ parameter. Thanks for your explanation. The reason why I was doing it was to have class-level defaults, so that one can easily adjust how new instances will be made. I'm doing it now with capitilized class attribute names to avoid the name clash. -- -- Ewald From Tomasik at 2kop.mil.pl Fri Nov 11 08:54:24 2005 From: Tomasik at 2kop.mil.pl (Robert) Date: Fri, 11 Nov 2005 14:54:24 +0100 Subject: something wrong in wx Message-ID: something wrong in wx I wrote program training na Artificial Neural Network. It work well in console mode, but when I try to add GUI there is an error: FANN Error 10: Error reading info from train data file "zapis.txt", line: 2 There is a code: ##### this work ############ #!/usr/bin/python import fann connection_rate = 1 learning_rate = 0.7 num_layers = 3 num_input = 319 num_neurons_hidden = 50 num_output = 5 ann = fann.fann_create(connection_rate, learning_rate, num_layers,num_input, num_neurons_hidden, num_output) desired_error = 0.00001 max_iterations = 500000 iterations_between_reports = 1000 fann.fann_train_on_file(ann, "zapis.txt", max_iterations, iterations_between_reports, desired_error) print fann.fann_get_MSE(ann) fann.fann_save(ann, "po_nauce.net") fann.fann_destroy(ann) ######### with GUI (not work) ######### #!/usr/bin/python import wx import fann class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Trenowanie sieci", pos=(50, 50)) panel = wx.Panel(self) # First create the controls topLbl = wx.StaticText(panel, -1, "Trenowanie sieci", size=wx.Size(400, 21), style=wx.ALIGN_CENTRE) topLbl.Center(wx.HORIZONTAL) topLbl.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) polaczenia_Lbl = wx.StaticText(panel, -1, u'Stopie\u0144 po\u0142\u0105cze\u0144 [%]:') self.polaczenia = wx.SpinCtrl(panel, -1, "") self.polaczenia.SetRange(0,100) self.polaczenia.SetValue(100) ilosc_warstw_Lbl = wx.StaticText(panel, -1, u'Ilo\u015b\u0107 warstw:') self.ilosc_warstw = wx.SpinCtrl(panel, -1, "") self.ilosc_warstw.SetRange(0,5) self.ilosc_warstw.SetValue(3) cstLbl1 = wx.StaticText(panel, -1, '\n' u'Poszczeg\xf3lne warstwy sieci: ') cstLbl = wx.StaticText(panel, -1, '\n' u'wej\u015biowa ukryta wyj\u015biowa') self.ilosc_wejsc = wx.SpinCtrl(panel, -1, "") self.ilosc_wejsc.SetRange(0,2000) self.ilosc_wejsc.SetValue(319) self.ukryte = wx.SpinCtrl(panel, -1, "") self.ukryte.SetRange(0,500) self.ukryte.SetValue(50) self.ilosc_wyjsc = wx.SpinCtrl(panel, -1, "") self.ilosc_wyjsc.SetRange(0,100) self.ilosc_wyjsc.SetValue(5) uczenie_Lbl = wx.StaticText(panel, -1, u'Cz\u0119sto\u015b\u0107 uczenia [%]:') self.uczenie = wx.SpinCtrl(panel, -1, "") self.uczenie.SetRange(0,100) self.uczenie.SetValue(70) oczekiwany_blad_Lbl = wx.StaticText(panel, -1, u'Oczekiwany b\u0142\u0105d: [1/x]') self.oczekiwany_blad = wx.SpinCtrl(panel, -1, "") self.oczekiwany_blad.SetRange(0,100000000) self.oczekiwany_blad.SetValue(100000) powtorzen_Lbl = wx.StaticText(panel, -1, u'Maxymalna liczba powt\xf3rze\u0144:') self.powtorzen = wx.SpinCtrl(panel, -1, "") self.powtorzen.SetRange(0,100000) self.powtorzen.SetValue(50000) raporty_Lbl = wx.StaticText(panel, -1, u'raport co:') self.raporty = wx.SpinCtrl(panel, -1, "") self.raporty.SetRange(0,10000) self.raporty.SetValue(1000) trenujBtn = wx.Button(panel, -1, "Trenuj Siec") self.Bind(wx.EVT_BUTTON, self.on_trenujBtn, trenujBtn) cancelBtn = wx.Button(panel, -1, "Cancel") # Now do the layout. # mainSizer is the top-level one that manages everything mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(topLbl, 0, wx.ALL, 5) ainSizer.Add(wx.StaticLine(panel), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5) # addrSizer is a grid that holds all of the address info addrSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) addrSizer.AddGrowableCol(1) addrSizer.Add(polaczenia_Lbl, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) addrSizer.Add(self.polaczenia, 0, wx.EXPAND) addrSizer.Add(ilosc_warstw_Lbl, 0, wx.ALIGN_RIGHT| wx.ALIGN_CENTER_VERTICAL) addrSizer.Add(self.ilosc_warstw, 0, wx.EXPAND) #addrSizer.Add((10,10)) # some empty space #addrSizer.Add(addr2, 0, wx.EXPAND) addrSizer.Add(cstLbl1, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) addrSizer.Add(cstLbl, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) addrSizer.Add((10,10)) # some empty space # the city, state, zip fields are in a sub-sizer cstSizer = wx.BoxSizer(wx.HORIZONTAL) cstSizer.Add(self.ilosc_wejsc, 1) cstSizer.Add(self.ukryte, 0, wx.LEFT|wx.RIGHT, 5) cstSizer.Add(self.ilosc_wyjsc) addrSizer.Add(cstSizer, 0, wx.EXPAND) addrSizer.Add(uczenie_Lbl, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) addrSizer.Add(self.uczenie, 0, wx.EXPAND) addrSizer.Add(oczekiwany_blad_Lbl, 0, wx.ALIGN_RIGHT| wx.ALIGN_CENTER_VERTICAL) addrSizer.Add(self.oczekiwany_blad, 0, wx.EXPAND) addrSizer.Add(powtorzen_Lbl, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) addrSizer.Add(self.powtorzen, 0, wx.EXPAND) addrSizer.Add(raporty_Lbl, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) addrSizer.Add(self.raporty, 0, wx.EXPAND) # now add the addrSizer to the mainSizer mainSizer.Add(addrSizer, 0, wx.EXPAND|wx.ALL, 10) # The buttons sizer will put them in a row with resizeable # gaps between and on either side of the buttons btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add((20,20), 1) btnSizer.Add(trenujBtn) btnSizer.Add((20,20), 1) btnSizer.Add(cancelBtn) btnSizer.Add((20,20), 1) mainSizer.Add(btnSizer, 0, wx.EXPAND|wx.BOTTOM, 10) # Finally, tell the panel to use the sizer for layout panel.SetSizer(mainSizer) # Fit the frame to the needs of the sizer. The frame will # automatically resize the panel as needed. Also prevent the # frame from getting smaller than this size. mainSizer.Fit(self) self.SetSizeHints(*self.GetSize()) def on_trenujBtn(self, event): connection_rate = float(self.polaczenia.GetValue()*0.01) learning_rate = float(self.uczenie.GetValue()*0.01) num_layers = int(self.ilosc_warstw.GetValue()) num_input = int(self.ilosc_wejsc.GetValue()) num_neurons_hidden = int(self.ukryte.GetValue()) num_output = int(self.ilosc_wyjsc.GetValue()) ann = fann.fann_create(connection_rate, learning_rate, num_layers, num_input, num_neurons_hidden, num_output) max_iterations = int(self.powtorzen.GetValue()) iterations_between_reports = int(self.raporty.GetValue()) desired_error = 0.00001 #float(1/(self.oczekiwany_blad.GetValue())) print desired_error fann.fann_train_on_file(ann, "zapis.txt", max_iterations, iterations_between_reports, desired_error) fann.fann_save(ann, "po_nauce.net") fann.fann_destroy(ann) app = wx.PySimpleApp() frame = TestFrame() frame.Show() app.MainLoop() ####################################################### Thanks for any help. Robert From twic at urchin.earth.li Sat Nov 12 19:21:56 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sun, 13 Nov 2005 00:21:56 +0000 Subject: Iterator addition In-Reply-To: <7xslu5cdhz.fsf@ruckus.brouhaha.com> References: <7x4q6lm87q.fsf_-_@ruckus.brouhaha.com> <1h5s1dp.i6hnk31bmv4xN%aleax@mail.comcast.net> <7xslu5cdhz.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 9 Nov 2005, it was written: > aleax at mail.comcast.net (Alex Martelli) writes: > >>> Is there a good reason to not define iter1+iter2 to be the same as >> >> If you mean for *ALL* built-in types, such as generators, lists, files, >> dicts, etc, etc -- I'm not so sure. > > Hmm, there might also be __add__ operations on the objects, that would > have to take precedence over iterator addition. Iterator addition > itself would have to be a special kludge like figuring out "<" from > __cmp__, etc. > > Yeah, I guess the idea doesn't work out that well. Oh well. How about if we had some sort of special sort of iterator which did the right thing when things were added to it? like an iterable version of The Blob: class blob(object): def __init__(self, it=None): self.its = [] if (it != None): self.its.append(iter(it)) def __iter__(self): return self def next(self): try: return self.its[0].next() except StopIteration: # current iterator has run out! self.its.pop(0) return self.next() except IndexError: # no more iterators raise StopIteration def __add__(self, it): self.its.append(iter(it)) return self def __radd__(self, it): self.its.insert(0, iter(it)) Then we could do: all_lines = blob(file1) + file2 + file3 candidate_primes = blob((2,)) + (1+2*i for i in itertools.count(1)) Which, although not quite as neat, isn't entirely awful. Another option would be a new operator for chaining - let's use $, since that looks like the chain on the fouled anchor symbol used by navies etc: http://www.diggerhistory.info/images/badges-asstd/female-rels-navy.jpg Saying "a $ b" would be equivalent to "chain(a, b)", where chain (which could even be a builtin if you like) is defined: def chain(a, b): if (hasattr(a, "__chain__")): return a.__chain__(b) elif (hasattr(b, "__rchain__")): # optional return b.__rchain__(a) else: return itertools.chain(a, b) # or equivalent Whatever it is that itertools.chain or whatever returns would be modified to have a __chain__ method which behaved like blob.__add__ above. This then gets you: all_lines = file1 $ file2 $ file3 candidate_primes = (2,) $ (1+2*i for i in itertools.count(1)) And we're halfway to looking like perl already! Perhaps a more pythonic thing would be to define a "then" operator: all_lines = file1 then file2 then file3 candidate_primes = (2,) then (1+2*i for i in itertools.count(1)) That looks quite nice. The special method would be __then__, of course. tom -- if you can't beat them, build them From jgreenwald78 at yahoo.com Thu Nov 3 18:42:54 2005 From: jgreenwald78 at yahoo.com (Jeremy Greenwald) Date: Thu, 3 Nov 2005 15:42:54 -0800 (PST) Subject: Learning multiple languages (question for general discussion) Message-ID: <20051103234254.5299.qmail@web34209.mail.mud.yahoo.com> I would say that learning a few languages is necessary to realizing what type of things different languages excel at. For instance I didn't understand why java would never allocate objects on the stack until I read about using object pointers in C++ to lower compilation dependecies. This helped me to understand the trade-offs involved. I also used to like perl until I got to know Pythons compactness (perl sucks by the way). On a broader stroke, learning a language is NOT about learning the syntax (although that is a requirement) it is about learning that languages style, coding practices and what API's are useful in your domain. That should be your guide as to when you have "learned" a language, when you can answer more questions than you have about a language's style, coding practices, and API. -- Jeremy Greenwald __________________________________ Yahoo! FareChase: Search multiple travel sites in one click. http://farechase.yahoo.com From robert.kern at gmail.com Tue Nov 29 16:39:51 2005 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 29 Nov 2005 13:39:51 -0800 Subject: Which License Should I Use? In-Reply-To: References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: Aahz wrote: > In article , > Robert Kern wrote: > >>Don't listen to schmucks on USENET when making legal decisions. Hire >>yourself a competent schmuck. > > Mind if I .sig this? How would you like to be attributed? Please do. "USENET schmuck" is a sufficient attribution if you like, though "Robert Kern" will work, too. -- 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 aleax at mail.comcast.net Wed Nov 23 23:49:52 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 20:49:52 -0800 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> Message-ID: <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> Ben Finney wrote: ... > > Of course, these restrictions can be easily worked around by a > > sufficiently determined attacker... but if you have to think of the > > user of your code as an attacker, you've got worse problems than > > this trifling one. > > I've probably stumbled across something that people often want to do > for ill-considered reasons; I don't really understand the reaction I'm > getting. > > Why is "I want to make objects immutable" seen as "I don't trust my > users"? Are Python's existing immutable types also seen the same way? > If not, why the distinction? A type implemented in C offers different possibilities than one implemented in Python -- no deep conceptual reason, just practical ones. A substantial fraction of the time, people asking "how do I stop the users of my code from doing X" proceed by screaming "but they could still do X if they hopped on their left foot in a moonless midnight while sprinkling bat's blood!" as a response to any suggestion. So, when you ask "how do I stop the users of my code from doing X" without qualification, you're quite likely to get such disclaimers. If you don't want them, learn to ask about stopping your users from ACCIDENTALLY doing X, and no reasonable respondant will fail to notice the qualification. > For context, I'm intending for the immutability of class instances to > be a properly documented part of the class protocol. Does that sound > more reasonable? There was nothing unreasonable in your original request, either; and I don't think that making it explicit that you intended to document the restriction would have changed my answer (although an explicit acknowlegment that you're looking for restrictions against accidental misuse rather than against determined attackers surely would). Alex From skip at pobox.com Thu Nov 17 10:15:22 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 17 Nov 2005 09:15:22 -0600 Subject: Current execution frame of another thread? Message-ID: <17276.40586.548629.418195@montanaro.dyndns.org> I would like to try a sampling approach to profiling. My thought is to have a profiling thread that samples the execution frame of all the other started threads. I don't see any path from the threads returned by threading.enumerate() to their current frames. Am I missing something? Thx, Skip From mwm at mired.org Fri Nov 11 10:40:10 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 11 Nov 2005 10:40:10 -0500 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86ek5o54kl.fsf@bhuda.mired.org> <1131719177.838744.271690@z14g2000cwz.googlegroups.com> Message-ID: <86fyq342hx.fsf@bhuda.mired.org> "Ben Sizer" writes: >> A recent, heavily >> publicized case where Sony added copy protection to a product cost >> them sales, and from what I've heard, even legal fees. > I think that's a poor example - the cost hasn't come from the mere act > of adding protection, but the method in which that protection operates. That was sort of the point - that the effect on the bottom line of adding copy protection is usually worse than just the cost of the software, and can be much worse. This is a particularly egregious example, but that just makes it an egregious example, not a poor one. > I don't think anybody here - certainly not me - is talking about > infecting a user's system to protect our property, or taking any other > intrusive steps. I'd just like to make it non-trivial to make or use > additional copies. I've returned software that wouldn't run from a backup copy. Would I return your software? If yes, have you factored the loss of sales to people like me into your profit calculations? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From noahlt at gmail.com Thu Nov 3 00:05:55 2005 From: noahlt at gmail.com (noahlt at gmail.com) Date: 2 Nov 2005 21:05:55 -0800 Subject: XML DOM: XML/XHTML inside a text node Message-ID: <1130994355.266863.264890@g14g2000cwa.googlegroups.com> In my program, I get input from the user and insert it into an XHTML document. Sometimes, this input will contain XHTML, but since I'm inserting it as a text node, xml.dom.minidom escapes the angle brackets ('<' becomes '<', '>' becomes '>'). I want to be able to override this behavior cleanly. I know I could pipe the input through a SAX parser and create nodes to insert into the tree, but that seems kind of messy. Is there a better way? Thanks. From jschamba at physics.utexas.edu Tue Nov 1 17:04:08 2005 From: jschamba at physics.utexas.edu (Jo Schambach) Date: Tue, 01 Nov 2005 16:04:08 -0600 Subject: array of Tkinter variables? Message-ID: I want to build an array of entry widgets in python with Tkinter that all have similar textvariables. I was hoping that I could use an array of StringVar variables to attach to these widgets, so that I can loop through the widget creation. But my simple minded approach failed: for i in range(32): self.dllAdjust[i] = StringVar() self.dllAdjust[i].set('000') gives me the following error: File "./config.py", line 787, in setDefaultVals self.dllAdjust[i] = StringVar() AttributeError: Configurator instance has no attribute 'dllAdjust' ("Configurator" is the class in which this code fragment appears) How does one define an array of StringVar? If that is not possible, what would be an alternative approach to the idea in the code fragment above? Jo -- Dr Joachim Schambach The University of Texas at Austin Department of Physics 1 University Station C1600 Austin, Texas 78712-0264, USA Phone: (512) 471-1303; FAX: (814) 295-5111 e-mail: jschamba at physics.utexas.edu From steve at REMOVETHIScyber.com.au Sat Nov 19 05:45:40 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 21:45:40 +1100 Subject: Immutable instances, constant values References: Message-ID: On Fri, 18 Nov 2005 14:32:46 +1100, Ben Finney wrote: > Is there any difference between a Python immutable value, and a > constant? I suppose "constant" also implies that the *name* binds > unchangeably to a particular value. Is that meaningful? That's precisely how I understand "constant" to be useful. Consider: c = 2.9979246e+08 # speed of light in metres per second def energy(mass): """Converts mass in kilograms to energy in joules""" return mass*c**2 That works fine until the name c is rebound to some other value. The fact that the float object 2.9979246e+08 is immutable is necessary but not sufficient. > How does one actually ensure an object is immutable? Is it a matter of > overriding a bunch of methods, or is ther a neater way? > > Is it bad style to make a user-defined class that creates immutable > objects? Why? I can't see why it would be bad style. That's what FrozenSet does. > In the case of 'enum', can anyone argue for or against an enumerated > type being immutable? Its values being constant? According to Gary Larson, there are four fundamental types of people. You can tell them apart from their reaction to being given a half-filled glass: "The glass is half full." "The glass is half empty." "Half full. No, half empty! No, half full. Wait... what was the question?" "Hey! I ordered a cheeseburger!" We might handle this with: states = Enum("full", "empty", "indeterminate", "cheeseburger") which then get referred to with: states.full states.empty states.indeterminate states.cheeseburger I might decide that "argumentative" is a better label than "cheeseburger", and mutate the appropriate enum value. What should happen? I see three possibilities: (1) states.cheeseburger still hangs around, but is not equivalent to states.argumentative, in much the same way that reloading a module can leave obsolete objects in your namespace (reloading doesn't automatically cause names that point to objects from a module to rebind to new objects). (2) references to states.cheeseburger raise an exception (3) references to states.cheeseburger are equivalent to states.argumentative. A rose by any other name. It shouldn't matter what label we put on the enums, in principle. Possibility (1) is obviously Bad with a Capital B, and should be avoided. Possibility (2) has the saving grace that it is no different to what happens if you rebind class attributes. There is an argument that if you can rebind class attributes, you should be able to rebind enums and face the consequences (good bad or indifferent) as best you can. Possibility (3) is the logical solution. It shouldn't matter what labels we put on the enums. But I fear not practical unless the enums are implemented as Singletons (multitons?), and perhaps not even then. Alternatively, you could bypass the whole problem by making enums immutable. -- Steven. From gandalf at designaproduct.biz Thu Nov 10 10:09:31 2005 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Thu, 10 Nov 2005 16:09:31 +0100 Subject: IE Temporary Internet Files & Python In-Reply-To: References: Message-ID: <437362AB.5070207@designaproduct.biz> >The script does not seem to work when used on Temporary Internet Files. > > Doesn't work well? What does it mean? Is there an exception raised? Les From documentation-bounces at vovida.org Thu Nov 24 08:47:33 2005 From: documentation-bounces at vovida.org (documentation-bounces at vovida.org) Date: Thu, 24 Nov 2005 05:47:33 -0800 Subject: Your message to documentation awaits moderator approval Message-ID: Your mail to 'documentation' with the subject pcgiqaqwbxsoyvyg Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://www.vovida.org/mailman/confirm/documentation/b748613cfdb91cb9550ef8952820c2f71671f5ac From Dennis.Benzinger at gmx.net Tue Nov 29 04:35:08 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 29 Nov 2005 10:35:08 +0100 Subject: XMLSchema Parsing In-Reply-To: References: Message-ID: <438c20ca$1@news.uni-ulm.de> km schrieb: > Hi all, > i'd like to know if there are any good XMLSchema (.xsd files) parsing modules in python. > regards, > KM > Try lxml a pythonic binding for the libxml2 and libxslt libraries. Bye, Dennis From jdtiede at sstar.com Wed Nov 30 10:05:32 2005 From: jdtiede at sstar.com (John Tiedeman) Date: Wed, 30 Nov 2005 09:05:32 -0600 Subject: Python-list Digest, Vol 14, Issue 147 In-Reply-To: <20041110185554.117CB1E4005@bag.python.org> References: <20041110185554.117CB1E4005@bag.python.org> Message-ID: On Wed, 10 Nov 2004 19:55:54 +0100 (CET) python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." From et1ssgmiller at gmail.com Thu Nov 17 06:47:00 2005 From: et1ssgmiller at gmail.com (Greg Miller) Date: 17 Nov 2005 03:47:00 -0800 Subject: sqlite utf8 encoding error Message-ID: <1132228020.486726.26630@g47g2000cwa.googlegroups.com> I have an application that uses sqlite3 to store job/error data. When I log in as a German user the error codes generated are translated into German. The error code text is then stored in the db. When I use the fetchall() to retrieve the data to generate a report I get the following error: Traceback (most recent call last): File "c:\Pest3\Glosser\baseApp\reportGen.py", line 199, in OnGenerateButtonNow self.OnGenerateButton(event) File "c:\Pest3\Glosser\baseApp\reportGen.py", line 243, in OnGenerateButton warningresult = messagecursor1.fetchall() UnicodeDecodeError: 'utf8' codec can't decode bytes in position 13-18: unsupported Unicode code range does anyone have any idea on what could be going wrong? The string that I store in the database table is: 'Keinen Text f?r ?bereinstimmungsfehler gefunden' I thought that all strings were stored in unicode in sqlite. Greg Miller From exarkun at divmod.com Mon Nov 7 12:25:11 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 7 Nov 2005 12:25:11 -0500 Subject: RAW_INPUT In-Reply-To: <1131387255.3171.1.camel@localhost.localdomain> Message-ID: <20051107172511.10365.1011649657.divmod.quotient.4848@ohm> On Mon, 07 Nov 2005 12:14:15 -0600, A D wrote: >On Mon, 2005-11-07 at 07:57 -0800, john boy wrote: >> I am having trouble with the following example used in a tutorial: >> >> print "Halt !" >> s = raw_input ("Who Goes there? ") >> print "You may pass,", s > >at this print line you need to do >print "you may pass, %s" % s > >this will allow you to enter the string s into the output sentence No, this is totally irrelevant. The print in the original code will work just fine. > >> >> I run this and get the following: >> Halt! >> Who Goes there? >> >> --thats it....if I hit enter again "You may pass," >> appears... >> >> In the example after running you should get: >> >> Halt! >> Who Goes there? Josh >> You may pass, Josh >> >> I'm assuming s=Josh...but that is not included in the statement at all >> I don't know how you put "Josh" in or how you got it to finish running >> w/o hitting enter after "Who goes there?" >> >> What am I doing wrong? Did you try typing "Josh" and then enter? Or any other name, for that matter... Jean-Paul From simon.brunning at gmail.com Fri Nov 11 15:09:33 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 11 Nov 2005 20:09:33 +0000 Subject: Python Countdown In-Reply-To: <20051111195325.65703.qmail@web35915.mail.mud.yahoo.com> References: <8c7f10c60511111141u4196c852v@mail.gmail.com> <20051111195325.65703.qmail@web35915.mail.mud.yahoo.com> Message-ID: <8c7f10c60511111209x31617c24g@mail.gmail.com> On 11/11/05, john boy wrote: > I have adjusted the program to: > > import sys. > sys. getrecursionlimit() > sys.setrecursionlimit(2000) > def countdown (n): > if n ==0: > print "blastoff" > else: > print n > countdown (n-1) > countdown (1200) > > this acutally works now.... Good! > is there any way to permanently set the recursion > level or do I have to type a setrecursionlimit everytime the program will > likely exceed 1000 Well, you could always always set it in site.py, I suppose, but in general, I prefer iteration over recursion in Python. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at REMOVETHIScyber.com.au Mon Nov 28 17:12:36 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 29 Nov 2005 09:12:36 +1100 Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> <1133193055.057481.174380@g49g2000cwa.googlegroups.com> <1133194571.960132.94640@g43g2000cwa.googlegroups.com> Message-ID: On Mon, 28 Nov 2005 08:16:12 -0800, Martin Miller wrote: > First of all,why do you think the new module is deprecated? (I can't > find anything in the docs to indicate this.) Did you try help(new) from an interactive prompt? py> new.__doc__.splitlines()[0] 'Create new objects of various types. Deprecated.' -- Steven. From fccoelho at gmail.com Sun Nov 27 18:38:18 2005 From: fccoelho at gmail.com (Flavio) Date: 27 Nov 2005 15:38:18 -0800 Subject: importing a method Message-ID: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> hi, I have an object defined with a number of hardcoded methods. Class soandso: def __init__(self): self.this = 0 self.that = 1 def meth1(self): ... def meth2(self): ... def custom(self): pass I want to allow the user to write a python module that declares a function so that myprogram can import it and attribute it to the custom method of the soandso object. So far so good, that is an easy thing to do in Python. import usermodule a=soandso() a.custom = usermodule.function But, what if the method had to access the self attributes (self.this and self.that) of the soandso object? Can it be done? and if so, what is the most Pythonic way of doing it? thanks in advance, Fl?vio From pythonnew at gmail.com Fri Nov 25 21:00:07 2005 From: pythonnew at gmail.com (Ben Bush) Date: Fri, 25 Nov 2005 18:00:07 -0800 Subject: the first element in the list of list In-Reply-To: References: <8c11e4350511220636p59b22d63pced73232aed06379@mail.gmail.com> <8c11e4350511220802o3de6724dh72a01faea86fc6d4@mail.gmail.com> Message-ID: <8c11e4350511251800j63ca7227gc53e1767766ef72c@mail.gmail.com> On 11/22/05, Fredrik Lundh wrote: > "Ben Bush" wrote: > > > This question just came to my mind and not assigned by anyone. > > given that you and "Shi Mu" are asking identical questions, and that > you've both started to send questions via direct mail, can you please > ask your course instructor to contact me asap. > > thanks /F Hi Fredrik, Thanks for your help. Miss Mu is my friend and we are learning Python by ourselves. Because we have too many naive questions and we discussed first then posted online either though her or me. Actually we are looking for some good online python courses about data structure. Both of us are using gmail for easier to track everything that has been posted under the topic. That is why brings you confusion. Thanks a lot! Ben From grante at visi.com Wed Nov 23 13:20:48 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 23 Nov 2005 18:20:48 -0000 Subject: Reading binary data References: <1132769538.319905.272190@z14g2000cwz.googlegroups.com> Message-ID: <11o9co08ahk07cf@corp.supernews.com> On 2005-11-23, David M wrote: > OK so here is my task. I want to get at the data stored in > /var/account/pacct, which stores process accounting data, so that I can > make it into a more human understandable format then what the program > sa can do. The thing is, its in a binary format and an example program > that reads some data from the file is done in C using a struct defined > in sys/acct.h. > > http://www.linuxjournal.com/articles/lj/0104/6144/6144l2.html > > So I was wondering how can I do the same thing, but in python? I'm > still learning so please be gentle. use the struct module http://www.python.org/doc/current/lib/module-struct.html -- Grant Edwards grante Yow! O.K.! Speak with a at PHILADELPHIA ACCENT!! Send visi.com out for CHINESE FOOD!! Hop a JET! From lycka at carmen.se Thu Nov 3 12:41:13 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 03 Nov 2005 18:41:13 +0100 Subject: Learning multiple languages (question for general discussion) In-Reply-To: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> Message-ID: infidel wrote: > Python has spoiled me. I used to periodically try out new languages > just for fun, but since learning Python, it's become a lot less > interesting. I find myself preferring to just try new ideas or > techniques in Python rather than searching for new languages to dabble > in. Agreed. It's a bit like getting married. Maybe it seems a little more dull than chasing new girls now and then, but it's really much more rewarding to grow together with a (person or language) that you know and like really well. Particularly when it's such amazing darlings such as Python and my wife! :) From bignose+hates-spam at benfinney.id.au Sun Nov 13 18:54:40 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Nov 2005 10:54:40 +1100 (EST) Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: Michael wrote: > Ben Finney wrote: > > I've yet to see a convincing argument against simply assigning > > values to names, then using those names. > > If you have a name, you can redefine a name, therefore the value a > name refers to is mutable. Since there are mutable and immutable values, it might be clearer to say "the binding of a name to a value can be changed". Yes? In that case, I don't see why someone who wants such a binding to be unchanging can't simply avoid changing it. Where's the case for having Python enforce this? > Conversely consider "NAME" to be a symbol. I can't modify "NAME". It > always means the same as "NAME" and "NAME", but is never the same as > "FRED". What's tricky is I can't have namespaceOne."NAME" [1] and > namespaceTwo."NAME" as different "NAME"s even though logically > there's no reason I couldn't treat "NAME" differently inside each. So you want to mark such objects as being in a namespace, where they compare the same within that namespace but not outside. Why is separate syntax necessary for this? A data type that is informed of its "space", and refuses comparison with values from other spaces, would suffice. class Xenophobe(object): def __init__(self, space, value): self.__space = space self.__value = value def __str__(self): return str(self.__value) def __cmp__(self, other): if not isinstance(other, Xenophobe): raise AssertionError, \ "Can only compare Xenophobes to each other" if not other.__space == self.__space: raise AssertionError, \ "Can only compare Xenophobes from the same space" return cmp(self.__value, other.__value) With the bonus that you could pass such values around between different names, and they'd *still* compare, or not, as you choose when you first create them. Replace the AssertionError with some appropriate return value, if you want such comparisons to succeed. > However it might be useful to note that these two values (or > symbols) are actually different, even if you remove their > namespaces. The above Xenophobe implementation creates objects that know their "space" forever. > To me, the use of a symbol implies a desire for a constant, and then > to only use that constant rather than the value. In certain > situations it's the fact that constant A is not the same as constant > B that's important (eg modelling state machines). Since the actual value can't be easily accessed, the only purpose of a Xenophobe is too be created and compared to others. > Often you can use strings for that sort of thing, but unfortunately > even python's strings can't be used as symbols that are always the > same thing in all ways. For example, we can force the id of > identical strings to be different: Hold up -- what in your stated use case requires *identity* to be the same? You said you just wanted to compare them to each other. Besides, Python *does* preserve identity for short strings... > >>> s = "h"*10000 > >>> x = "h"*10000 > >>> id(s), id(x) > (135049832, 135059864) ... which is sufficient for unique values, if you're not actively fighting the system as above. If the use case is for brief, identical values, we have those: short strings. > As a result I can see that *IF* you really want this kind of symbol, > rather than the various other kinds people have discussed in the > thread, that some special syntax (like u'hello' for unicode 'hello') > could be useful. I can see the case for a new type. I disagree that syntax changes are necessary. > However, I'd be more interested in some real world usecases where > this would be beneficial, and then seeing what sort of syntax would > be nice/useful (Especially since I can think of some uses where it > would be nice). Real use cases would interest me, too, but *only* if they can't be satisfied with a new type that knows things about its creation state, such as Xenophobe. > The reason I'm more interested in seeing usecases, is because I'd > rather see where the existing approaches people use/define symbols > has caused the OP problems to the extent he feels the language needs > to change to fix these real world problems. Ditto. -- \ "My aunt gave me a walkie-talkie for my birthday. She says if | `\ I'm good, she'll give me the other one next year." -- Steven | _o__) Wright | Ben Finney From gh at ghaering.de Wed Nov 9 11:12:24 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 09 Nov 2005 17:12:24 +0100 Subject: Lie Hetland book: Beginning Python.. In-Reply-To: References: Message-ID: <43721FE8.9090704@ghaering.de> Vittorio wrote: > [...] > Nonetheless, I was unable to find any documentation about such a > different behaviour between Pysqlite and Pysqlite2; from my beginner > point of view the Pysqlite (Magnus' version) paramstyle looks a better > and more pythonic choice and I don't grasp the Pysqlite2 developers' > intentions deviating from that way. The reason why pysqlite 0.x/1.x used paramstyle "pyformat", based on Python string substitution for SQL parameters is that at the time pysqlite was started, SQLite 2.x did not have any support for parameter binding. So we had to "fake" it in Python, just like the MySQL interface does (for the same reasons). Later SQLite 2.x versions and of course SQLite 3.x supported real bound parameters and pysqlite2 was developed from scratch to benefit from them. SQLite 3.x supports both qmark and named paramstyles, so you can use question marks *or* named parameters: >>> from pysqlite2 import dbapi2 as sqlite >>> con = sqlite.connect(":memory:") >>> cur = con.cursor() >>> cur.execute("select 2*?", (14,)) >>> cur.fetchone() (28,) >>> >>> cur.execute("select 2 * :x", {"x": 14}) >>> cur.fetchone() (28,) >>> >>> x = 14 >>> cur.execute("select 2 * :x", locals()) >>> cur.fetchone() (28,) >>> I've also once written a wrapper using pysqlite 2.x's hooks that allows you to use the "format" paramstyle with pysqlite 2.x, so you can reuse more code that was originally written against pysqlite 0.x/1.x: from pysqlite2 import dbapi2 as sqlite class PyFormatConnection(sqlite.Connection): def cursor(self): return sqlite.Connection.cursor(self, PyFormatCursor) class PyFormatCursor(sqlite.Cursor): def execute(self, sql, args=None): if args: qmarks = ["?"] * len(args) sql = sql % tuple(qmarks) sqlite.Cursor.execute(self, sql, args) else: sqlite.Cursor.execute(self, sql) con = sqlite.connect(":memory:", factory=PyFormatConnection) cur = con.cursor() cur.execute("create table test(a, b, c)") cur.execute("insert into test(a, b, c) values (%s, %s, %s)", ('asdf', 4, 5.2)) cur.execute("select a, b, c from test where c <> %s", (4.27,)) print cur.fetchone() cur.close() con.close() > I would be very grateful if someone would cast a light over > Pysqlite/Pysqlite2 discrepancies. I think about the only place I wrote a bit about the differences was in the pysqlite 2.0 final announcement: http://lists.initd.org/pipermail/pysqlite/2005-May/000043.html -- Gerhard From philippe.dalet at voila.fr Fri Nov 25 11:27:07 2005 From: philippe.dalet at voila.fr (pdalet) Date: 25 Nov 2005 08:27:07 -0800 Subject: How to get started in GUI Programming? In-Reply-To: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> References: <1132927360.270239.64670@f14g2000cwb.googlegroups.com> Message-ID: <1132936027.208519.283280@g14g2000cwa.googlegroups.com> If you come from visual basic, I suggest to use pythoncard GUI, which is very simple to develop with a Ressource Editor (create a panel, see labwindows, visual basic ..). https://sourceforge.net/projects/vb2py/ a package to transform VB to pythoncard http://www.linux2000.com/pimp.html a pythoncard application Philippe DALET Lyp champollion 46100 FIGEAC FRANCE peter.mosley at talk21.com a ?crit : > I am trying to learn GUI programming in Python, but have to confess I > am finding it difficult. > > I am not an experienced programmer - just someone who from time to > time writes small programs for my use. Over the years I have moved > from GWBASIC to QBASIC to Visual Basic, and now trying to move across > to a Linux platform. Python seems to be the best compromise between > the limitations of command line basic programming and the total > incomprehensibility of C. > > Googling around it seems the best GUI is either Tkinter or PyGtk. I > found a book which recommended PyGtk, as it had a graphical design > option, Glade. Coming from a VB background I latched onto that and > bought the book (Beginning Python, Wrox), but it was a disappointment > (or more accurately a complete waste of money) - there was > insufficient detail in the text. > > I've found the tutorial and reference manual on the PyGtk web site, > but although I've made some progress, I keep reaching points where I > have insufficient background to understand them. Currently I'm stuck > on dialog boxes (the code seems immensely complex for the equivalent of > MsgBox("Do you really want to do this ",vbYesNo) and I haven't > got it to work properly yet) and loading graphical images in anything > other than their original size, but every new step brings another > struggle > > I've seen reference to a Tkinter book - something like 'Python > and Tkinter Programming' but it seems to be out of print and > unavailable. > > Can anyone offer any suggestions as to the least painful way forwards? > > (Email address was valid once but has long since been abandoned to > spam. Please rely via newsgroup) From muttu2244 at yahoo.com Mon Nov 14 07:27:57 2005 From: muttu2244 at yahoo.com (muttu2244 at yahoo.com) Date: 14 Nov 2005 04:27:57 -0800 Subject: problem with from win32com.client import Dispatch Message-ID: <1131971277.550304.66840@g14g2000cwa.googlegroups.com> Hi all Am trying to read an html page using win32com in the following way. from win32com.client import Dispatch ie = Dispatch("InternetExplorer.Application") ie.Navigate("https://secure.authorize.net/") doc =ie.Document print doc.body.innerHTML with this code am easily able to read the mentioned page from the pythonwin interactive window, but the same code if I write it in some *.py file, am not able to read the page. The following error it throws when I compile the file. Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Python23\Lib\site-packages\Script1.py", line 14, in ? ie.Quit() File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", line 456, in __getattr__ return self._ApplyTypes_(*args) File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", line 446, in _ApplyTypes_ return self._get_good_object_( com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None) if any body has the answer for this please help me in this. Thanks and regards Yogi From pu at pmville.com Fri Nov 18 01:46:57 2005 From: pu at pmville.com (Ask) Date: Fri, 18 Nov 2005 17:46:57 +1100 Subject: GTK for windows and Linux References: <437c3560@news1.veridas.net> Message-ID: <437d7903$1@news1.veridas.net> Of course that's where I first looked but the amount of options are many. Thanks anyway. "Antoon Pardon" wrote in message news:slrndnolhb.isd.apardon at rcpc42.vub.ac.be... > Op 2005-11-17, Ask schreef : >> Hi All, >> >> Can someone please tell me what I need to use GTK with python for windows >> and Linux? >> >> Any links to the appropriate installations would be greatly appreciated >> as I >> don't know what I need... GIMP... GTK+ etc > > Well I think if you visit http://www.pygtk.org/, it will answer most of > your questions. > > -- > Antoon Pardon From aleax at mail.comcast.net Sun Nov 13 19:37:59 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 13 Nov 2005 16:37:59 -0800 Subject: gmpy 1.01 binaries for the mac Message-ID: <1h5xi1j.k0d5hy1nmkakcN%aleax@mail.comcast.net> I've added to gmpy.sf.net two binary packages of gmpy for Mac OS X 10.4, one for the Python 2.3.5 that comes with the system and one for Bob Ippolito's build of 2.4.1. They still need GMP to be previously installed (I'm told the one that comes with fink works; I installed my own from sources, from the GMP's site at swox.com), and they're .tar.gz packages requiring unpacking with tar xzf from the Terminal -- so, not very Mackish -- but they may still help if you don't want to install Apple's free and powerful XCode (which IS currently an 800+ MB download, after all) and still want to play with gmpy's functionality on your Mac's Python, I hope. Let me know if there's interest in me eventually doing a better job of Mac packaging... while I have a hard time getting ahold of Windows machines, and particularly suitable development systems for them, I _am_ rather full of Macs (& dev systems for them;-)... Alex From fredrik at pythonware.com Fri Nov 25 04:49:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Nov 2005 10:49:54 +0100 Subject: Guification of console app References: <1132871970.821787.204830@g14g2000cwa.googlegroups.com> <1132909528.263090.326890@g47g2000cwa.googlegroups.com> Message-ID: "metiu" wrote: > you have a compression utility that works as a standard *nix filter, so > it takes something from stdin and gives it back compressed to stdout > you like to use it as such, because it's nice to call it from the > command line > > now someone finds your utility quite nice, and says it would be nice to > have a GUI that shows you, for example, how long it will take to > compress... > > one way for sure it would be to fork your app, but this would be a > waste of time > > you'd like to reuse the compression library you've already written for > your GUI and your console, but: > - you'd like to have your console app clean and simple, such as: > > import sys > import CompressLib > > data = sys.stdin.read() > cdata = CompressLib.compress(data) > print cdata > > but you'd like the GUI to show some progress and status info. here's a simple, stupid, and portable solution. the first script simulates your compression utility: # compress.py (simulator) import time, sys for i in range(100): sys.stdout.write(".") sys.stderr.write("%d%% done\r" % i) sys.stderr.flush() time.sleep(0.1) (it prints "N% done" messages to stderr during the compression) the second script simulates your GUI. the stuff in the while loop should be run by a timer/alarm function, at regular intervals: import re, subprocess, time, os class monitor: # looks for "N% done" messages in the output stream def __init__(self, tfile): # could use dup/reopen instead self.file = open(tfile.name, "r") def poll(self): pos = self.file.tell() data = self.file.read() if data: data = re.findall("(\d+)% done", data) if not data: self.file.seek(pos) else: return int(data[-1]) def close(self): self.file.close() ifile = open("in.txt", "rb") ofile = open("out.dat", "wb") tfile = open("out.tmp~", "wb") p = subprocess.Popen( "python compress.py", stdin=ifile, stdout=ofile, stderr=tfile, ) m = monitor(tfile) while 1: # this should be placed in a background task that's called # every second or so if p.poll() is not None: print "DONE" break status = m.poll() if status is not None: # update status monitor print status, "PERCENT DONE" # wait a while before calling the background task again print "." time.sleep(0.5) # clean up ifile.close() ofile.close() m.close() name = tfile.name tfile.close() os.remove(name) if you limit yourself to Unix only, you can simplify things quite a bit (e.g. using a pipe instead of the temporary file and use select to poll it, or use dup/reopen tricks to avoid opening the temporary file twice; if you do the latter, you can also use safe tempfile creation methods (see the "tempfile" method for details. etc). hope this helps! From lycka at carmen.se Thu Nov 24 05:52:28 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 24 Nov 2005 11:52:28 +0100 Subject: about sort and dictionary In-Reply-To: <1132793085.808501.279500@g44g2000cwa.googlegroups.com> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132793085.808501.279500@g44g2000cwa.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > "do things right" is my fundamental beef with Python. > Dispite claims, I don't believe Python's designers have > a monopoly on the definition of "right". "This hammer is stupid. It's very uncomfortable, and it's not hard and heavy enough to get the nails into the wall." "It will work better if you hold it in the other end." "Don't tell me how to hold my hammer. It's just built wrong. This cold and hard thing should be in the other end!" ;^) Seriously, it's not a matter of right or wrong. It's a matter of trying to understand how a tool is intended to be used, and to adjust to that. I'm not saying that all Python programmers should be some kind of Guido clones, there's plenty of room for variation, but it usually pays to be adaptable. Python fits my brain. I felt that from the start. YMMV. From everettcc at hotmail.com Thu Nov 17 19:15:11 2005 From: everettcc at hotmail.com (Chad Everett) Date: Thu, 17 Nov 2005 18:15:11 -0600 Subject: Socket Error Message-ID: <24aff.11700$cd1.1358@bignews5.bellsouth.net> Does anyone know why you get socket error while trying to run IDLE and the module. Is says something about a Subprocess Startup Error. I know that it always says something about a personal firewall. I have all that shut off. About 50% of the time when I try and test code by running the module it will pop up. Any suggestions? thanks, From twic at urchin.earth.li Fri Nov 25 19:13:10 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 26 Nov 2005 00:13:10 +0000 Subject: Which License Should I Use? In-Reply-To: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> Message-ID: On Fri, 25 Nov 2005, mojosam wrote: > How do I decide on a license? You decide on what obligations you wish to impose on licensees, then pick a license which embodies those. There are basically three levels of obligation: 1. None. 2. Derivatives of the code must be open source. 3. Derivatives of the code and any other code which uses it must be open source. By 'derivatives', i mean modified versions. By 'open source', i really mean 'under the same license as the original code'. So, the licenses corresponding to these obligations are: 1. A BSD-style license. I say 'BSD-style' because there are about a hojillion licenses which say more or less the same thing - and it's quite amazing just how many words can be split spelling out the absence of obligations - but the grand-daddy of them all is the BSD license: http://www.opensource.org/licenses/bsd-license.php 2. The GNU Lesser General Public License: http://www.gnu.org/copyleft/lesser.html 3. The GNU General Public License: http://www.gnu.org/copyleft/gpl.html The GPL licenses place quite severe restrictions on the freedom of programmers using the code, but you often hear GNU people banging on about freedom - 'free software', 'free as in speech', etc. What you have to realise is that they're not talking about the freedom of the programmers, but about the freedom of the software. The logic, i think, is that the freedom of the code is the key to the freedom of the end-users: applying the GPL to your code means that other programmers will be forced to apply to to their code, which means that users of that code will get the benefits of open source. Having said all that, you can only license software if you own the copyright on it, and as has been pointed out, in this case, you might not. > Are there any web sites that summarize the pros and cons? The GNU project has a quite useful list of licenses, with their takes on them: http://www.gnu.org/licenses/license-list.html Bear in mind that the GNU project is strongly in favour of the GPL, so they're perhaps not as positive about non-GPL licenses as would be fair. This dude's written about this a bit: http://zooko.com/license_quick_ref.html > I guess I don't care too much about how other people use it. These > things won't be comprehensive enough or have broad enough appeal that > somebody will slap a new coat of paint on them and try to sell them. I > guess I don't care if somebody incorporates them into something bigger. > If somebody were to add features to them, it would be nice to get the > code and keep the derivative work as open source, but I don't think that > matters all that much to me. If somebody can add value and find a way > of making money at it, I don't think I'd be too upset. To me, it sounds like you want a BSD-style license. But then i'm a BSD afficionado myself, so perhaps i would say that! In fact, while were on the subject, let me plug my own license page: http://urchin.earth.li/~twic/The_Amazing_Disappearing_BSD_License.html I apply 0-clause BSD to all the code i release these days. > I will be doing the bulk of the coding on my own time, because I need to > be able to take these tools with me when I change employers. However, > I'm sure that in the course of using these tools, I will need to spend > time on the job debugging or tweaking them. I do not want my current > employer to have any claim on my code in any way. Usually if you > program on company time, that makes what you do a "work for hire". I > can't contaminate my code like that. Does that mean the GPL is the > strongest defense in this situation? The license you choose has absolutely no bearing on this. Either the copyright belongs to you, in which case you're fine, or to your employer, in which case you don't have the right to license it, so its moot. > Let's keep the broader issue of which license will bring about the fall > of Western Civilization You mean the GPL? > on the other thread. Oops! tom -- Science runs with us, making us Gods. From steve at REMOVETHIScyber.com.au Fri Nov 18 22:46:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 19 Nov 2005 14:46:23 +1100 Subject: How to convert a "long in a string" to a "long"? References: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> Message-ID: On Fri, 18 Nov 2005 11:10:06 -0500, Carsten Haese wrote: >> s = long("0xffffffffL") >> ValueError: invalid literal for long(): 0xffffffffL >> >> s = long("0xffffffff") >> ValueError: invalid literal for long(): 0xffffffffL >> >> What can I do? >> >> Thank you in advance. >> Stefan > > Leave out the "0x" prefix and tell long() that you're using base 16: > >>>> long("ffffffff", 16) > 4294967295L Or leave the prefix in, and tell Python to use the prefix to predict the base: py> long("0xffffffffL", 0) 4294967295L -- Steven. From mwm at mired.org Fri Nov 4 05:22:06 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 04 Nov 2005 05:22:06 -0500 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> <8764r8u3wr.fsf@keizer.soze.com> Message-ID: <86ek5whfw1.fsf@bhuda.mired.org> > Would it be too much to ask that in a line like. > > x = x + 1. > > both x's would resolve to the same namespace? Yes. That's to much bondage for programmers who've become accustomed to freedom. Explain why this should be illegal: >>> class C: ... def __getattr__(self, name): ... x = 1 ... return locals()[name] ... def __setattr__(self, name, value): ... globals()[name] = value ... >>> o = C() >>> o.x = o.x + 1 >>> x 2 >>> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From __peter__ at web.de Tue Nov 8 05:51:15 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Nov 2005 11:51:15 +0100 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> Message-ID: Jerzy Karczmarczuk wrote: > Sure, I didn't want to claim that the assignment a=anything can be plainly > overloaded. I interpreted your previous post as such a claim. No disagreement here then. > Would you please concentrate on - what I underlined - the sense of "C" > aliasing, where you can make a pointer to point to anything, say, the > 176th byte of a function code? I've never heard the expression "aliasing" for that, sorry. > This is impossible in Python. Of course, but I don't think this is what the OP wanted. Peter From venkatasubramanian at gmail.com Fri Nov 4 01:50:06 2005 From: venkatasubramanian at gmail.com (venk) Date: 3 Nov 2005 22:50:06 -0800 Subject: reading internet data to generate random numbers. In-Reply-To: References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> <11mi8n2t39q2534@corp.supernews.com> <11mj21gr6rjgc65@corp.supernews.com> <86ll06jr79.fsf@bhuda.mired.org> <4369B2CF.70201@REMOVEMEcyber.com.au> <11mkcg2l9d89qff@corp.supernews.com> Message-ID: <1131087006.011989.243160@g49g2000cwa.googlegroups.com> hotbits hotbits hotbits! http://www.fourmilab.ch/hotbits/ based on quantum mechanics.... check it out! From dcrespo at gmail.com Tue Nov 8 09:30:53 2005 From: dcrespo at gmail.com (dcrespo) Date: 8 Nov 2005 06:30:53 -0800 Subject: Application monitor In-Reply-To: <868xw09hap.fsf@bhuda.mired.org> References: <1131399761.209133.19690@g49g2000cwa.googlegroups.com> <868xw09hap.fsf@bhuda.mired.org> Message-ID: <1131460253.286733.232240@o13g2000cwo.googlegroups.com> > Personally, I use init > as an app monitor. It doesn't need monitoring What's "init"? Sorry about my ignorance. From pwatson at redlinepy.com Wed Nov 23 20:45:03 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 23 Nov 2005 19:45:03 -0600 Subject: 2.4.2 on AIX fails compiling _codecs_cn.c In-Reply-To: <43850790$0$4066$9b622d9e@news.freenet.de> References: <3uk6siF11mqgvU1@individual.net> <4384ec18$0$25871$9b622d9e@news.freenet.de> <438505AA.8000105@redlinepy.com> <43850790$0$4066$9b622d9e@news.freenet.de> Message-ID: <3ukk91F11t5c5U1@individual.net> Martin v. L?wis wrote: > Paul Watson wrote: > >> Can we #undef _ALL_SOURCE for _codecs_cn.c compilation? > > > Where does _ALL_SOURCE come from? Why is it defined? > What is its effect on hz? > > Regards, > Martin Martin v. L?wis wrote: > Paul Watson wrote: > >> Can we #undef _ALL_SOURCE for _codecs_cn.c compilation? > > > Where does _ALL_SOURCE come from? Why is it defined? > What is its effect on hz? > > Regards, > Martin It appears that _ALL_SOURCE gets defined in the /usr/include/standards.h file. If we could #define _ANSI_C_SOURCE or _POSIX_SOURCE, it appears that it would eleminate _ALL_SOURCE. $ cat t.c #include #include int main() { printf("hello, world\n"); #ifdef _ALL_SOURCE printf("hello, again\n"); #endif exit(0); } $ cc_r t.c $ ./a.out hello, world hello, again From piet at cs.uu.nl Wed Nov 23 12:15:37 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 23 Nov 2005 18:15:37 +0100 Subject: How to write an API for a Python application? References: <437af434@news.bezeqint.net> <80842$437e51f0$520491f0$23836@nf2.news-service.com> <5f05b$4383119c$520491f0$4821@nf2.news-service.com> Message-ID: >>>>> Duncan Grisby (DG) wrote: >DG> I've not done any benchmarks for Python (yet), but I've just posted >DG> some results to comp.object.corba that show omniORB is a lot faster >DG> than Ice for many things. Very n ice (that was an accident, but I decided to let it stay). -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From scott.daniels at acm.org Mon Nov 21 20:21:11 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 21 Nov 2005 17:21:11 -0800 Subject: Any royal road to Bezier curves...? In-Reply-To: References: Message-ID: <438270fb$1@nntp0.pdx.net> The Bezier gives control points with natural interpretations and a nice "within the convex hull" property. I happen to like Beziers to control curves which are aestheticly, rather than computationally defined. -- -Scott David Daniels scott.daniels at acm.org From twic at urchin.earth.li Fri Nov 25 14:42:49 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 25 Nov 2005 19:42:49 +0000 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> <1132737886.158858.255830@g44g2000cwa.googlegroups.com> <4384538f.541027426@news.oz.net> Message-ID: On Wed, 23 Nov 2005, Carsten Haese wrote: > On Wed, 2005-11-23 at 15:17, Christoph Zwerschke wrote: >> Bengt Richter wrote: >> >> > E.g., it might be nice to have a mode that assumes d[key] is >> d.items()[k][1] when >> > key is an integer, and otherwise uses dict lookup, for cases where >> the use >> > case is just string dict keys. >> >> I also thought about that and I think PHP has that feature, but it's >> probably better to withstand the temptation to do that. It could lead >> to an awful confusion if the keys are integers. > > Thus quoth the Zen of Python: > "Explicit is better than implicit." > "In the face of ambiguity, refuse the temptation to guess." > > With those in mind, since an odict behaves mostly like a dictionary, [] > should always refer to keys. An odict implementation that wants to allow > access by numeric index should provide explicitly named methods for that > purpose. +1 Overloading [] to sometimes refer to keys and sometimes to indices is a really, really, REALLY bad idea. Let's have it refer to keys, and do indices either via a sequence attribute or the return value of items(). More generally, if we're going to say odict is a subtype of dict, then we have absolutely no choice but to make the methods that it inherits behave the same way as in dict - that's what subtyping means. That means not doing funky things with [], returning a copy from items() rather than a live view, etc. So, how do we provide mutatory access to the order of items? Of the solutions discussed so far, i think having a separate attribute for it - like items, a live view, not a copy (and probably being a variable rather than a method) - is the cleanest, but i am starting to think that overloading items to be a mutable sequence as well as a method is quite neat. I like it in that the it combines two things - a live view of the order and a copy of the order - that are really two aspects of one thing, which seems elegant. However, it does strike me as rather unpythonic; it's trying to cram a lot of functionality in an unexpected combination into one place. Sparse is better than dense and all that. I guess the thing to do is to try both out and see which users prefer. tom -- YOU HAVE NO CHANCE TO ARRIVE MAKE ALTERNATIVE TRAVEL ARRANGEMENTS. -- Robin May From bonono at gmail.com Wed Nov 9 23:18:03 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 20:18:03 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <1131595096.310029.98740@g43g2000cwa.googlegroups.com> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131595096.310029.98740@g43g2000cwa.googlegroups.com> Message-ID: <1131596283.073069.165700@g43g2000cwa.googlegroups.com> George Sakkis wrote: > >>> list(takewhile(p, xrange(10000000))) > [0, 1] thanks. that is what I am doing now, in a more generic form : takewhile(p, (x for x in xrange(100000000))) From mwm at mired.org Sat Nov 26 07:34:13 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 07:34:13 -0500 Subject: Why is dictionary.keys() a list and not a set? References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> Message-ID: <86br07fv0a.fsf@bhuda.mired.org> Christoph Zwerschke writes: > Mike Meyer wrote: > > I think you're trying to tweak the wrong definition. Types are > > immutable if their instances are immutable. > I'm not trying to tweak it, but to gain more clarity about what is > actually meant when you talk about "mutable" types and objects and > whether it suffices to use these terms as long as you speak about > built-in datatypes. I think we both agree that mutability isn't adequate, because it's really irrelevant to the question. What it seems to provide is a convenient and usually well-understood way of describing which builtin types can be used: "Mutable builtin types cannot be used as dictionary keys." "Immutable builtin types can be used as dictionary keys, except for certain tuples." That exception creates headaches. Then you have to ponder things like "Is a file instance immutable?" because they are hashable. Maybe we should just skip the idea completely. > > Do you think it's really necessary to specify "has a __hash__ method > > that returns a value", as opposed to just "has a __hash__ method"? > I think it is necessary to require that it has a "proper" __hash__ > function. As far as I understand you can always add a __hash__ > method. Not only invalid __hash__ methods like in this case: > class mylist0(list): > def __hash__(self): return None > But you can also easily add valid __hash__ methods: > > class mylist1(list): > def __hash__(self): return 0815 > > class mylist2(list): > def __hash__(self): return id(self) > > In the case of mylist1, everything is ok including semantics, but > performance suffers dramatically. In mylist2, performance is great, > but semantics suffers greatly. > Which of these user-defined types would you call "hashable"? The latter two, as the given __hash__ meets the specifications for __hash__. __hash__ itself isn't enough to decide the question of semantics. You can make mylist2 have the right semantics by adding def __eq__(self, other): return self is other to it. > Technically speaking, both probably are, so you can indeed use list > objects of both types as keys of a dictionary - but I think there > should be a hint in the docs that you need to have a "proper" hash > function if you want your dictionary to be performant and show the > usually expected behavior. I agree - but where does that hint belong? I think it belongs in the documentation for __hash__, not the documentation for sets and dictionaries. How about we document it in the spirit of Python's "try it and see" philosophy: Any hashable object can be used as a dictionary key/set element. An object is hashable if calling hash on that object returns an integer. That's 100% correct. However, is it to little information to be useful? If so, then going back to the mutable/immutable thing seems to be right: Any hashable object can be used as a dictionary key/set element. Instances of mutable builtins are not hashable. Instances of immutable builtins are hashable, except for tuples that contain a non-hashable value. Instances of classes are usually hashable(*). Footnote *: An instance of a class is hashable if it has a __hash__ method, or does not have either a __cmp__ or __eq__ method. If you're not sure, call hash() on the instance, and if it returns an integer, the instance is hashable. Either way, over in the documentation for __hash__, add a note that: For instances of a class to work properly with builtin container types, two instances that compare as equal must have the same hash value. For best performance, hash values should be different as often as possible while honoring the equality requirement. (or is that wrong?) http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From twic at urchin.earth.li Sat Nov 26 15:32:22 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 26 Nov 2005 20:32:22 +0000 Subject: Comparison problem In-Reply-To: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: Chris, as well as addressing what i think is causing your problem, i'm going to point out some bits of your code that i think could be polished a little. It's intended in a spirit of constructive criticism, so i hope you don't mind! On Sat, 26 Nov 2005, Chris wrote: > if item[0:1]=="-": item[0:1] seems a rather baroque way of writing item[0]! I'd actually suggest writing this line like this: if item.startswith("-:): As i feel it's more readable. > item=item[ :-7] > item=item[1:] You could just write: item = item[1:7] For those two lines. > infile=open("inventory","r") The "r" isn't necessary - reading is the default mode for files. You could argue that this documents your intentions towards the file, i suppose, but the traditional python idiom would leave it out. > while infile: > dummy=infile.readline() The pythonic idiom for this is: for dummy in infile: Although i'd strongly suggest you change 'dummy' to a more descriptive variable name; i use 'line' myself. Now, this is also the line that i think is at the root of your trouble: readline returns lines with the line-terminator ('\n' or whatever it is on your system) still on them. That gets you into trouble later - see below. When i'm iterating over lines in a file, the first thing i do with the line is chomp off any trailing newline; the line after the for loop is typically: line = line.rstrip("\n") > if dummy=='':break You don't by any chance mean 'continue' here, do you? > print item > print ", "+dummy > if (dummy == item): This is where it all falls down - i suspect that what's happening here is that dummy has a trailing newline, and item doesn't, so although they look very similar, they're not the same string, so the comparison comes out false. Try throwing in that rstrip at the head of the loop and see if it fixes it. HTH. tom -- Gotta treat 'em mean to make 'em scream. From deets at nospam.web.de Sun Nov 6 14:56:40 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 06 Nov 2005 20:56:40 +0100 Subject: Learning multiple languages (question for general discussion) In-Reply-To: <7xslu9ppaz.fsf@ruckus.brouhaha.com> References: <1131030123.345056.218380@g44g2000cwa.googlegroups.com> <1h5gyzz.1dt4ijb139wfwzN%aleax@mail.comcast.net> <1h5hs5y.19u42x51mo5hupN%aleax@mail.comcast.net> <7xvez5wvgc.fsf@ruckus.brouhaha.com> <3t6ubgFr6f2dU1@uni-berlin.de> <7xslu9ppaz.fsf@ruckus.brouhaha.com> Message-ID: <3t75fpFqtk5fU1@uni-berlin.de> Paul Rubin wrote: > "Diez B. Roggisch" writes: > >>It's a great book - I cetainly owe it the better part of my thesis >>about multi level specification for functional languages. If you want >>to understand type-systems, its a great comprehensive read. > > > So do I really want to understand type systems? I mean, I think I > understand Haskell types from reading the manual, but probably not at > the level of that TAPL book. Am I going to find out anything > important as an implementer? I don't know what you want to understand - I never learned a language by a book, if it's that what you want to know But to understand type systems in detail, compare them and know their limits will certainly make you a better programmer I guess - and especially in functional languages,as these are more or less built around their type-systems. Regards, Diez From bonono at gmail.com Sun Nov 27 06:34:06 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 27 Nov 2005 03:34:06 -0800 Subject: Comparison problem In-Reply-To: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> References: <1133031599.747967.320560@g47g2000cwa.googlegroups.com> Message-ID: <1133091246.949659.76300@g14g2000cwa.googlegroups.com> I think no matter what language you programs it, it is hard to understand. Can you break it up into sub-problems first ? Like first parsing the inventory file into a python dict, then also the fields from web to another dict ? Chris wrote: > Hi, > > I'm new to python, and I'm trying to write a small python script for a > webpage. The script opens up a file called inventory, reads the > contents, and checks the contents against the data from the form in my > webpage. Now I have to do some slicing to get the name of the form > elements (in this case, checkboxes), to resemble the values in the > inventory file. Here's my python part: > > #!/usr/local/bin/python > import cgi > import types > from Cookie import * > form=cgi.FieldStorage() > user_answer=[] > error='false' > item='' > qty='' > def main(): > print"Content-type: text/html\n" > i=open("inventory","r") > keys=form.keys() > for key in keys: > field=form[key] > if type(field)==types.InstanceType: > item=field.value > if item[0:1]=="-": > item=item[ :-7] > item=item[1:] > infile=open("inventory","r") > while infile: > dummy=infile.readline() > if dummy=='':break > print item > print ", "+dummy > if (dummy == item): > print"Found it" > else: > print"Didn\'t Find it" > print "
" > infile.close() > else: > #print" Quantity: " > #print item > print"
" > #print field.value > else: > print"BAD" > main() > > Let me know if more information is needed. Any assistance will be > greatly appreciated. From aleax at mail.comcast.net Fri Nov 25 12:30:00 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 25 Nov 2005 09:30:00 -0800 Subject: Persist a class (not an instance) References: <43871516$1_1@newspeer2.tds.net> Message-ID: <1h6ksmv.13ahmkh5fgeo2N%aleax@mail.comcast.net> Kent Johnson wrote: > Is there a way to persist a class definition (not a class instance, the > actual class) so it can be restored later? A naive approach using pickle > doesn't work: You can use copy_reg to customize pickling behavior. In this case, you'd need a custom metaclass to use as the type for your "picklable classes". Moreover, if the class has attributes that you also want to pickle, such as methods or properties, you'll have to arrange for custom pickling of *them*, too. So, yes, there are ways, but not simple ones. Alex From steve at holdenweb.com Sat Nov 5 00:12:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 05 Nov 2005 05:12:05 +0000 Subject: Class Variable Access and Assignment In-Reply-To: <7x4q6r1zb8.fsf@ruckus.brouhaha.com> References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <7xpsphlxri.fsf@ruckus.brouhaha.com> <7x3bmcaxnt.fsf@ruckus.brouhaha.com> <7x4q6r1zb8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steven D'Aprano writes: > >>It also allows you to do something like this: >> >>class ExpertGame(Game): >> current_level = 100 > > >>and then use ExpertGame anywhere you would have used Game with no problems. > > > Well, let's say you set, hmm, current_score = 100 instead of current_level. > Scores in some games can get pretty large as you get to the higher > levels, enough so that you start needing long ints, which maybe are > used elsewhere in your game too, like for the cryptographic signatures > that authenticate the pieces of treasure in the dungeon. Next you get > some performance gain by using gmpy to handle the long int arithmetic, > and guess what? Eventually a version of your game comes along that > enables the postulated (but not yet implemented) mutable int feature > of gmpy for yet more performance gains. So now, current_score += 3000 > increments the class variable instead of creating an instance > variable, and whoever maintains your code by then now has a very weird > bug to track down and fix. > > Anyway, I'm reacting pretty badly to the construction you're > describing. I haven't gotten around to looking at the asyncore code > but will try to do so. I wouldn't bother. From memory it's just using a class variable as an initialiser. 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 fuzzyman at gmail.com Mon Nov 14 11:12:03 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Nov 2005 08:12:03 -0800 Subject: ANN: rest2web 0.4.0alpha Message-ID: <1131984723.071591.299390@g49g2000cwa.googlegroups.com> rest2web 0.4.0 alpha is now available. http://www.voidspace.org.uk/python/rest2web/ What's New ? ========== See http://www.voidspace.org.uk/python/rest2web/reference/changelog.html#version-0-4-0-alpha-2005-11-11 Lots of bugfixes and new features since the 0.3.0 release. Includes a new gallery plugin (which will also function as a standalone HTML gallery generator). http://www.voidspace.org.uk/python/rest2web/reference/gallery.html There is also an experimental windows executable version. The documentation has been greatly improved, including a tutorial which should get anyone up to scratch on the basics very quickly. http://www.voidspace.org.uk/python/rest2web/tutorial.html What is rest2web ============= **rest2web** is a tool for autogenerating wesites, or parts of websites. It's main features are : * Integrated with docutils. * Automatically builds index pages and navigation links (sidebars and {acro;breadcrumbs;Weird name for navigation links ?}). * Embedded code in templates for unlimited expressiveness. * Flexible macro system. * Uses relative links, so sites can be viewed from the filesystem. * Unicode internally - so you don't have to be. {sm;:-p} * Includes features for multiple translations of sites. * Built-in gallery creator plugin. * The basic system is very easy to use. * Lots of powerful (optional) features. The content can be stored as HTML, or in reST format; in which case the HTML will be generated using docutils. **rest2web** inserts each page into a template, and automatically creates index pages for sections, and navigation links. From bignose+hates-spam at benfinney.id.au Mon Nov 14 22:16:04 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Nov 2005 14:16:04 +1100 (EST) Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> Message-ID: Steven D'Aprano wrote: > On Mon, 14 Nov 2005 17:15:04 +0100, Pierre Barbier de Reuille wrote: > > The key point that, I think, you misunderstand is that symbols are > > not *variables* they are *values*. > > Python doesn't have variables. It has names and objects. That seems to be what Pierre wants to change. What he hasn't yet made clear is what benefit this brings, over simply using existing basic types (with as much intrinsic meaning -- i.e. none -- as the new object he's proposing). -- \ "I cannot conceive that anybody will require multiplications at | `\ the rate of 40,000 or even 4,000 per hour ..." -- F. H. Wales | _o__) (1936) | Ben Finney From martin at v.loewis.de Thu Nov 24 17:36:38 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Nov 2005 23:36:38 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <86veyhx5fb.fsf@bhuda.mired.org> References: <43850a7a$0$8074$9b622d9e@news.freenet.de> <868xvex8d6.fsf@bhuda.mired.org> <86veyhx5fb.fsf@bhuda.mired.org> Message-ID: <43864076.8050603@v.loewis.de> Mike Meyer wrote: >>I trusted the doco which defines a set as "an unordered collection of >>immutable values" (http://docs.python.org/lib/types-set.html). > > > If the hash changes, you've screwed up the set. What it really should > say is "collection of objects with fixed hashes", or words to that > effect. Do you want to file a PR on this? It's more than that: you really mean "hashable values", where "hashable" does not just imply that the hash value is fixed, but also that the equal objects hash same. Regards, Martin From debacle at debian.org Fri Nov 11 11:32:37 2005 From: debacle at debian.org (W. Borgert) Date: Fri, 11 Nov 2005 17:32:37 +0100 Subject: Python-based Document Management System? Message-ID: <1131726757.4374c7a51cb7c@webmail.in-berlin.de> > If you search for CONTENT management system, there is > Plone: A user-friendly and powerful open source Content Management ... > http://plone.org/ No, I'm looking for a DMS, not a CMS. My impression from the Plone web page is, that it does not have DMS features. Cheers, WB From eight02645999 at yahoo.com Mon Nov 7 20:48:00 2005 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 7 Nov 2005 17:48:00 -0800 Subject: pls help me with strange result In-Reply-To: References: <1131353588.072795.320660@g14g2000cwa.googlegroups.com> Message-ID: <1131414480.068290.167000@g44g2000cwa.googlegroups.com> hi thanks for your advice. yes,the args parameter can be included. Yes , the syntax is valid. I tried and it works for the 2 tables. looks like sybase knows how to distinguish that 2 update statements..as separate ones. cheers From zach at in.tu-clausthal.de Fri Nov 18 09:34:36 2005 From: zach at in.tu-clausthal.de (Gabriel Zachmann) Date: Fri, 18 Nov 2005 15:34:36 +0100 Subject: different binding behavior In-Reply-To: References: Message-ID: > We've just had a HUGE thread arguing about this behaviour, just three or > five days ago. Let's not start it again. ok, could you please point me to it? > In a nutshell, the behaviour is because ints are immutable and can't be > changed in place, and lists are mutable and can be changed in place. > > Imagine that ints could be changed in place. Then you could do this: i don't see why there should be only one instance of Int with the value 0. But if all this has already been debated (and, apparently, my point didn't succeed), there is no need to discuss all this over again. In any case, thanks a lot for your response and summary. Best regards, Gabriel. -- /-----------------------------------------------------------------------\ | Any intelligent fool can make things bigger, more complex, | | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \-----------------------------------------------------------------------/ From matt.schinckel at gmail.com Wed Nov 9 17:51:16 2005 From: matt.schinckel at gmail.com (matt.schinckel at gmail.com) Date: 9 Nov 2005 14:51:16 -0800 Subject: which feature of python do you like most? References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> <042dne8P_Ys9y-zenZ2dnUVZ_sadnZ2d@powergate.ca> Message-ID: <1131576676.738956.232210@o13g2000cwo.googlegroups.com> >>>I have no idea why people are so facinating with python. > Hey, I'm fascinating even without python! >And so modest, too :-) People as good as us usually are. From tim.peters at gmail.com Sun Nov 6 21:57:18 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 6 Nov 2005 21:57:18 -0500 Subject: python gc performance in large apps In-Reply-To: <436BC7F2.7020902@u20.org> References: <43594BD5.7050104@u20.org> <436BC7F2.7020902@u20.org> Message-ID: <1f7befae0511061857l613240c8x64b5a24d7b2bdbba@mail.gmail.com> [Robby Dermody] > ... > -len(gc.get_objects()) will show linearly increasing counts over time > with the director (that match the curve of the director's memory usage > exactly), but with the harvester, the object count doesn't increase over > time (although memory usage does). This might mean that we are dealing > with two separate problems on each component.... You meant "at least two" <0.5 wink>. > uncollected object count growth on the director, and something else on > the harvester. ...OR the harvester may have an object count growth > problem as well, it might just be in a C module in a place not visible to > gc.get_objects() ? Note that gc.get_objects() only knows about container objects that elect to participate in cyclic gc. In particular, it doesn't know anything about "scalar" types, like strings or floats (or any other type that can't be involved in a cycle). For example, this little program grows about a megabyte per second on my box, but len(gc.get_objects()) never changes: """ import gc from random import choice letters = "abcdefghijklmnop" def build(n): return "".join(choice(letters) for dummy in range(n)) d = {} i = 0 while 1: d[build(10)] = build(5) i += 1 if i % 1000 == 0: print i, len(gc.get_objects()) """ To learn about non-gc-container-object growth, use a debug build and sys.getobjects() instead. This is described in SpecialBuilds.txt. sys.getobjects() tries to keep track of _all_ objects (but exists only in a debug build). From support at intercable.ru Mon Nov 21 02:21:40 2005 From: support at intercable.ru (Technical Support of Intercable Co) Date: Mon, 21 Nov 2005 10:21:40 +0300 Subject: about dictionary Message-ID: <43817584.70205@intercable.ru> >>> b=dict.fromkeys(a) From bokr at oz.net Tue Nov 22 16:13:28 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 21:13:28 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> <438301ef$0$29180$8fcfb975@news.wanadoo.fr> <1132674151.370320.100130@g44g2000cwa.googlegroups.com> Message-ID: <4383897d.489297222@news.oz.net> On 22 Nov 2005 07:42:31 -0800, "George Sakkis" wrote: >"Laurent Rahuel" wrote: > >> Hi, >> >> newList = zip(aList[::2], aList[1::2]) >> newList >> [('a', 1), ('b', 2), ('c', 3)] >> >> Regards, >> >> Laurent > >Or if aList can get very large and/or the conversion has to be >performed many times: > >from itertools import islice >newList = zip(islice(aList,0,None,2), islice(aList,1,None,2)) > Or, if you want to include fractional groups at the end >>> aList = ['a', 1, 'b', 2, 'c', 3] >>> from itertools import groupby >>> def grouper(n): ... def git(): ... while True: ... for _ in xrange(n): yield 0 ... for _ in xrange(n): yield 1 ... git = git() ... def grouper(_): return git.next() ... return grouper ... >>> [tuple(g) for _, g in groupby(aList, grouper(2))] [('a', 1), ('b', 2), ('c', 3)] >>> [tuple(g) for _, g in groupby(aList, grouper(3))] [('a', 1, 'b'), (2, 'c', 3)] >>> [tuple(g) for _, g in groupby(aList, grouper(4))] [('a', 1, 'b', 2), ('c', 3)] Regards, Bengt Richter From tim.vets at skynet.be Tue Nov 22 18:15:15 2005 From: tim.vets at skynet.be (tim) Date: Wed, 23 Nov 2005 00:15:15 +0100 Subject: hex string to hex value Message-ID: <4383A683.5020205@skynet.be> This is probably another newbie question...but... even after reading quite some messages like '..hex to decimal', 'creating a hex value' , I can't figure this out: If i do >>> m=66 >>> n=hex(m) >>> n '0x42' i cannot use n as value for a variable that takes hex values, because it throws: error: required argument is not an integer >>> int(n) gives me: Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 0x42 how do I convert '0x42' to 0x42 ? thanks! From juho.schultz at helsinki.fi Tue Nov 8 05:55:31 2005 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Tue, 08 Nov 2005 12:55:31 +0200 Subject: any python module to calculate sin, cos, arctan? In-Reply-To: References: Message-ID: Shi Mu wrote: > any python module to calculate sin, cos, arctan? math There are two versions of arctan: atan and atan2. atan2(y,x) does the quadrant selection you do not get from atan(y/x) From fairwinds at eastlink.ca Sat Nov 26 11:20:45 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Sat, 26 Nov 2005 12:20:45 -0400 Subject: Whitespace test after string.split In-Reply-To: Message-ID: <98DCBAE4-5E98-11DA-BC76-000A27B3B070@eastlink.ca> Hi Fredrik and Peter. Many thanks for this helpful advice :-) These are very nice solutions and much better than what I had been contemplating. Also thanks for heads up for changes with method. I am still using 2.3 but will move to 2.4 as soon as this is formally approved for use in Zope. Regards, David On Saturday, November 26, 2005, at 11:42 AM, Fredrik Lundh wrote: > Peter Otten wrote: > >>>>> [t.strip() for t in s.split(",") if t and not t.isspace()] >> ['alpha', 'gamma', 'delta'] > > footnote: this solution is faster than my filter version. > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From falcon3166 at hotmail.com Tue Nov 15 23:45:01 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 15 Nov 2005 21:45:01 -0700 Subject: Can anyone tell me if pygame and Tkinter can work together? In-Reply-To: <20051116034640.GA17342@unpythonic.net> Message-ID: Sounds good, I'll give it a try and see what happens, and report back about my results. Nathan Pinno, Owner/operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -----Original Message----- From: jepler at unpythonic.net [mailto:jepler at unpythonic.net] Sent: November 15, 2005 8:47 PM To: Nathan Pinno Cc: python-list at python.org Subject: Re: Can anyone tell me if pygame and Tkinter can work together? On Tue, Nov 15, 2005 at 06:33:40PM -0700, Nathan Pinno wrote: > Thanks. I was going to use TKInter to pop up a message box, then use > pygame to run the game and display the score on the playing surface. > Is this still possible (I'm using Python 2.4.1 and Pygame 1.7.0 on > WinXP with Service Pack 2)? This is more likely to work than the scenario I first considered, where both GUI libraries would be in use at the same time. With my understanding of how X works, and my knowledge of Tk, you'd probably be successful if what you want to do is first use GUI Library A, and then GUI Library B. This resolves the issue with XSetErrorHandler, for instance, because you'll be completely done with Library A at the time you call the initialization routines of Library B. It also resolves the event loop problem, because you never need to allow Libraries A and B to receive events during the same phase of the program. I don't know anything about Windows, and I haven't actually given this scenario a try on Linux either, so it's still all idle speculation on my part. Actual experimentation on your part wouldn't be that hard, though. Just write the simplest possible Tk program as a callable function 't()' and the simplest possible pygame program as a callable function 'p()', and then see what happens when you run them back to back: def t(): import Tkinter t = Tkinter.Tk() Tkinter.Button(t, command = t.destroy).pack() t.mainloop() def p(): likewise t() p() Jeff From dan at wolf.com Sat Nov 5 12:52:23 2005 From: dan at wolf.com (Dan M) Date: Sat, 05 Nov 2005 09:52:23 -0800 Subject: Using Which Version of Linux References: Message-ID: On Sat, 05 Nov 2005 04:26:38 -0600, blahman wrote: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. Personally I would recommend staying away from Fedora unless you have a friend who is well-versed in it and willing to help. I like the distributin ok (I run it on the laptop I'm writing this from) but it uses RPMs for package distribution, and the rpm tools don't know how to automatically downloaded dependencies like yum or apt do. Because of that I have to say that the RPM package tools suck quite badly. Debian and SUSE are both pretty good choices. From dan at wolf.com Wed Nov 30 18:47:23 2005 From: dan at wolf.com (Dan M) Date: Wed, 30 Nov 2005 15:47:23 -0800 Subject: how to handle two forms in cgi? References: <1133390777.768717.299070@z14g2000cwz.googlegroups.com> Message-ID: > My question is: How let these two form works together? I try to use > two codes for these two forms, e.g. Login.py for login form and > search.py for search form. But when user input data in search form and > click its submit button, it just comes back to login form. Second form > doesn't work. > > Any help is appriciated! It sounds like the "action" attribute in the 2nd form's
tag is not pointing to search.py. From roy at panix.com Sun Nov 27 09:06:25 2005 From: roy at panix.com (Roy Smith) Date: Sun, 27 Nov 2005 09:06:25 -0500 Subject: Estimating memory use? Message-ID: I've got a large text processing task to attack (it's actually a genomics task; matching DNA probes against bacterial genomes). I've got roughly 200,000 probes, each of which is a 25 character long text string. My first thought is to compile these into 200,000 regexes, but before I launch into that, I want to do a back of the envelope guess as to how much memory that will take. Is there any easy way to find out how much memory a Python object takes? If there was, it would be simple to compile a random small collection of these patterns (say, 100 of them), and add up the sizes of the resulting regex objects to get a rough idea of how much memory I'll need. I realize I could just compile them all and watch the size of the Python process grow, but that seems somewhat brute force. From irmen.NOSPAM at xs4all.nl Mon Nov 21 17:51:52 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 21 Nov 2005 23:51:52 +0100 Subject: Aproximative string matching In-Reply-To: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> References: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> Message-ID: <438250bf$0$11067$e4fe514c@news.xs4all.nl> javuchi wrote: > I'm searching for a library which makes aproximative string matching, > for example, searching in a dictionary the word "motorcycle", but > returns similar strings like "motorcicle". > > Is there such a library? > Perhaps the get_close_matches function that is presentt in the standard library (in the difflib module) could be useful ?" --Irmen From bignose+hates-spam at benfinney.id.au Mon Nov 21 00:34:39 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 21 Nov 2005 16:34:39 +1100 (EST) Subject: Why are there no ordered dictionaries? References: <43814eaa.343166777@news.oz.net> <1132549972.254320.287490@g44g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > [sort by] some other metadata that is not present in the data. > [...] > Of course, you may say, just put another column that represent > this(some reporting programs I have seen do it this way) and that is > an option but not the only option. It's a pretty good option, and very commonly used. It's known as the "Schwartzian transform", or more descriptively, the "Decorate, Sort, Undecorate" pattern. -- \ "Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again." -- Franklin P. | _o__) Jones | Ben Finney From cjw at sympatico.ca Sat Nov 12 10:50:44 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 12 Nov 2005 10:50:44 -0500 Subject: tutorial example In-Reply-To: References: <20051112015026.74881.qmail@web35903.mail.mud.yahoo.com> Message-ID: <4bodf.24429$1L3.1061302@news20.bellglobal.com> Ruben Charles wrote: > That is the diference between a method and a function. > A method do something and a function return something. > This is not quite correct. The difference between a method and a function is that the method is associated with a type or class object, a function is not. A method can be bound to a particular instance of an object or it can be unbound. In the latter case the first argument of the method call should be an instance of the type or class object. However, there is no builtin check to ensure that the first argument is in fact an instance. Please see the little example below. Colin W. # areaToy.py class Point(object): def __init__(self, x, y): self.x= x self.y= y class Area(object): def __init__(self, *pts): ''' pts is a list of points describing the enclosing polygon, in clockwise order, instances of Point. ''' self.pts= pts[0] def size(self): nPts= len(self.pts) if nPts < 3: return 0 elif nPts == 3: return 0.5 # replace this with triangle area calc else: pts= self.pts return Area(pts[0:2] + [pts[-1]]).size() + \ Area(pts[1:]).size() pts= [Point(*pt) for pt in [(0, 1), (1, 1), (1, 0), (0, 0)]] area= Area(pts) size= area.size() print 'points:', pts print 'size:', size print 'Area.size:', Area.size print 'area.size:', area.size > Example: > > def psum(n, m): > print (n + m) > > def rsum(n, m): > return (n +m) > > Then try this... > > > >>>> psum(2, 3) > > >>>>a = psum(2, 3) > > >>>>a > > >>>>a = rsum(2, 3) > > >>>>a > > > You see it? From steve at REMOVETHIScyber.com.au Sat Nov 19 20:24:22 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 20 Nov 2005 12:24:22 +1100 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: On Sat, 19 Nov 2005 13:08:57 -0500, Peter Hansen wrote: > Umm... in other words, "the underscore is under-used so let's assign > some arbitrary meaning to it" (to make the language more like Perl > perhaps?). +1 I *really* don't like the idea of allowing underscores in numeric literals. Firstly, for aesthetic reasons: I think 123_456 is seriously ugly. Secondly, for pragmatic reasons, I think it is too easy to mistype as 123-456. I know that Python can't protect you from typing 9-1 instead of 901, but why add special syntax that makes that sort of error MORE common?) > Or maybe one should instead interpret this as "numeric literals need > more bells and whistles, and I don't care which of these two we add, but > we have to do *something*!". :-) -1 That's a tad unfair. Dealing with numeric literals with lots of digits is a real (if not earth-shattering) human interface problem: it is hard for people to parse long numeric strings. In the wider world outside of IT, people deal with long numeric digits by grouping. This is *exceedingly* common: mathematicians do it, economists do it, everybody who handles long numeric literals does it *except* computer language designers. Depending on personal preference and context, we use any of comma, period, dash or space as a separator. Underscore is never used. Of these, the comma clashes with tuples, the period opens a rather large can of worms vis-a-vis internationalisation, and the dash clashes with the minus sign. Allowing spaces to group digits is subtle but effective, doesn't clash with other syntax, and is analogous to string concatenation. I don't believe it is either practical or desirable for a computer language to accept every conceivable digit separator in literals. If you need full support for internationalised numbers, that should go into a function. But the question of including a digit separator for numeric literals does solve a real problem, it isn't just meaningless bells and whistles. Likewise, base conversion into arbitrary bases is not, in my opinion, common enough a task that support for it needs to be built into the syntax for literals. If somebody cares enough about it, write a module to handle it and try to get it included with the Python standard modules. -- Steven. From levicc00123 at gmail.com Wed Nov 2 13:21:27 2005 From: levicc00123 at gmail.com (Levi Campbell) Date: 2 Nov 2005 10:21:27 -0800 Subject: reading internet data to generate random numbers. Message-ID: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> Hi, I'm working on a random number generator using the internet as a way to gather entropy, I have two questions. 1. is there a way to capture the internet stream? 2. how would I skip every 2nd, 3rd, or 4th byte to protect privacy? From apardon at forel.vub.ac.be Mon Nov 7 03:28:49 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 08:28:49 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131026455.722847.153180@g14g2000cwa.googlegroups.com> Message-ID: Op 2005-11-04, Christopher Subich schreef : > Antoon Pardon wrote: >> Well I wonder. Would the following code be considered a name binding >> operation: >> >> b.a = 5 > > Try it, it's not. > > Python 2.2.3 (#1, Nov 12 2004, 13:02:04) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-42)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> a > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'a' is not defined > >>> b = object() > >>> b.a > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'a' > > Once it's attached to an object, it's an attribute, not a base name. So? It is still a name and it gets bound to an object. Sure the name is bound within a specific namespace but that is IMO a detail. > unified for Py3k, but in cases like this the distinction is important. But part of this dicussion is about the sanity of making these kind of distinctions. Since they apparantly plan to get rid of them in Py3k, I guess I'm not the only one questioning that. -- Antoon Pardon From riplin at Azonic.co.nz Sat Nov 19 16:31:00 2005 From: riplin at Azonic.co.nz (riplin at Azonic.co.nz) Date: 19 Nov 2005 13:31:00 -0800 Subject: HTML generation vs PSP vs Templating Engines In-Reply-To: <1132225003.654019.309170@z14g2000cwz.googlegroups.com> References: <1132158690.299954.90920@g14g2000cwa.googlegroups.com> <1132225003.654019.309170@z14g2000cwz.googlegroups.com> Message-ID: <1132435860.231522.29450@g14g2000cwa.googlegroups.com> > No templates, no python-like or special languages, only pure and simple python. > You can embedd python into html or, if it better suits your programming > style, you can embed html into python. Why don't you give it a try? I dislike embedding code or html in each other, apart from the 'impurity' of mixing code and user interface it makes them inseparable. Using templates means that the code can work with different templates, and this should be seamless, it also means that different code can be used with the templates, for example if different languages are used. The main advantage, for me, is that different outputs formats can be created without changing the code. If the user wants a set of data in a table then the html template is used, if they want a csv file of the data, that is just a different template name. A printed report: same code just a different template name. XML, simple text, postscript, EDIFACT file, all done with same code, different template. Just arrange for the name of the template file to be a parameter on the URL and the various outputs can be selected by the user. I did, however, write my own templating module, they are quite easy to do. From __peter__ at web.de Thu Nov 10 10:42:22 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Nov 2005 16:42:22 +0100 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> Message-ID: Antoon Pardon wrote: > Write somekind of property so that if you manipulate a.x it would > manipulate data[-1] Like that? >>> def make_prp(index): ... def get(self): return self[index] ... def set(self, value): self[index] = value ... return property(get, set) ... >>> class List(list): ... first = make_prp(0) ... last = make_prp(-1) ... >>> items = List([1,2,3]) >>> items.first 1 >>> items.last = 42 >>> items [1, 2, 42] However, that's customizing attribute access, not name binding. Peter From jbenson at sextans.lowell.edu Tue Nov 1 18:46:21 2005 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Tue, 1 Nov 2005 16:46:21 -0700 (MST) Subject: WTF? In-Reply-To: <200511011409.28683.jstroud@mbi.ucla.edu> Message-ID: On Tue, 1 Nov 2005, James Stroud wrote: > Why do my posts get held for suspcious headers and troll Xha Lee gets to post > all sorts of profanity and ranting without any problem? > I like many others have had the same experience. I recently choose to respond to one of Xha Lee's post and my Re (to the same subject line) post was bounced. I inquired to the Python-list-owner. Here was the response: ->Python.org uses several techniques to filter out spam. The one that ->affected you was Spambayes (check http://www.spambayes.org for more ->information). This uses known spam and non-spam (ham) messages and ->statistical methods to determine whether a given message is likely spam ->or ham, or whether it can't tell. If it can't tell, it adds a header to ->the message which triggers the next step in the filtering chain to hold ->the message for manual review. This is what happened to your message. So maybe we have answered the question of how the blankty blank with all the f this and f that does Xha Lee's posts get through. I postulate that he uses a script (written in mathematica of course...humm...wonder why he never includes the mathematica list in his cross posts) that randomly generates his subject line from his favorite topics. He does this till he sees the post appear. Jim From grflanagan at yahoo.co.uk Sat Nov 19 12:34:31 2005 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 19 Nov 2005 09:34:31 -0800 Subject: Is Python weak on the web side? References: Message-ID: <1132421671.432999.221730@z14g2000cwz.googlegroups.com> Tony wrote: > If I'd like to learn Python for web-development, what are the options > available? > > Thanks. tony Nov 18th: http://groups.google.co.uk/group/comp.lang.python/browse_frm/thread/c23b12dc0edf8af0/19f859dc43c77ac1#19f859dc43c77ac1 Gerard From aisaac0 at verizon.net Wed Nov 23 11:38:24 2005 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 23 Nov 2005 16:38:24 GMT Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> Message-ID: <4W0hf.11$id.3@trnddc04> "Michael Spencer" wrote in message news:mailman.1054.1132707811.18701.python-> This can be written more concisely as a generator: > > >>> import operator > >>> def ireduce(func, iterable, init): > ... for i in iterable: > ... init = func(init, i) > ... yield init OK, this might do it. But is a generator "better"? (I assume accuracy is the same, so what about speed?) def ireduce(func, iterable, init=None): if not init: iterable = iter(iterable) init = iterable.next() yield init elif not iterable: yield init for item in iterable: init = func(init, item) yield init Alan Isaac From fredrik at pythonware.com Tue Nov 22 08:03:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Nov 2005 14:03:32 +0100 Subject: sort in the list References: <1d987df30511220356r95126bbvcc09328df4f681e@mail.gmail.com> Message-ID: "Shi Mu" wrote: >I use Python 2.3 to run the following code: >>>> a=[[1,2],[4,8],[0,3]] >>>> a.sort() >>>> a > [[0, 3], [1, 2], [4, 8]] >>>> > I wonder whether the sort function automatically consider the first > element in the list of list as the sorting criteria or it just happens > to be? the documentation has the answer: http://docs.python.org/ref/comparisons.html "Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length. If not equal, the sequences are ordered the same as their first differing elements." From bonono at gmail.com Tue Nov 22 22:15:42 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 19:15:42 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> Message-ID: <1132715742.672265.259740@o13g2000cwo.googlegroups.com> Alex Martelli wrote: > However, since Christoph himself just misclassified C++'s std::map as > "ordered" (it would be "sorted" in this new terminology he's now > introducing), it seems obvious that the terminological confusion is > rife. Many requests and offers in the past for "ordered dictionaries" > (e.g. on this group) were also "sorted", NOT "ordered", in this new > terminology. > > Maybe it would therefore be clearer to have the name of the new > container reflect this, with a specific mention of *insertion* order... > rather than just call it "ordered" and risk probable confusion. Um, what would be the definition of "sorted" and "ordered", before we can go on ? From john.lehmann at gmail.com Sat Nov 19 11:24:20 2005 From: john.lehmann at gmail.com (john.lehmann at gmail.com) Date: 19 Nov 2005 08:24:20 -0800 Subject: Problems returning/attaching cookies Message-ID: <1132417459.990824.232590@g49g2000cwa.googlegroups.com> Attacked is a piece of code which first hits the login page successfully and receives back login cookies. But then when I attempt to hit a page which is restricted to logged in users only, I fail. That seems to be because I am not successfully re-attaching the cookies to the header portion of the this request. I have tried 2 methods which should both work I think. The first was to use install_opener to attach the cookie handler back to urlopen. The second method was to use the cookiehandler method add_cookie_header. But in both cases, before sending out the 2nd request, it seems to have empty headers -- which indicates to me that the necessary cookies have not been attacked. I also tryed messing with the policy quite a bit, thinking that might be causing the cookies not to be returned. First I used the default, then set some flags on the default, then even overrode methods on the default to make it as lenient as possible. This had no apparent effect. Thanks a lot! Below I have pasted the most relevant code section, as well as my full code file. Apologies for all the comments, but I wanted to show what I had tried. ----------------- RELEVANT CODE (snipped from full code) # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE the_url = "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp" req = urllib2.Request(the_url) #print "headers:", req.headers #cj.add_cookie_header(req) # EXPECT THESE HEADERS TO BE NON-EMPTY - BUT THEY ARE EMPTY, # NO COOKIES RETURNED? print "headers:", req.headers # THIS OPEN FAILS - I GET - "NEED TO LOGIN" PAGE #handle = opener.open(req) handle = urllib2.urlopen(req) the_page = handle.read() ----------------- FULL CODE #!/usr/bin/python import urllib import urllib2 import re import os from cookielib import * class MyCookiePolicy(DefaultCookiePolicy): def __init__(self): DefaultCookiePolicy.__init__(self, rfc2965=True, hide_cookie2=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal) def set_ok(self, cookie, request): return True def return_ok(self, cookie, request): return True def domain_return_ok(self, cookie, request): return True def path_return_ok(self, cookie, request): return True the_url = 'http://www.dpreview.com/forums/login_post.asp' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = { 'email' : '****', 'password' : '****', #"remember" : "checked", # <- create permanent cookie 'jump' : "/forums/" } # also "remember" : "remember" # INITIAL REQUEST WITH USER INFO headers = { 'User-Agent' : user_agent } data = urllib.urlencode(values) req = urllib2.Request(the_url, data, headers) # COOKIE POLICY # tried using several configurations of the default cookie policy #policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal) # tried using my own custom cookie policy #policy = MyCookiePolicy() policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False) # CREATE COOKIE JAR WITH POLICY cj = MozillaCookieJar() cj.set_policy(policy) # CREATE OPENER, AND OPEN PAGE opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) #handle = opener.open(req) handle = urllib2.urlopen(req) the_page = handle.read() # SHOW COOKIES COLLECTED - LOOKS GOOD HERE for c in cj: print "COOKIE:", c print "URL:", handle.geturl() print "INFO:", handle.info() #DEMONSTRATE WE'RE LOGGED IN for line in the_page.split('\n'): line = line.strip() if re.search("Welcome to the", line): print "MESSAGE:", line # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE # - tried using the install_opener above # - tried using add_cookie_header # - either way, can't seem to get cookies in the header of this request the_url = "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp" req = urllib2.Request(the_url) #print "headers:", req.headers #cj.add_cookie_header(req) # EXPECT THESE HEADERS TO BE NON-EMPTY print "headers:", req.headers #handle = opener.open(req) handle = urllib2.urlopen(req) the_page = handle.read() # THIS ALSO PROVES LOGIN-STATE WAS LOST for line in the_page.split('\n'): line = line.strip() if re.search("To access", line): print "MESSAGE:", line print "URL:", handle.geturl() print "INFO:", handle.info() From bokr at oz.net Tue Nov 22 13:32:18 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 18:32:18 GMT Subject: Why are there no ordered dictionaries? References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <438258f2.411334718@news.oz.net> Message-ID: <4383635b.479535916@news.oz.net> On Tue, 22 Nov 2005 10:26:22 +0100, Christoph Zwerschke wrote: >Bengt Richter wrote: > > > d = OrderedDict(); d[1]='one'; d[2]='two' =>> list(d) => [1, 2] > > ok, now we do d[1]='ein' and what is the order? list(d) => [2, 1] ?? > > Or do replacements not count as "insertions"? > >If you simply set a value for a key that already exists, the order >should not be changed. I think this is intuitive. > >> Or maybe you want to permit append and NOT prevent > > [('a',1), ('a':2)] and maybe d['a'] => [1, 2] ??? > >You could ask the same question about dict. I think that is not an >option. Why should you want odict behave different than dict? Well, it was beginning to remind of RDB with possible non-unique keys, where a select can get you multiple records back. > >I still believe that the concept of an "ordered dictionary" ("behave >like dict, only keep the order of the keys") is intuitive and doesn't >give you so much scope for ambiguity. But probably I need to work on an >implementation to become more clear about possible hidden subtleties. > Does that mean that the Larosa/Foord odict.py implementation in PyPI does not do what you want? Regards, Bengt Richter From rurpy at yahoo.com Wed Nov 23 14:57:05 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 23 Nov 2005 11:57:05 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132756197.635519.114180@g47g2000cwa.googlegroups.com> Message-ID: <1132775825.182959.314090@g43g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Daniel Crespo wrote: > > > Let me tell you something: I'm not a one-liner coder, but sometimes It > > is necesary. > > For example: > > I need to translate data from a DataField to Another. > > > > def Evaluate(condition,truepart,falsepart): > > if condition: > > return truepart > > else: > > return falsepart > > > > dOldDataFields = {} > > dNewDataFields = {} > > > > dNewDataFields = { > > 'CODE': dOldDataFields['CODEDATA'], > > 'DATE': dOldDataFields['DATE'], > > 'CONTACT': Evaluate(dOldDataFields['CONTACTTYPE']==2, > > dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT']) > > } > > > > With this, I created a new dic very easy, saving in > > dNewDataFields['CONTACT'] the value of dOldDataFields['FIRSTCONTACT'] > > or the value of dOldDataFields['SECONDCONTACT'] depending on > > dOldDataFields['CONTACTTYPE']. How you do this in a practic way without > > the use of one-line code? It is needed! You can't avoid it! > > if you use less verbose names, you can do the same thing in less than half > the number of characters, without a single oneliner: > > def convert(old): > > new = dict( > CODE=old['CODEDATA'], > DATE=old['DATE'] > ) > > if old['CONTACTTYPE'] == 2: > new['CONTACT'] = old['FIRSTCONTACT'] > else: > new['CONTACT'] = old['SECONDCONTACT'] > > return new I don't find your code any more readable than the OP's equivalent code: def convert(old): new = { CODE: old['CODEDATA'], DATE: old['DATE'], CONTACT: old['FIRSTCONTACT'] \ if old['CONTACTTYPE'] == 2 \ else old['OLDDCONTACT'] } return new The OPs code make one pass through the dict, your's makes two. I do not know what effect (if any) that has in the case of a very large dict. From aahz at pythoncraft.com Fri Nov 25 12:37:23 2005 From: aahz at pythoncraft.com (Aahz) Date: 25 Nov 2005 09:37:23 -0800 Subject: books: Dive into Python vs Beginning Python References: Message-ID: In article , Franz Mueller wrote: > >which of the following books would you recommend: >"Dive into Python" or "Beginning Python: From Novice to Professional"? > >I'm an experienced C++-programmer who wants to take a look at Python. Another option: just use the on-line tutorial at python.org -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair From robert.kern at gmail.com Sun Nov 20 23:48:29 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 20 Nov 2005 20:48:29 -0800 Subject: Any royal road to Bezier curves...? In-Reply-To: References: Message-ID: Warren Francis wrote: > I'm fairly new to Python (2-3 months) and I'm trying to figure out a simple > way to implement Bezier curves... So far I've tried the following: > > http://runten.tripod.com/NURBS/ > ...which won't work because the only compiled binaries are for Windows 2000, > python 2.1. I'm on Windows XP (for now), using Python 2.4. I downloaded > the source distribution, but the header files aren't included, so I'm not > sure how to compile it. > > It appears there's some bezier functionality in the python that comes > Blender... but I'm not savvy enough yet to try and extract whatever makes > beziers work there, to make it work in my general-purpose Python programs. > > Basically, I'd like to specify a curved path of an object through space. 3D > space would be wonderful, but I could jimmy-rig something if I could just > get 2D... There's some 2D code (which could be trivially adapted to 3D) in PIDDLE/Sping. In the latest Sping download, look in the file pid.py at the Canvas.curvePoints() method. http://piddle.sourceforge.net/ > Are bezier curves really what I want after all? I dunno. It depends on how much flexibility you need. -- 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 mclaugb at nospm.yahoo.com Tue Nov 8 11:59:55 2005 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Tue, 8 Nov 2005 16:59:55 -0000 Subject: debugger Message-ID: Is there a decent debugger to use with IDL? I have briefly about "PDB" but this looks pretty limited in features and difficult to use. Any suggestions? Bryan From ejatwellkeepercom Thu Nov 10 17:11:52 2005 From: ejatwellkeepercom (ej) Date: Thu, 10 Nov 2005 15:11:52 -0700 Subject: exceptions, internals (introspection?) References: <4373ae4a$1@nntp.zianet.com> <7x64r04473.fsf@ruckus.brouhaha.com> Message-ID: <4373c62d$1@nntp.zianet.com> "Paul Rubin" wrote in message news:7x64r04473.fsf at ruckus.brouhaha.com... > It's messy. Look at sys.exc_info() and go from there. Yeah, I think I am starting to see what you mean... #! /usr/local/bin/python import sys try: {}['foo'] except Exception, x: print "class of x =", x.__class__ print "type(x) =", type(x) print "dir(x) =", dir(x) print (type_, value_, traceback_) = sys.exc_info() print "type_ =", type_ print "value_ =", value_ print "traceback_ =", traceback_ for key in dir(traceback_): print "traceback_.%s =" % key, eval("traceback_.%s" % key) print "dir(frame) = ", dir(traceback_.tb_frame) ej at sand:~/src/python/exceptions> foo class of x = exceptions.KeyError type(x) = dir(x) = ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] type_ = exceptions.KeyError value_ = 'foo' traceback_ = traceback_.tb_frame = traceback_.tb_lasti = 18 traceback_.tb_lineno = 6 traceback_.tb_next = None dir(frame) = ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace'] But at least that is something to go on. Thanks for your reply! -ej From gblais at cox.net Thu Nov 10 20:18:18 2005 From: gblais at cox.net (gblais at cox.net) Date: Fri, 11 Nov 2005 01:18:18 GMT Subject: Stopping Execution References: Message-ID: surely you mean sys.exit() Gerry From falcon3166 at hotmail.com Fri Nov 18 20:13:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 18 Nov 2005 18:13:36 -0700 Subject: Is there a way to create a button in either pygame or livewires? Message-ID: <437e7373$0$20261$88260bb3@news.atlantisnews.com> Hey all, Is there a way to create a button in either pygame or livewires, that is able to be clicked and when clicked sends a command to restart the program? Thanks, Nathan Pinno -- For great sites go to: http://www.the-web-surfers-store.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty -- ............................................................. > Posted thru AtlantisNews - Explore EVERY Newsgroup < > http://www.AtlantisNews.com -- Lightning Fast!!! < > Access the Most Content * No Limits * Best Service < From chris at kateandchris.net Wed Nov 30 13:06:16 2005 From: chris at kateandchris.net (Chris Lambacher) Date: Wed, 30 Nov 2005 13:06:16 -0500 Subject: improving pypi / setuptools In-Reply-To: References: <1133321761.109769.87280@f14g2000cwb.googlegroups.com> Message-ID: <20051130180616.GA12100@kateandchris.net> On Wed, Nov 30, 2005 at 11:49:14AM +0100, Fredrik Lundh wrote: > Alia Khouri wrote: > > > What ideas do people out there have for making the installation of > > python module more reliable? > > judging from the support load it's causing me these days, setuptools is a > piece of utter crap. if you want to make things reliable, don't use it. setuptools is still alpha. Give it another 6months to a year and you will wonder how we ever got along without it. > > (if the various "rails" cloners want people to use their stuff, it would be a > lot better is they shipped complete and well-tested source code kits, and > left the packaging to the huge crowd of nice, friendly, and competent > downstream packagers that exist for all major platforms these days. the Which downstream packager exists for Windows, or is Windows not a major platform anymore? Besides many useful modules are not important enough to be picked up by packagers for some distributions. For instance, Gentoo does not have RuleDispatch. > downstream folks know what they're doing, and the tools they're using > happens to work. both for the maintainers and for the users.) > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From mwm at mired.org Thu Nov 24 12:49:23 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 12:49:23 -0500 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> Message-ID: <86zmnuvsv0.fsf@bhuda.mired.org> "Martin P. Hellwig" writes: >> "Martin P. Hellwig" writes: >>> If the non-techie is still interested, I'll rave on about that I >>> understand why GPL is a good way to ensure availability of IP >>> especially if the software is a collaborated effort in the academic >>> scene. >> Your comment about the GPL "ensuring availability" would imply that >> other-licensed software has a tendency to become unavailable. Do you >> know of any examples of such? > Yes, it happens on a regular bases that *BSD's are ported to a > particular platform or devices and that the necessary changes to make > it work that way are not released back (eg Ironport mail > systems). Other examples are extensions of other software to fill a > particular need that are kept close for a binary only sale (eg Mammoth > PostgreSQL + Replication). Is that software really unavailable, or just unavailable for free? If the latter, then it's not unavailabe. If the former, the it didn't become unavailable, as it was never available in the first place. In the latter case, you could also use those examples to similarly "prove" that non-GPL'ed software is a "good way to ensure the availability of IP", as the developers of those IPs obviously felt that the ability to restrict distribution in some way was needed to make the effort of developing and distributing the software in the first place worthwhile. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From twic at urchin.earth.li Fri Nov 25 21:48:23 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 26 Nov 2005 02:48:23 +0000 Subject: icmp - should this go in itertools? Message-ID: Hi all, This is a little function to compare two iterators: def icmp(a, b): for xa in a: try: xb = b.next() d = cmp(xa, xb) if (d != 0): return d except StopIteration: return 1 try: b.next() return -1 except StopIteration: return 0 It's modelled after the way cmp treats lists - if a and b are lists, icmp(iter(a), iter(b)) should always be the same as cmp(a, b). Is this any good? Would it be any use? Should this be added to itertools? tom -- I content myself with the Speculative part [...], I care not for the Practick. I seldom bring any thing to use, 'tis not my way. Knowledge is my ultimate end. -- Sir Nicholas Gimcrack From dwahler at gmail.com Wed Nov 2 14:43:33 2005 From: dwahler at gmail.com (David Wahler) Date: 2 Nov 2005 11:43:33 -0800 Subject: question about urllib and parsing a page References: <1130957593.322210.185450@o13g2000cwo.googlegroups.com> Message-ID: <1130960613.557180.6800@g43g2000cwa.googlegroups.com> nephish at xit.net wrote: > hey there, > i am using beautiful soup to parse a few pages (screen scraping) > easy stuff. > the issue i am having is with one particular web page that uses a > javascript to display some numbers in tables. > > now if i open the file in mozilla and "save as" i get the numbers in > the source. cool. but i click on the "view source" or download the url > with urlretrieve, i get the source, but not the numbers. > > is there a way around this ? > > thanks If the Javascript is automatically generated by the server with the numbers in a known location, you can use a regular expression to extract them. For example, if there's something in the code like: var numbersToDisplay = [123,456,789]; Then you could use: (warning, this is not fully tested): import re js_source = "... the source inside the -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From haraldarminmassa at gmail.com Fri Nov 18 04:53:22 2005 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 18 Nov 2005 01:53:22 -0800 Subject: Announce: PythonD 2.4.2 r 1.0 for DJGPP/DOS/Windows In-Reply-To: <3u5jihFvengjU1@individual.net> References: <1132302854.765971.176360@z14g2000cwz.googlegroups.com> <3u5jihFvengjU1@individual.net> Message-ID: <1132307601.985186.224650@g49g2000cwa.googlegroups.com> Claudio, maybe it's because PythonD is running within DOS? (which, for archaelogical completeness, is an ancient operating system) Harald From deets at nospam.web.de Sun Nov 13 08:31:33 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 13 Nov 2005 14:31:33 +0100 Subject: about python ide In-Reply-To: References: Message-ID: <3tothjFtvng7U1@uni-berlin.de> ?? wrote: > i am use python2.4.2 on my gentoo linux system > i want to find some ide of python > but i am using gtk2.8,wxPython has some bug on it.i cant emerge it correctly. > i want some ide use pygtk or other lib of python gui except wxpython(wxWidgets) Take astab at eric3. Uses Qt + PyQt Diez From Neil.Jin at gmail.com Wed Nov 2 06:55:07 2005 From: Neil.Jin at gmail.com (Neil.Jin at gmail.com) Date: 2 Nov 2005 03:55:07 -0800 Subject: How can I setup proxy of urllib2 properly Message-ID: <1130932507.050768.175920@g14g2000cwa.googlegroups.com> I got some source code form python's help document. the below: proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'}) proxy_auth_handler = urllib2.HTTPBasicAuthHandler() proxy_auth_handler.add_password('realm', 'host', 'username', 'password') ^^^^^^^ ^^^^^ opener = urllib2.build_opener(proxy_handler, proxy_auth_handler) # This time, rather than install the OpenerDirector, we use it directly: opener.open('http://www.example.com/login.html') I have only the username and password of proxy server. But I do not know what should I provide for the 'realm' and 'host' prameters of add_password function. for example, My proxy server is "www.myproxy.com" username is "user1" password is "pass1" how can I provide parameters for "add_password" function? From frithiof.jensen at die_spammer_die.ericsson.com Wed Nov 30 06:05:53 2005 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 30 Nov 2005 12:05:53 +0100 Subject: python speed References: Message-ID: "Krystian" wrote in message news:hhupo15bdg0tvnivtpu60907nanuose44r at 4ax.com... > Hi > are there any future perspectives for Python to be as fast as java? Sure, if/when Python becomes as water-logged with obtruse OO-layers as Java is now. Python is faster than Java. Because Python per design generally is a thin layer of glue poured over binary C modules, it does not take very many instructions before one hits the fastest speed that the platform can go at. I would test it, then worry about it. > i would like to use Python as a language for writing games. >From the speed requirement: Is that correspondance chess by any chance?? From bonono at gmail.com Tue Nov 8 23:18:44 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 8 Nov 2005 20:18:44 -0800 Subject: Newb ?? In-Reply-To: References: Message-ID: <1131509924.139654.279020@g14g2000cwa.googlegroups.com> I would rather to do the loop as : max_try = 5 for x in xrange(max_try): g = int(raw_input(["Take a guess","Take another guess"][x != 0])) if g == number: print "bingo, hit it in %i tries" % x + 1 break elif g < number: print "try higher" else: print "try lower" else: print "sorry, you lose, the number is %i" % number Chad Everett wrote: > import random > > print "\tWelcome to 'Guess my Number'!" > print "\nI'm Thinking of a Number between 1 and 100." > print "\nTry to Guess it in as few attempts as possible.\n" > > #Set the initial values > the_number = random.randrange(100) + 1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #Guessing Loop > > while (guess != the_number): > if (guess >the_number): > print "Lower..." > else: > print "Higher..." > guess = int(raw_input("Take another Guess:")) > tries +=1 > if tries == 5: > print "Sorry you lose." > print "The Correct Number was ", the_number > > > print "You guess correctly!!" > print "The number was:", the_number > print "You got it correct in", tries, "tries" > > raw_input("Press Enter to exit the program") From apardon at forel.vub.ac.be Fri Nov 4 05:38:30 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 10:38:30 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: Op 2005-11-04, Magnus Lycka schreef : > Antoon Pardon wrote: >>>Because b.a += 2 expands to b.a = b.a + 2. Why would you want b.a = >>> to correspond to b.__class__.a = ? >> >> >> That is an implemantation detail. The only answer that you are given >> means nothing more than: because it is implemented that way. > > Something that is written in the language reference is not > an implementation detail. Every implementation that aims to > be Python must follow this. It's a design decision. I have looked and didn't find it in the language reference. This is what I have found: An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. I think one could argue that in the case of b.a += 1 and a being a class variable that incrementing the class variable was a similar effect in this case. But I can be and maybe a more strict definition is available that I looked over. Do happen to know one? > Whether you like it or not, you will find out that the behaviour > of Python is largely based on an idea of an underlying structure. > A lot of the syntax is basically just convenient ways to access > this structure, and there is a strong tradition to avoid magic. Fine. I already wrote that if people think that changing this behaviour would cause more problems than it solved or that solving it would cause more problems than it is worth, I would have no problem with that. That doesn't change the fact that the current behaviour is on occasions awkward or whatever you want to call it. > The explicit use of self might be the most obvious example of that, > but you can find a lot of other things in Python that shows you > this, __dict__ for instance. > > I agree that the behaviour you are questioning isn't completely > unsurprising for someone who stumbles over it the first time, but > considering how things work in Python classes, where the class > scope is searched if a name isn't found in the instance scope > (self.__dict__), any other solution would involve more magic, and > be more surprising to someone who actually knows what is going on. It would be more suprising to someone depending on what is now going on. I also find that people underestimate the magic that is going on in python. But just because you are familiar with the magic, doesn't make it less magic. IMO python shows its history a little. > It's possible that a oldie like me, who started coding Python in > 1996 is just blind to the warts in Python by now, but no language > is perfect, and whatever design decisions you make, they will have > both positive and negative consequences. I completely agree. Personnaly I find python has withstood its changes remarkebly well and I find the design in general still very consistent despite the changes it underwent. > I frankly don't understand what you are after Antoon. Just to > vent your frustrations? If you want to use Python in an effective > way, try to learn how to use the language that actually exists. I'm after nothing particular. The only thing I'm frustrated about is the way in which some people seem willing to defend python just because it is python. If the only reaction I would have gotten would have been something like: Yeah that seems a bit awkward but fixing this would break more than it would cure, I would have left it as it is. > Asking questions in this forum is clearly a part of that, but > your confrontational style, and idea that everything that bothers > you is a language bug that needs to be fixed is not the most > constructive approach. I have rarely indicated I wanted things to be fixed. Sure I would like it if some things were different, but I recognize that there are more important things that needs to be resolved. Does that mean I shouldn't mention things that IMO could have been better or that I should only mention them in the softest of language that certainly can't be interpreted as emotional language. -- Antoon pardon From mwm at mired.org Mon Nov 28 20:20:50 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 28 Nov 2005 20:20:50 -0500 Subject: General question about Python design goals References: Message-ID: <86k6estfkd.fsf@bhuda.mired.org> Christoph Zwerschke writes: > A programming language is not a "work of art". If you are an artist, > you may break symmetry and introduce all kinds of unexpected > effects. Actually, as an artist, you purposfully want to provoke > astonishment. But if I am using a programming language or a user > interface, I don't want to be confronted with inconsistent > behavior. Here, the "principle of least astonishment" is much more > helpful (in my little mind's humble optionion). But a programming language (or UI) is not just a collection of syntax and and interfaces - it's an implementation. You need to keep in mind that "practicality beats purity". If following POLA makes the implementation an order of magnitude slower or larger, then you don't follow POLA - at least until you can do it without that cost. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From __peter__ at web.de Fri Nov 18 16:48:30 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Nov 2005 22:48:30 +0100 Subject: func(*params) References: Message-ID: David Duerrenmatt wrote: > For some reasons, I've to use Python 1.5.2 and am looking for a > workaround: > > In newer Python versions, I can call a function this way: > > func = some_function > func(*params) Use apply(func, params) Peter From aleax at mail.comcast.net Sun Nov 13 20:03:23 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 13 Nov 2005 17:03:23 -0800 Subject: gmpy/decimal interoperation Message-ID: <1h5z5pl.rbt4q91q4qw27N%aleax@mail.comcast.net> As things stand now (gmpy 1.01), an instance d of decimal.Decimal cannot transparently become an instance of any of gmpy.{mpz, mpq, mpf}, nor vice versa (the conversions are all possible, but a bit laborious, e.g. by explicitly going through string-forms). I'm thinking about possible ways to fix this, in whole or in part, but, before I spend more time on this, I was wondering if there's anybody else who'd be interested -- if so, maybe we can discuss which conversions should happen implicitly (e.g., if you try to sum a Decimal and an mpz, maybe the latter should implicitly become a Decimal, just like an int would, so that the result is a Decimal) and which ones should only happen on explicit request (e.g., gmpy.mpf(d) should produce an mpf instance, just as calling gmpy.mpf on an int instance would). Alex From bokr at oz.net Tue Nov 15 19:23:05 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 16 Nov 2005 00:23:05 GMT Subject: Parse file into array References: <1132004925.481923.47520@z14g2000cwz.googlegroups.com> Message-ID: <437a765a.591512830@news.oz.net> On 14 Nov 2005 13:48:45 -0800, "amfr" wrote: >I was wondering how i could parse the contents of a file into an array. > the file would look something like this: > >gif:image/gif >html:text/html >jpg:image/jpeg >... > >As you can see, it contains the mime type and the file extension >seperated by commas, 1 per line. I was wondering if it was possible to >create and array like this: > >(Pseudocode) >mimetypearray[gif] = "image/gif" >mimetypearray[html] = "text/html" >mimetypearray[jpg] = "image/jpeg" >... > >I come from a PHP backround where I know this is possible, but I am new >at Python. Please disregard this if it is a stupid question. > Pretty much anything is possible in Python, if you can conceive it well enough ;-) Assuming f is from f = open(yourfile), simulated with StringIO file object here, >>> from StringIO import StringIO >>> f = StringIO("""\ ... gif:image/gif ... html:text/html ... jpg:image/jpeg ... """) And assuming that there are no spaces around the ':' or in the two pieces, but maybe some optional whitespace at either end of a line and \n at the end (except maybe the last line), and no blank lines, you can get a dict mapping easily: >>> mimetypedict = dict(tuple(line.strip().split(':')) for line in f) This gives you: >>> mimetypedict {'gif': 'image/gif', 'html': 'text/html', 'jpg': 'image/jpeg'} Which you can access using the names as keys, e.g., >>> mimetypedict['gif'] 'image/gif' If you want to use bare names to access the info via an object, you can use the dict info to create a class or class instance and give it the named attributes, e.g. a class with the data as class variables is quick: >>> MTC = type('MTC',(), mimetypedict) >>> MTC.gif 'image/gif' >>> MTC.jpg 'image/jpeg' Or you could substitute the mimetypedict expression from above to make another one-liner ;-) Other ways of setting up your info are certainly possible, and may be more suitable, depending on how you intend to use the info. As mentioned, the mimetypes module may already have much of the data and/or functionality you want. Regards, Bengt Richter From simon.brunning at gmail.com Wed Nov 2 04:11:43 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 2 Nov 2005 09:11:43 +0000 Subject: Python and DevTrack? In-Reply-To: <1130871448.959281.105160@f14g2000cwb.googlegroups.com> References: <1130871448.959281.105160@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c60511020111r7b6d17fag@mail.gmail.com> On 1 Nov 2005 10:57:29 -0800, warpcat wrote: > I'm a python nubie, so be gental. I've been setting up functionality > by managing my Perforce clientspec with python (since it seems all of > P4's commands are avaliable at the prompt), and I'd love to get access > to DevTrack in the same way, but it's looking like it's off limits, UI > only. Does anyone have any experience with this? Much appreciated. I > have searched the posts, came up with nothing. For driving Windows GUIs, check out WATSUP. But be warned, it's a non-trivial exercise. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From jmdeschamps at gmail.com Thu Nov 3 12:33:54 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 3 Nov 2005 09:33:54 -0800 Subject: Can Anyone Help me on this In-Reply-To: References: Message-ID: <1131039234.706772.69660@g47g2000cwa.googlegroups.com> blah at blah.blah wrote: > i m trying to reverse the order in which the > strings are stored in list > > then pop it into another list > > what m i doin worng?? > > here's the code: > > list1 = [] > list2 = [] > list1.extend('123456789') > > print list1 > > for a in list1: > list2 = list1.pop() > > print list2 > -- > * Posted with NewsLeecher v3.0 Beta 7 > * http://www.newsleecher.com/?usenet well, mant things are happening, so many it's not clear to me what you're trying to do... BUT, considering your for statement, since you are poping elements out of list you are shortening it, so you are only getting as far as element '5' If what you want is a reversed copy, you could just append list1 elements to list2, and use the reverse function such as >>> ... >>> for i in list1: ... list2.append(i) ... >>> list2.reverse() >>> list1 ['1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> list2 ['9', '8', '7', '6', '5', '4', '3', '2', '1'] From tuvas21 at gmail.com Wed Nov 9 15:06:32 2005 From: tuvas21 at gmail.com (Tuvas) Date: 9 Nov 2005 12:06:32 -0800 Subject: Floating numbers and str In-Reply-To: <1131566584.712391.248200@o13g2000cwo.googlegroups.com> References: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> <1131566584.712391.248200@o13g2000cwo.googlegroups.com> Message-ID: <1131566792.341658.89590@g44g2000cwa.googlegroups.com> Wait, one more question. If the number is something like: 1.32042 It is like "1.32 stuff" I would like it's size to remain constant. Any way around this? From duncan.booth at invalid.invalid Thu Nov 24 03:49:36 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Nov 2005 08:49:36 GMT Subject: Why are there no ordered dictionaries? References: <1132533922.953694.251100@g43g2000cwa.googlegroups.com> <1h6c6t4.1hc5owk13rgcrhN%aleax@mail.comcast.net> <1h6dx5i.1l70utq155zpbsN%aleax@mail.comcast.net> <1h6f39h.n2wpx91c4cc2qN%aleax@mail.comcast.net> Message-ID: Christoph Zwerschke wrote: > Duncan Booth schrieb: >> In Javascript Object properties (often used as an associative array) >> are defined as unordered although as IE seems to always store them in >> the order of original insertion it wouldn't surprise me if there are >> a lot of websites depending on that behaviour. > > You're right with both. The ECMA language definition says object > properties are an unordered collection, but MSIE and probably other > browsers keep the order in which they were created. Of course one > should not rely on that. > Yes, the real fun bit is arrays. If you create an array using the 'new Array' or [ ... ] then a for..in loop might well trick you into thinking it is going to go through the elements in order, but if you assign to elements directly it breaks down: a = ['a', 'b', 'c']; a[4] = 'e'; a[3] = 'd'; for (var k in a) { alert(a[k]+'='+a[k]); } On IE this will go through elements in the order 0, 1, 2, 4, 3. Also, it is original order of insertion which matters, not the 'last in/last out' you might have expected. In other words it looks rather as though IE simply sets deleted properties to undefined (and skips them on iteration), it never really deletes a property, so anyone who tries to use a Javascript object as an associative array with lots of rapidly changing keys could be in for a nasty shock. From kent37 at tds.net Tue Nov 29 18:38:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 29 Nov 2005 18:38:24 -0500 Subject: Looking for good beginner's tutorial In-Reply-To: References: Message-ID: <438ce39e$1_1@newspeer2.tds.net> Roy Smith wrote: > My wife wants to learn Python. Can anybody suggest a good tutorial > for her to read? She's a PhD molecular biologist who is a pretty > advanced Unix user. She mucks about with Perl scripts doing things > like text processing and even some simple CGI scripts, but has no > formal programming training. http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From steve at holdenweb.com Thu Nov 24 03:23:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 08:23:06 +0000 Subject: return in loop for ? In-Reply-To: <1132812397.369787.214140@g47g2000cwa.googlegroups.com> References: <4384F705.31CEC951@valid.org><86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Steve Holden wrote: > > >>Yomgui: I am not a language lawyer, but I think you can feel safe >>returning from inside a loop. Just as a matter of interest, how else >>would you propose to implement the functionality Mike showed: >> >> >>>>>>def f(): >>> >>>... for i in range(20): >>>... if i > 10: return i >>>... >>> >> >>Python is supposed to cleanly express the programmer's intent. I can;t >>think of a cleaner way that Mike's - can you? > > Interestingly, I just saw a thread over at TurboGears(or is it this > group, I forgot) about this multiple return issue and there are people > who religiously believe that a function can have only one exit point. > > def f(): > r = None > for i in range(20): > if i > 10: > r = 10 > break > if r is None: something > else: return r > Well, I'm happy in this instance that practicality beats purity, since the above is not only ugly in the extreme it's also far harder to read. What are the claimed advantages for a single exit point? I'd have thought it was pretty obvious the eight-line version you gave is far more likely to contain errors than Mike's three-line version, wouldn't you agree? 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 devlai at gmail.com Thu Nov 10 20:23:17 2005 From: devlai at gmail.com (Devan L) Date: 10 Nov 2005 17:23:17 -0800 Subject: Command-line tool able to take multiple commands at one time? In-Reply-To: References: Message-ID: <1131672197.698115.284580@g43g2000cwa.googlegroups.com> Peter A. Schott wrote: > Per subject - I realize I can copy/paste a line at a time into an interactive > session when I'm trying to debug, but was wondering if there is any tool out > there that allows me to copy sections of working Python scripts to paste into my > interactive console and let those run so I don't have to copy line-by-line. > > Not sure if iPython would meet that criteria or not or even if such a beast > exists. It would be helpful for debugging some of my simpler, yet still lengthy > at times, scripts. > > Thanks in advance. > > -Pete Schott It's called IDLE (At least, the interactive session with it). Some people dislike IDLE, though. From jelleferinga at gmail.com Mon Nov 14 06:24:41 2005 From: jelleferinga at gmail.com (jelle) Date: 14 Nov 2005 03:24:41 -0800 Subject: SciPy python 2.4 wintel binaries In-Reply-To: References: <1131803968.993069.29660@f14g2000cwb.googlegroups.com> Message-ID: <1131967481.007598.158350@g44g2000cwa.googlegroups.com> Hi Peter, I'm aware of the Enthought distribution, which really is my preferred 2.3 Python distribution. Problem is that many programs I'm working on would require both 2.4 & SciPy What kind of puzzles me is that SciPy.core is available for wintel 2.4, is that an indication a full SciPy distribution is coming along? Cheers, -jelle From danb_83 at yahoo.com Wed Nov 2 18:24:45 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 2 Nov 2005 15:24:45 -0800 Subject: Most efficient way of storing 1024*1024 bits References: Message-ID: <1130973885.746466.208470@g44g2000cwa.googlegroups.com> Tor Erik S?nvisen wrote: > Hi > > I need a time and space efficient way of storing up to 6 million bits. The most space-efficient way of storing bits is to use the bitwise operators on an array of bytes: import array class BitList(object): def __init__(self, data=None): self._data = array.array('B') self._length = 0 if data is not None: self.extend(data) def __len__(self): return self._length def __getitem__(self, index): if index < 0: index += self._length if index < 0 or index >= self._length: raise IndexError('BitList index out of range') byte_index, bit_index = divmod(index, 8) return int(bool(self._data[byte_index] & (1 << bit_index))) def __setitem__(self, index, value): if index < 0: index += self._length if index < 0 or index >= self._length: raise IndexError('BitList index out of range') byte_index, bit_index = divmod(index, 8) byte = self._data[byte_index] bitmask = 1 << bit_index byte &= ~bitmask & 0xFF if value: byte |= bitmask self._data[byte_index] = byte def __repr__(self): return 'BitList([%s])' % ', '.join(str(bit) for bit in self) def append(self, value): if not self._length % 8: self._data.append(0) self._length += 1 self[-1] = value def extend(self, values): for v in values: self.append(v) > Time efficency is more important then space efficency In that case, you're better off simply using a list of bools. > as I'm going to do searches through the bit-set. What kind of searches? From strombrg at dcs.nac.uci.edu Mon Nov 7 15:29:05 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 07 Nov 2005 20:29:05 GMT Subject: O_DIRECT on stdin? References: <11mvbsv4lbri8d@corp.supernews.com> Message-ID: On Mon, 07 Nov 2005 19:48:47 +0000, Gordon Burditt wrote: >> [quoted text muted] > > There is no O_DIRECT or fcntl() in Standard C. > > fcntl() operates on an open file descriptor, and the file descriptor > for stdin is 0. Two calls to fcntl(), one with F_GETFL and one > with F_SETFL, would do what you want. > > I'm not sure why you want to do that, though. It's not going to > get you character-at-a-time I/O, if that's what you want. > > Gordon L. Burditt I want to be able to read a HUGE file without having such a negative impact on the system's buffer cache. I'm trying: if hasattr(os, 'O_DIRECT'): try: flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) flags |= os.O_DIRECT fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags) except: sys.stderr.write('Setting O_DIRECT on stdin attempted but failed\n') else: sys.stderr.write('Setting O_DIRECT on stdin succeeded :)\n') ...but while this code doesn't error out, I get: seki-root> reblock -e $[1024*1024*80] $[1024*1024] 300 < /dev/sda1 > /dev/null stdin seems seekable, but file length is 0 - no exact percentages Estimated filetransfer size is 85899345920 bytes Estimated percentages will only be as accurate as your size estimate Setting O_DIRECT on stdin succeeded :) Traceback (most recent call last): File "/Dcs/seki/strombrg/bin/reblock", line 276, in ? main() File "/Dcs/seki/strombrg/bin/reblock", line 222, in main block = os.read(0,blocksize) OSError: [Errno 22] Invalid argument Mon Nov 07 12:25:53 ...but if I comment out the fcntl/O_DIRECT code, then the same thing works well. Any other ideas folks? Thanks! From luca.tavoletti at gmail.com Tue Nov 29 14:10:36 2005 From: luca.tavoletti at gmail.com (lux) Date: 29 Nov 2005 11:10:36 -0800 Subject: wxGrid and Focus Event Message-ID: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> Hi, How can I capture the EVT_SET_FOCUS on a wxGrid? Tank's in advance Luca From jgrahn-nntq at algonet.se Wed Nov 9 15:37:59 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 9 Nov 2005 20:37:59 GMT Subject: Flat file, Python accessible database? References: <877jbsxnrx.fsf@lucien.dreaming> Message-ID: On Tue, 1 Nov 2005 21:02:20 +0000 (UTC), Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) wrote in > news:877jbsxnrx.fsf at lucien.dreaming: > >> If you need it to be SQL-like, SQLite seems to be the right thing. > > Tried that one, but had some problems setting things up. On the other > hand, BerkeleyDB + Pybsddb worked like a charm, with no setting up (under > Cygwin). > > The problem is, Pybsddb is as badly documented as Windows Registry, no > examples, no tutorials, no nothing :(. What about the standard module bsddb, then? It's not a /relational/ database though, if that is what you're looking for. But it's simple to understand, well documented, and unbelievably fast. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From ptmcg at austin.rr._bogus_.com Mon Nov 7 07:48:20 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 07 Nov 2005 12:48:20 GMT Subject: how to present Python's OO feature in design? References: <1131332809.044523.169900@o13g2000cwo.googlegroups.com> Message-ID: "pcmanlin" wrote in message news:1131332809.044523.169900 at o13g2000cwo.googlegroups.com... > As I know java has many UML tools to design for its OO feature, is > there any tools or good concept for Python project Modeling? > Check out EnterpriseArchitect (http://www.sparxsystems.com.au ). They have a very good UML tool that has a Python plugin. I'd recommend the Professional Edition - the code reverse-engineering is like magic. Not open source or free, though. EA Pro is US$199, Academic license is US$105. But compare to Rational at $US000's, it is a great value for the money. -- Paul McGuire (not associated wth SparxSystems, just a happy customer) From steveha at localhost.localdomain Tue Nov 22 18:44:23 2005 From: steveha at localhost.localdomain (Steve R. Hastings) Date: Tue, 22 Nov 2005 15:44:23 -0800 Subject: user-defined operators: a very modest proposal References: Message-ID: > Here is a thought: Python already supports an unlimited number of > operators, if you write them in prefix notation: And indeed, so far Python hasn't added user-defined operators because this has been adequate. > Here is some syntax that I don't object to, although that's not saying > much. > m0(+)m1 That form was discussed previously, as were "[+]", "<+>", etc. The favorite was "{+}". I believe such forms were considered hard to tell from code. In particular, m0(+) looks like a function call. See the PEP: http://www.python.org/peps/pep-0225.html Alas, the links to the discussion about this don't work. But it is possible to use the Google Groups archive of comp.lang.python to read some of the discussion. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From gsakkis at rutgers.edu Wed Nov 2 04:14:16 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 2 Nov 2005 01:14:16 -0800 Subject: Attributes of builtin/extension objects Message-ID: <1130922856.013081.172770@g47g2000cwa.googlegroups.com> Hi all, I have a few questions on object introspection of builtins and extension modules. Here's an example: >>> from datetime import date >>> d=date(2003,1,23) >>> d.__dict__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'datetime.date' object has no attribute '__dict__' >>> d.__slots__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'datetime.date' object has no attribute '__slots__' >>> dir(d) ['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__str__', '__sub__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year'] - Where do the attributes of a datetime.date instance live if it has neither a __dict__ nor __slots__ ? - How does dir() determine them ? - dir() returns the attributes of the instance itself, its class and its ancestor classes. Is there a way to determine the attributes of the instance alone ? TIA, George From bonono at gmail.com Mon Nov 21 02:02:43 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 23:02:43 -0800 Subject: best cumulative sum In-Reply-To: References: <9Qbgf.8204$BC2.5713@trnddc04> Message-ID: <1132553397.042444.147660@g44g2000cwa.googlegroups.com> Erik Max Francis wrote: > Micah Elliott wrote: > > > On Nov 21, David Isaac wrote: > > > >> What's the good way to produce a cumulative sum? > > > >>>> import operator > >>>> x = 1,2,3 > >>>> reduce(operator.add, x) > > 6 > > Or just sum(x). > He seems to want scanl From apardon at forel.vub.ac.be Thu Nov 24 06:09:26 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Nov 2005 11:09:26 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> Message-ID: Op 2005-11-24, Mike Meyer schreef : > "bonono at gmail.com" writes: >> Mike Meyer wrote: >>> > I do think that the Python development community believes they do, >>> > or more accurately, that if someone wants to use a different style, >>> > they can go use something else. >>> In other words, they believe that you should use a screwdriver to >>> drive screws, and not a hammer. You apparently disagree with them. >> That is the kind of argument I see all the time on this thread. It is >> more appropriate to say that "I don't believe it is a screw, but >> something else and don't want to use a screw driver with it". > > Whatever it is, trying to turn Python into a tool for dealing with it > isn't the right thing to do. > >>> > I think that it is possible to include in Python, things that are >>> > non-Pythonic (such as a return value from sort()) that allow users >>> > more stylistic freedom, without degrading the ability of those who >>> > don't want to use such features, to write in a pure Pythonic manner. >>> So you think we can turn a hammer into a screwdriver without degrading >>> the ability to use the hammer to drive nails. The problem is, doing >>> this means you have a bigger, heavier hammer - which almost certainly >>> degrades the ability to use it as a hammer. >> And it follows through, first said it is a screw and since you >> disagree, you are trying to do screwing with a hammer. > > You're the one that wants to use the hammer to do whatever it is, not > me. I don't believe in silver bullets. Python is good at what it > does. If I need a different tool, I use a different tool, rather than > try and mangle a good tool into something it's not. Why do you use the word "mangle" here? I'll come to this again later. > Such attempts are > pretty much doomed. They nearly inevitably producej a tool that's not > as good at what the original did as the original, and not as good at > whatever new task it's being mangledd to do as a tool that was > designed for that in the first place. > >>> Now, I'm not against changing the language per se. But most language >>> changes have deeper implications than are obvious at first >>> glance. Even when they don't, I'd prefer that you get cases that make >>> for significantly cleaner code without having major negative >>> connotations. The first is why people ask for "use cases": they want >>> to see a real-world example where the proposed change would make >>> things cleaner or more readable, or otherwise better in some way. At >>> the same time, the new feature should provide an abuse that's hard to >>> read, or lead to code that is easily misinterpreted. >> I am just curious that if the "should we have ternary" back then >> creates similar arguments. > > By the results of the vote, most people wanted ternary. The use > cases for it are well know. From what I recall, the debate was over > which of the many proposals should be adopted. No it wasn't. From what I have picked up, the ternary operator was finaly introduced after one of the developers tripped over the commonly used idiom to simulate a ternary operator, which can fail in certain cases. Anyway, when I was arguing for a ternary operator in python, those who opposed me, certainly gave me the impression that they thought I wanted to mangle the language, the mere idea of a ternary operator was against the spirit of python. When I argued for a more general loop construct similar objections were made and the proposal was fiercely fought. Someone even started a PEP, with the intention to bury the idea. (That can be from before I argued for it) Now I have read about both that they will be introduced in Python 2.5 without a whisper of protest. >> Based on what I have read for this few period of time on this group, it >> is actually not people coming in complain loudly that "why can't Python >> have this" kind of post, it usually was a neutral question because >> either they come from another background, or they for whatever reason >> expect things to work certain way, or they enjoy certain style. But >> many times, the responses are toned in a way of "you dumb, you didn't >> know that is the wrong way of doing it?", without explain why or with >> convincing reasons. > > The usual response is "That's not the Python way." That's not calling > someone dumb, just pointing out that they don't yet fully understand > the Python way. "That is not the Python way", is just saying "Python doesn't have it" in other words. So it can't be the answer to why python can't have something. > The Python way is not something you're going to grok > by reading postings on usenet. You can have bits and pieces explained > to you, and your understanding will increase. And that's the way it is > for everyone but GvR. The python way is something that changes continuously. What is the python way now certainly wasn't the python way with version 1.5 (when I started). So "That is not the python way" doesn't answer the question why it couldn't be the python way. -- Antoon Pardon From roy at panix.com Fri Nov 25 21:58:00 2005 From: roy at panix.com (Roy Smith) Date: Fri, 25 Nov 2005 21:58:00 -0500 Subject: icmp - should this go in itertools? References: Message-ID: Tom Anderson wrote: > It's modelled after the way cmp treats lists - if a and b are lists, > icmp(iter(a), iter(b)) should always be the same as cmp(a, b). > > Is this any good? Would it be any use? Should this be added to itertools? Whatever happens, please name it something other than icmp. When I read "icmp", I think "Internet Control Message Protocol". From deets at nospam.web.de Thu Nov 17 13:33:16 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Nov 2005 19:33:16 +0100 Subject: Current execution frame of another thread? In-Reply-To: References: Message-ID: <3u40n9Fvdc5fU1@uni-berlin.de> skip at pobox.com wrote: > I would like to try a sampling approach to profiling. My thought is to have > a profiling thread that samples the execution frame of all the other > started threads. I don't see any path from the threads returned by > threading.enumerate() to their current frames. Am I missing something? I doubt that works. As python uses the OS underlying threading model, it doesnn't know about the internal management structures - and even it knew, these had to be carefully designed for that exact purposes of yours, as the stack frame can only be safely inspected by the thread _running_ in it. An external thread could be interrupted at all times while traversing other threads management structures, and then find a corrupted memory location when it is re-scheduled. Maybe one could write a threading model that allwos for hooks in the scheduler (which has all the time in the world for such stuff) - but I'm not aware that that's possible under e.g. pthreads, so there is unlikely a python-way to do so. Regards, Diez From mrbmahoney at gmail.com Thu Nov 10 13:22:59 2005 From: mrbmahoney at gmail.com (B Mahoney) Date: 10 Nov 2005 10:22:59 -0800 Subject: Python-based Document Management System? In-Reply-To: References: Message-ID: <1131646979.571306.21280@f14g2000cwb.googlegroups.com> If you search for CONTENT management system, there is Plone: A user-friendly and powerful open source Content Management ... http://plone.org/ From careers at htsg.com Wed Nov 16 00:58:29 2005 From: careers at htsg.com (Frank Odia) Date: Tue, 15 Nov 2005 21:58:29 -0800 Subject: Do you have PERL and SQL programming experience? Message-ID: <5BB15121-F54A-4A43-9C2A-993BC3625DA9@htsg.com> If the answer is yes I want to talk to you. My name is Frank Odia and I am a recruiter with High Tech Staffing, an IT placement firm in Portland. I came across your name while searching for PERL programmer with relational database background (Postgress or Oracle) for a client here in Portland. Honestly I don't know anything about your work experience but thought it wouldn't harm anybody if I shared this opening with you. PERL DEVLOPER Our client provides business intelligence to the entertainment industry. Their product allows key decision-makers to become aware of trends and market opportunities. They are looking for an experienced PERL and SQL programmer (3-5 years or more) to help them expand their line of data analysis and reporting applications. The ideal candidate will have strong experience with Perl in a Unix environment and large transactional databases with Oracle 9i. Broad knowledge of computer science and software engineering discipline is preferred. If you know Scheme, Common Lisp, Haskell, ML, Smalltalk, Python and/or Ruby, your familiarity with advanced programming language concepts will benefit you during application and on the job. Candidates with experience or interest in pair programming and test- driven development are encouraged to apply. If you would like to be considered for this opening please forward me a copy of your resume to careers at htsg.com. This may not be the right situation for you. If not, hopefully you respect someone you know enough to pass this on to them, so they can make a decision to improve their life. Imagine - you have the ability to improve a colleague or friend?s job, career, lifestyle, by simply passing this on to them. Sincerely Frank Michael Odia Sr. Partner HIGH TECH STAFFING GROUP 3112 SE 197th Court Camas WA 98607 Phone 503-914-6114 Alternate: 415-513-5399 Cell: 503-780-3210 Fax 440-388-5940 email:careers at htsg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From adonisv at DELETETHISTEXTearthlink.net Sun Nov 20 20:34:55 2005 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Mon, 21 Nov 2005 01:34:55 GMT Subject: about list In-Reply-To: References: Message-ID: <3v9gf.3485$N45.2354@newsread1.news.atl.earthlink.net> Shi Mu wrote: > How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]? > Thanks! From what I gather try: a = [1,2,4] n = list() for i in a: index = a.index(i) + 1 for x in a[index:]: n.append([i, x]) print n more elegant ways to do this, but its a start. hope this helps. Adonis From bonono at gmail.com Wed Nov 9 22:47:47 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 19:47:47 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> Message-ID: <1131594467.709976.320520@o13g2000cwo.googlegroups.com> Alex Martelli wrote: > This becomes a valid list comprehension by writing 'if' instead of > 'when'. valid, yes. efficient, I am not sure. [ x for x in xrange(10000000) if p(x) ] means I need to go through the whole range even if p = lambda x: x < 2. From fairwinds at eastlink.ca Tue Nov 8 18:30:26 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Tue, 08 Nov 2005 19:30:26 -0400 Subject: sqlite3 decode error In-Reply-To: <20051108204948.10365.1937227228.divmod.quotient.5308@ohm> Message-ID: Hi Jean-Paul for some really good advice. I'll take a look at the project to see how this is handled. I was not aware of your wrapper project for SQLite - so this is something new to look at too. I have worked with SQLObject and also Django's db wrappers. In fact this question has come out of an SQLObject implementation in RDFlib since it is here I discovered this issue in the way this backend is behaving with SQLite3 and I have got it working now. I am only starting to warm to the idea of unicode throughout. For example. In the backend code that I am trying to work with you have this. _tokey is a helper to bring things into the relational database, _fromkey is a helper when extracting data from the database. Commenting out the .decode("UTF-8") and value = value.decode("UTF-8") allowed me to get this working but I need to make this work with unicode. My unicode experience is limited and I am confused about writing unicode compatible replacements for things like: return '<%s>' % ''.join(splituri(term.encode("UTF-8"))) def splituri(uri): if uri.startswith('<') and uri.endswith('>'): uri = uri[1:-1] if uri.startswith('_'): uid = ''.join(uri.split('_')) return '_', uid if '#' in uri: ns, local = rsplit(uri, '#', 1) return ns + '#', local if '/' in uri: ns, local = rsplit(uri, '/', 1) return ns + '/', local return NO_URI, uri def _fromkey(key): if key.startswith("<") and key.endswith(">"): key = key[1:-1].decode("UTF-8") ## Fails here when data extracted from database if key.startswith("_"): key = ''.join(splituri(key)) return BNode(key) return URIRef(key) elif key.startswith("_"): return BNode(key) else: m = _literal.match(key) if m: d = m.groupdict() value = d["value"] value = unquote(value) value = value.decode("UTF-8") ## Fails here when data extracted from database lang = d["lang"] or '' datatype = d["datatype"] return Literal(value, lang, datatype) else: msg = "Unknown Key Syntax: '%s'" % key raise Exception(msg) def _tokey(term): if isinstance(term, URIRef): term = term.encode("UTF-8") if not '#' in term and not '/' in term: term = '%s%s' % (NO_URI, term) return '<%s>' % term elif isinstance(term, BNode): return '<%s>' % ''.join(splituri(term.encode("UTF-8"))) elif isinstance(term, Literal): language = term.language datatype = term.datatype value = quote(term.encode("UTF-8")) if language: language = language.encode("UTF-8") if datatype: datatype = datatype.encode("UTF-8") n3 = '"%s"@%s&<%s>' % (value, language, datatype) else: n3 = '"%s"@%s' % (value, language) else: if datatype: datatype = datatype.encode("UTF-8") n3 = '"%s"&<%s>' % (value, datatype) else: n3 = '"%s"' % value return n3 else: msg = "Unknown term Type for: %s" % term raise Exception(msg) In an unrelated question, it appears SQLite is also extremely flexible about what types of data it can contain. When writing SQL in Postgres I use timestamp type and can use this also in SQLite. With my work with Django, the same information is mapped to datetime type. Would you be inclined to recommend the use of one type over the other. If so, can you explain the rationale for this choice. Many thanks. Regards, David On Tuesday, November 8, 2005, at 04:49 PM, Jean-Paul Calderone wrote: > On Tue, 08 Nov 2005 16:27:25 -0400, David Pratt > wrote: >> Recently I have run into an issue with sqlite where I encode strings >> going into sqlite3 as utf-8. I guess by default sqlite3 is converting >> this to unicode since when I try to decode I get an attribute error >> like this: >> >> AttributeError: 'unicode' object has no attribute 'decode' >> >> The code and data I am preparing is to work on postgres as well a >> sqlite so there are a couple of things I could do. I could always >> store any data as unicode to any db, or test the data to determine >> whether it is a string or unicode type when it comes out of the >> database so I can deal with this possibility without errors. I will >> likely take the first option but I looking for a simple test to >> determine my object type. >> >> if I do: >> >>>>> type('maybe string or maybe unicode') >> >> I get this: >> >>>>> >> >> I am looking for something that I can use in a comparison. >> >> How do I get the type as a string for comparison so I can do something >> like >> >> if type(some_data) == 'unicode': >> do some stuff >> else: >> do something else >> > > You don't actually want the type as a string. What you seem to be > leaning towards is the builtin function "isinstance": > > if isinstance(some_data, unicode): > # some stuff > elif isinstance(some_data, str): > # other stuff > ... > > But I think what you actually want is to be slightly more careful > about what you place into SQLite3. If you are storing text data, > insert is as a Python unicode string (with no NUL bytes, unfortunately > - this is a bug in SQLite3, or maybe the Python bindings, I forget > which). If you are storing binary data, insert it as a Python buffer > object (eg, buffer('1234')). When you take text data out of the > database, you will get unicode objects. When you take bytes out, you > will get buffer objects (which you can convert to str objects with > str()). > > You may want to look at Axiom > () to see how it handles each > of these cases. In particular, the "text" and "bytes" types defined > in the attributes module > (). > > By only encoding and decoding at the border between your application > and the outside world, and the border between your application and the > data, you will eliminate the possibility for a class of bugs where > encodings are forgotten, or encoded strings are accidentally combined > with unicode strings. > > Hope this helps, > > Jean-Paul > -- > http://mail.python.org/mailman/listinfo/python-list > From bokr at oz.net Wed Nov 2 01:46:43 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 02 Nov 2005 06:46:43 GMT Subject: With & marcos via import hooking? (Was Re: Scanning a file) References: <1130497567.764104.125110@g44g2000cwa.googlegroups.com> <7xek65nal0.fsf@ruckus.brouhaha.com> <1130505731.850947.68690@o13g2000cwo.googlegroups.com> <87ek65kbw5.fsf@lucien.dreaming> <1h5760l.1e2eatkurdeo7N%aleaxit@yahoo.com> <3siakvFohl3aU1@individual.net> <1h57cij.16dkc141lds4s4N%aleaxit@yahoo.com> <1h597yx.wjk2a71spyjhyN%aleaxit@yahoo.com> <3smn47FoolfbU1@individual.net> <3snboiFolt77U1@individual.net> <7x7jbt9l42.fsf@ruckus.brouhaha.com> <3sp82jFpgdhdU1@individual.net> Message-ID: <43685f44.1594572524@news.oz.net> On Tue, 01 Nov 2005 07:14:57 -0600, Paul Watson wrote: >Paul Rubin wrote: >> jjl at pobox.com (John J. Lee) writes: >> >>>Closing off this particular one would make it harder to get benefit of >>>non-C implementations of Python, so it has been judged "not worth it". >>>I think I agree with that judgement. >> >> >> The right fix is PEP 343. > >I am sure you are right. However, PEP 343 will not change the existing >body of Python source code. Nor will it, alone, change the existing >body of Python programmers who are writing code which does not close files. It might be possible to recompile existing code (unchanged) to capture most typical cpython use cases, I think... E.g., I can imagine a family of command line options based on hooking import on startup and passing option info to the selected and hooked import module, which module would do extra things at the AST stage of compiling and executing modules during import, to accomplish various things. (I did a little proof of concept a while back, see http://mail.python.org/pipermail/python-list/2005-August/296594.html that gives me the feeling I could do this kind of thing). E.g., for the purposes of guaranteeing close() on files opened in typical cpython one-liners or single-suiters) like e.g. for i, line in enumerate(open(fpath)): print '%04d: %s' %(i, line.rstrip()) I think a custom import could recognize the open call in the AST and extract it and wrap it up in a try/finally AST structure implementing something like the following in the place of the above; __f = open(fpath) # (suitable algorithm for non-colliding __f names is required) try: for i, line in enumerate(__f): print '%04d: %s' %(i, line.rstrip()) finally: __f.close() In this case, the command line info passed to the special import might look like python -with open script.py meaning calls of open in a statement/suite should be recognized and extracted like __f = open(fpath) above, and the try/finally be wrapped around the use of it. I think this would capture a lot of typical usage, but of course I haven't bumped into the gotchas yet, since I haven't implemented it ;-) On a related note, I think one could implement macros of a sort in a similar way. The command line parameter would pass the name of a class which is actually extracted at AST-time, and whose methods and other class variables represent macro definitions to be used in the processing of the rest of the module's AST, before compilation per se. Thus you could implement e.g. in-lining, so that ---- #example.py class inline: def mac(acc, x, y): acc += x*y tot = 0 for i in xrange(10): mac(tot, i*i) ---- Could be run with python -macros inline example.py and get the same identical .pyc as you would with the source ---- #example.py tot = 0 for i in xrange(10): tot += i*i ---- IOW, a copy of the macro body AST is substituted for the macro call AST, with parameter names translated to actual macro call arg names. (Another variant would also permit putting the macros in a separate module, and recognize their import into other modules, and "do the right thing" instead of just translating the import. Maybe specify the module by python - macromodule inline example.py and then recognize "import inline" in example.py's AST). Again, I just have a hunch I could make this work (and a number of people here could beat me to it if they were motivated, I'm sure). Also have a hunch I might need some flame shielding. ;-) OTOH, it could be an easy way to experiment with some kinds of language tweaks. The only limitation really is the necessity for the source to look legal enough that an AST is formed and preserves the requisite info. After that, there's no limit to what an AST-munger could do, especially if it is allowed to call arbitrary tools and create auxiliary files such as e.g. .dlls for synthesized imports plugging stuff into the final translated context ;-) (I imagine this is essentially what the various machine code generating optimizers do). IMO the concept of modules and their (optionally specially controlled) translation and use could evolve in may interesting directions. E.g., __import__ could grow keyword parameters too ... Good thing there is a BDFL with a veto, eh? ;-) Should I bother trying to implement this import for with and macros from the pieces I have (plus imp, to do it "right") ? BTW, I haven't experimented with command line dependent site.py/sitecustomize.py stuff. Would that be a place to do sessionwise import hooking and could one rewrite sys.argv so the special import command line opts would not be visible to subsequent processing (and the import hook would be in effect)? IWT so, but probably should read site.py again and figure it out, but appreciate any hints on pitfalls ;-) Regards, Bengt Richter From tuvas21 at gmail.com Mon Nov 7 13:24:07 2005 From: tuvas21 at gmail.com (Tuvas) Date: 7 Nov 2005 10:24:07 -0800 Subject: Tkinter- Building a message box Message-ID: <1131387846.676519.184420@g44g2000cwa.googlegroups.com> I've been trying to build a fairly simple message box in tkinter, that when a button is pushed, will pop up a box, that has a line of text, an entry widget, and a button, that when the button is pushed, will return the value in the line of text. However, while I can read the value of the button, I want to wait till the button is pushed to return the value. Any ideas of how I could do this? From wsanchez at apple.com Thu Nov 17 19:32:01 2005 From: wsanchez at apple.com (=?ISO-8859-1?Q?Wilfredo_S=E1nchez_Vega?=) Date: Thu, 17 Nov 2005 16:32:01 -0800 Subject: XML and namespaces Message-ID: I'm having some issues around namespace handling with XML: >>> document = xml.dom.minidom.Document() >>> element = document.createElementNS("DAV:", "href") >>> document.appendChild(element) >>> document.toxml() '\n' Note that the namespace wasn't emitted. If I have PyXML, xml.dom.ext.Print does emit the namespace: >>> xml.dom.ext.Print(document) Is that a limitation in toxml(), or is there an option to make it include namespaces? -wsv From steve at holdenweb.com Mon Nov 7 13:55:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 Nov 2005 18:55:29 +0000 Subject: [OT] Map of email origins to Python list In-Reply-To: <425926b9683e56644bf034dfb9ed65d7@zeesource.net> References: <425926b9683e56644bf034dfb9ed65d7@zeesource.net> Message-ID: Claire McLister wrote: > We've been working with Google Maps, and have created a web service to > map origins of emails to a group. As a trial, we've developed a map of > emails to this group at: > > http://www.zeesource.net/maps/map.do?group=668 > > This represents emails sent to the group since October 27. > > Would like to hear what you think of it. > > Thanks for listening. > Mostly I wonder what the point is. For example, given my own somewhat nomadic life I wondered what location has been used to map my own contributions. Examination of the maps source reveals you used the code _m = createMarker(new GPoint(-82.775497, 40.3736), 'red', "
Ohio, United States
s... at holdenweb.com
"); _m.city = ''; _m.country = 'United States'; _m.name = ' s... at holdenweb.com'; marar.push(_m); to generate my reference. This has never been correct (I am not sure I've ever been to Ohio) and it certainly isn't now (since I moved continents recently). Nonetheless I'm sure that before long these maps will be used to prove some spurious facts about newsgroup readership to gullible members of the business community. If I've got you wrong then please forgive my slight hostility, but I am particularly suspicious of the "click to change" functionality. You are clearly expecting people to update their locations, and other information that might be related to their domains, and I can't help wondering what purposes that information is intended for. Finally, considering email address from domains like "verizon.net", "aol.com" and other large ISPs I can't see that you have a chance in hell of extracting useful demographics. Which all leads me back to "what's the point?" - just because you can? 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 javuchi at gmail.com Sun Nov 20 21:43:03 2005 From: javuchi at gmail.com (javuchi) Date: 20 Nov 2005 18:43:03 -0800 Subject: Aproximative string matching Message-ID: <1132540983.139462.63330@f14g2000cwb.googlegroups.com> I'm searching for a library which makes aproximative string matching, for example, searching in a dictionary the word "motorcycle", but returns similar strings like "motorcicle". Is there such a library? From http Thu Nov 24 20:19:19 2005 From: http (Paul Rubin) Date: 24 Nov 2005 17:19:19 -0800 Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> <86y83dvacs.fsf@bhuda.mired.org> Message-ID: <7xfyplmsmg.fsf@ruckus.brouhaha.com> "Giovanni Bajo" writes: > > However, when you prevent a client from adding an attribute, you're > > not merely making your objects immutable, you're making them > > static. No I don't believe that. If an object is immutable, then obj.serialize() should return the same string every time. If you can add attributes then the serialization output will become different. From lycka at carmen.se Wed Nov 2 13:35:20 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 02 Nov 2005 19:35:20 +0100 Subject: Python and MySQL In-Reply-To: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> References: <1130948507.082484.199730@f14g2000cwb.googlegroups.com> Message-ID: Aquarius wrote: > I appologize in advance for this strange (and possibly stupid) > question. > > I want to know if there is a way to interface a MySQL database without > Python-MySQL or without installing anything that has C files that need > to be compiled. The reason for this, is that I want to develop a > certain web application, but my hosting provider (!#@$!@#%) isn't very > eager to supply Python-MySQL (or any modules to python). Is there an > alternative approach I could use to pass around this ridiculos lack of > functionality? I assume that MySQL clients talk to servers via sockets, and it should be possible to write a python client that did that. It's probably some work though, and it will probably piss MySQL AB off, since it means that you could write MySQL client apps using whatever license you want without paying them. I wrote a prototype for such a client lib for PostgreSQL once, and it was fairly simple, but the PostgreSQL docs have decent descriptions of their protocol, while I assume MySQL hasn't since they want people to use their client libs and pay for that. (If you read the client lib source and translate that to Python, it should be considered a derivate, and GPL applies. If you manage to get it to work without reading any GPLed code, I guess you are entitled to use whatever license you want.) Disclaimer: IANAL. From bwm at acm.org Wed Nov 30 10:58:52 2005 From: bwm at acm.org (Bernhard Mulder) Date: Wed, 30 Nov 2005 07:58:52 -0800 Subject: python number handling - tiny encryption algorithm In-Reply-To: References: Message-ID: <438DCC3C.7000005@acm.org> One systematic, if maybe clumsy way, is to mimic the C arithmetic operations more closely in Python. If you do, for example, a left shift in C, the result is always returned in a certain precision, 64 bits in the example below. In python, no bits are lost, so you have to force the result into the 64 bits back to obtain the same result. Instead of (y << 4) you can write something like (untested!) (y << 4) & 0xFF...FF. Once you understand what the algorithm is doing, you may want to go back and express the algorithm in a more pythonic way (not by programming C in Python). Kinsley Turner wrote: > > Hey-ho, > > I'm getting a bit out of my depth porting the 'tiny encryption algorithm' > from C to python. > > Ref: > http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm > http://www.simonshepherd.supanet.com/source.htm#new_ansi > > Specifically I don;t know how to handle a C-long block and perform the > mathmatical manipulations in python syntax. I played with pack and unpack > (from struct module) but that didn't seem to buy me anything. > > In my version, I end up with hugely long integers, which have obviously > not be constrained into the 4-byte unsigned longs that TEA is expecting. > > This is the C function: > > /* v is 64-bits input, w is 64-bits output, k is the 128-bit key */ > void decipher(const unsigned long *const v,unsigned long *const w, const > unsigned long * const k) > { > register unsigned long > y=v[0],z=v[1],sum=0xC6EF3720,delta=0x9E3779B9,n=32; > > while(n-->0) > { > z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3]; > sum -= delta; > y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3]; > } > w[0]=y; w[1]=z; > } > > > Which gives me a (broken) python version: > > def teaDecipher(input,key): > y = input[0] > z = input[1] > n = 32 > sum = 0xC6EF3720 > delta=0x9E3779B9 > > while (n > 0): > n -= 1 > z -= (y << 4 ^ y >> 5) + y ^ sum + key[sum>>11 & 3]; > sum -= delta; > y -= (z << 4 ^ z >> 5) + z ^ sum + key[sum&3]; > return y,z > > That seems to return hugely-long integers (around 30? digits), whereas I'd > expect > them to max-out at 2^32. > > Perhaps I'm not packing the input or the key properly. My inputs are > just strings which I put into an integer with the ordinal value of each > character > shifted into the correct position to make the C-long. > > Something like: > input[0] = ord(encrypted[i])<<24 + ord(encrypted[i+1])<<16 + > ord(encrypted[i+2])<<8 + ord(encrypted[i+3]) > input[1] = ord(encrypted[i+4])<<24 + ord(encrypted[i+5])<<16 + > ord(encrypted[i+6])<<8 + ord(encrypted[i+7]) > > The key is created as an array of numbers, each the ord() of the key > character... > > > Anyway, that's about it. > Any help much appreciated. > > > thanks, > -kt > > > > > > > > > > > > > > > > > > > > (non-removable disclaimer below... *sigh*) > -- > > Please consider our environment before printing this email. > > WARNING - This email and any attachments may be confidential. If received in error, please delete and inform us by return email. Because emails and attachments may be interfered with, may contain computer viruses or other defects and may not be successfully replicated on other systems, you must be cautious. Westpac cannot guarantee that what you receive is what we sent. If you have any doubts about the authenticity of an email by Westpac, please contact us immediately. > > It is also important to check for viruses and defects before opening or using attachments. Westpac's liability is limited to resupplying any affected attachments. > > > This email and its attachments are not intended to constitute any form of financial advice or recommendation of, or an offer to buy or offer to sell, any security or other financial product. We recommend that you seek your own independent legal or financial advice before proceeding with any investment decision. > > Westpac Institutional Bank is a division of Westpac Banking Corporation, a company registered in New South Wales in Australia under the Corporations Act 2001 (Cth). Westpac is authorised and regulated in the United Kingdom by the Financial Services Authority and is registered at Cardiff in the United Kingdom as Branch No. BR 106. Westpac operates in the United States of America as a federally chartered branch, regulated by the Office of the Comptroller of the Currency. > > Westpac Banking Corporation ABN 33 007 457 141. From igouy at yahoo.com Wed Nov 30 15:41:46 2005 From: igouy at yahoo.com (Isaac Gouy) Date: 30 Nov 2005 12:41:46 -0800 Subject: python speed In-Reply-To: References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> Message-ID: <1133383306.218266.123210@f14g2000cwb.googlegroups.com> Peter Hansen wrote: > David Rasmussen wrote: > > Frithiof Andreas Jensen wrote: > >>From the speed requirement: Is that correspondance chess by any chance?? > > > > Regular chess at tournament time controls requires speed too. Any pure > > Python chess program would lose badly to the best C/C++ programs out > > there now. > > > > I would also like to see Half Life 2 in pure Python. > > True, but so what? Why did you suddenly change the discussion to > require "pure" Python? And please define "pure" Python, given that the > interpreter and many builtins, not to mention many widely used extension > modules, are coded in C? And are you not allowed to use any of the > performance-boosting techniques available for Python, like Pyrex or > Psyco? Why such restrictions, when these are things Python programs use > on a daily basis: these are *part* of Python, as much as the -O switch > on the compiler is part of C/C++. > > Okay, let's compare a "pure" Python program (if you can define it in any > meaningful, practical way) with a "pure" Java program, running on a > non-JIT interpreter and with optimizations turned off (because, of > course, those optimizations are umm... somehow.. not "pure"...?). > > Judging by the other posts in this thread, the gauntlet is down: Python > is faster than Java. Let those who believe otherwise prove their point > with facts, and without artificially handcuffing their opponents with > non-real-world "purity" requirements. > > -Peter That form of argument is listed as one of the principal forms of illogical thinking in "Being Logical" D.Q.McInerny - "An Inability to Disprove Does Not Prove" "The fact that there is no concrete proof against a position does not constitute an argument in favour of the position. I cannot claim to be right simply because you can't prove me to be wrong." From codecraig at gmail.com Tue Nov 15 14:54:12 2005 From: codecraig at gmail.com (py) Date: 15 Nov 2005 11:54:12 -0800 Subject: is parameter an iterable? In-Reply-To: References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082786.2300.2.camel@blackwidow> Message-ID: <1132084452.046608.117850@o13g2000cwo.googlegroups.com> Thanks for the replies. I agree with Jean-Paul Calderone's suggestion...let the exception be raised. Thanks. From steve at REMOVETHIScyber.com.au Sat Nov 26 04:07:42 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 26 Nov 2005 20:07:42 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <1132841680.454026.203420@z14g2000cwz.googlegroups.com> <11ocu1og1660965@corp.supernews.com> <1132928461.261842.132720@g47g2000cwa.googlegroups.com> <11oehpnecp556df@corp.supernews.com> <7xfypkidth.fsf@ruckus.brouhaha.com> <11ofle6m5b9lc63@corp.supernews.com> Message-ID: On Sat, 26 Nov 2005 03:25:58 +0000, Ed Jensen wrote: > Paul Rubin wrote: >> Python and *BSD are getting far less volunteer development love than, >> say, GCC or Linux, and the licensing is at least part of the reason. > > I disagree. I believe *BSD gets less volunteer development because of > some legal wrangling in the early 90s that didn't affect Linux. That was over a decade ago, and the BSD licence was vindicated by the courts -- why has there been such limited volunteer development, and practically zero commercial development, for BSD? The BSDs are about 15 years older than Linux, and the legal wrangling they went through were no worse than the SCO nonsense going on now. With a 15 year head start, and 10 years since the legal problems, why has BSD never attracted 1% the commercial interest of Linux? You can often tell something of a thing by those who oppose it. Microsoft is perhaps the epitome of the closed-source mentality: on the rare occasions they release their source code at all, they do so only grudgingly, never the entire tool chain, at very high cost, and with exceedingly restrictive conditions. (Yes, I'm aware I'm generalising -- but it is a valid generalisation, one or two minor exceptions doesn't invalidate the overall picture of Microsoft's desire to keep their source code locked up tight.) Microsoft is spending a lot of time and effort trying to fight the GPL, but have said that BSD licences are acceptable to them. In fact they *love* BSD licences -- for others, just not for themselves. And no wonder: Windows only has an TCP/IP stack because they could grab the BSD source code and use it. Has Microsoft show any gratitude to the BSDs? Have they returned any code to BSDs, or given money to BSD coders? In a pig's ear they have. Microsoft stands for closed source software: they absolutely hate the GPL. But they like the BSD licence, because it lets them freeload off the labour of idealistic programmers for free, without so much as a thank you. -- Steven. From y.glodt at sitasoftware.lu Wed Nov 9 10:07:16 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 09 Nov 2005 16:07:16 +0100 Subject: append to non-existing list In-Reply-To: <43720a31$0$38620$edfadb0f@dread12.news.tele.dk> References: <4371fb5a$0$18086$626a14ce@news.free.fr> <43720a31$0$38620$edfadb0f@dread12.news.tele.dk> Message-ID: <437210A4.2000108@sitasoftware.lu> Max M wrote: > Yves Glodt wrote: >> bruno at modulix wrote: >> >>> Yves Glodt wrote: >>> >>>> Hello, >>>> >>>> if I do this: >>>> >>>> for row in sqlsth: >>>> ________pkcolumns.append(row[0].strip()) >>>> ________etc >>>> >>>> >>>> without a prior: >>>> >>>> pkcolumns = []; >>>> >>>> >>>> I get this error on first iteration: >>>> UnboundLocalError: local variable 'pkcolums' referenced before >>>> assignment >>>> >>>> >>>> I guess that's normal as it's the way python works...?!? > > > Well you could do something like this. (Untested and unrecommended) > > self.__dict__.setdefault('pkcolumns', []).append(row[0].strip()) > > Personally I find > > pkcolumns = [] > pkcolumns .append(row[0].strip()) > > to be nicer ;-) Yes me too, I'm gonna stick to that... :-) From steve.morin at gmail.com Thu Nov 17 16:21:23 2005 From: steve.morin at gmail.com (Steve) Date: 17 Nov 2005 13:21:23 -0800 Subject: Zope vs Php Message-ID: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> We are building a web app and the our backend is currently using python with php front end. We would like to do everything in python but php for our front end is so easy to use. We would like to use zope on our front end(no experience with it) can anyone provide any experience with this? >From what I can tell you can't just do <% #python code %> some title this is what we would like to do with session support and things that php provides? Steve From aahz at pythoncraft.com Tue Nov 1 13:14:24 2005 From: aahz at pythoncraft.com (Aahz) Date: 1 Nov 2005 10:14:24 -0800 Subject: Storing empties References: <1130539752.667045.183460@g14g2000cwa.googlegroups.com> <1h58k4p.12xd7rj1t5peh0N%aleaxit@yahoo.com> <1h5bepj.q0sqsnbqqgjrN%aleax@mail.comcast.net> Message-ID: In article <1h5bepj.q0sqsnbqqgjrN%aleax at mail.comcast.net>, Alex Martelli wrote: >Aahz wrote: >> In article <1h58k4p.12xd7rj1t5peh0N%aleaxit at yahoo.com>, >> Alex Martelli wrote: >>> >>>the canonical idiom when you need such distinction is: >>> >>>_not_there = object() >>>def foo(bar=_not_there, baz=_not_there, bap=_not_there): >>> if bar is _not_there: ... >>> >>>Other unique objects can be substituted for the 'sentinel', but I prefer >>>an empty "object()" because it has no other possible meaning except that >>>of a distinguishable, identifiable sentinel. IOW, you could set the >>>_not_there name to [] or {} or many other things, but that could be >>>slightly confusing for the reader (since the other things might have >>>other meanings and purposes) while 'object()' shouldn't be. >> >> What's your preferred idiom when you're dealing with storable objects? > >What's a "storable object"? You mean, something that can be pickled, or >passed to the .write method of a file object, or stored in a database, >or what else? Pickled and/or stored in a DB. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair From aisaac0 at verizon.net Mon Nov 21 14:52:12 2005 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 21 Nov 2005 19:52:12 GMT Subject: best cumulative sum References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> Message-ID: > Alan Isaac wrote: >> Like SciPy's cumsum. "Colin J. Williams" wrote in message news:rvngf.2987$gK4.200074 at news20.bellglobal.com... > Doesn't numarray handle this? Sure. One might say that numarray is in the process of becoming scipy. But I was looking for a solution when these are available. Something like: def cumreduce(func, seq, init = None): """Return list of cumulative reductions. Example use: >>> cumreduce(operator.mul, range(1,5),init=1) [1, 2, 6, 24] >>> :author: Alan Isaac :license: public domain """ if not seq: cr = [init]*bool(init) else: cr = [seq[0]] * len(seq) if init: cr[0] = func(cr[0],init) for idx in range(1,len(seq)): cr[idx] = func(cr[idx-1],seq[idx]) return cr From bokr at oz.net Fri Nov 18 13:19:54 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 18 Nov 2005 18:19:54 GMT Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> <1132249511.886027.93990@g14g2000cwa.googlegroups.com> <1h662eo.95qjyvd1bcnuN%aleax@mail.comcast.net> <437d0b86.63834689@news.oz.net> <1132325798.806457.91170@g47g2000cwa.googlegroups.com> Message-ID: <437e1784.132440599@news.oz.net> On 18 Nov 2005 06:56:38 -0800, "Anton Vredegoor" wrote: [...] >Pardon me, but I'm Anton, not Antoon (well maybe I am but lets keep >this distinction in order to avoid mental hash collisions) D'oh. I'm sorry. Please pardon _me_ ;-/ Regards, Bengt Richter From jmeile at hotmail.com Tue Nov 1 04:33:04 2005 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 01 Nov 2005 10:33:04 +0100 Subject: OpenSSL in Python In-Reply-To: References: <1130425810.431748.39660@g14g2000cwa.googlegroups.com> <1130808294.188603.169680@g47g2000cwa.googlegroups.com> Message-ID: <43673650.6070409@hotmail.com> >>First, is the PYTHON OpenSSL C wrapper what I need to get running. > > > I think that first you have to get OpenSSL running. Only then can you > think about wrapping it. I think Sybren is allright here. After installing openssl, pyopenssl won't be a problem. So, if you want to install openssl, you could download the binaries for windows (google for them) or you could compile it from source, which is the best approach for this kind of libraries. The last approach is out of the scope of this list as Sybren said. You should try first to find the answer in the openssl documentation or in its official list. Then if you aren't able to compile it, then you have to ask there. If on the other hand, you have already installed openssl, but the pyopenssl fails to run, then you can first see if pyopenssl has a mailing list and ask there. On the contrary, you can ask here. Regards, Josef From NOmanlio_perilloSPAM at libero.it Wed Nov 23 11:48:40 2005 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 23 Nov 2005 16:48:40 GMT Subject: strange behaviour when writing a large amount of data on stdout References: Message-ID: <7879o1t3acnq7dq9f60pspt6rhkpkbppsv@4ax.com> On Wed, 23 Nov 2005 14:59:45 +0100, "Fredrik Lundh" wrote: >Manlio Perillo wrote: > >> Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] >> on win32, Windows XP >> >> I have this problem: >> >>>>> n = 61409 + 1 >>>>> data = 'x' * n >> >>>>> print data >> >> Traceback (most recent call last): >> File "xxx", line xxx, in ? >> print data >> IOError: [Errno 12] Not enough space > >errno 12 is ENOMEM (that is, the system did not have enough memory >to finish an operation). > ... However I think the error message is not a good one. Better a "Not enough memory" >is the above a complete interpreter session? if it is, why did you xxx out >the filename () and line number? > I put these instructions in a script and executed it (from the console). The same problem with a complete interpreter session. Regards Manlio Perillo From __peter__ at web.de Sun Nov 20 07:22:35 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 20 Nov 2005 13:22:35 +0100 Subject: about polygon References: Message-ID: Shi Mu wrote: > Why I got a black polygon in the following code? > How can I make it no-color filled? > Thanks! > > import Tkinter > > c = Tkinter.Canvas(width=220, height=220) > c.pack() > c.create_polygon(60,60,100,60,100,100,60,120) > c.mainloop() You can set the color explicitly (use "" to denote transparency): c.create_polygon(60,60,100,60,100,100,60,120, fill="", outline="black") I don't know why that isn't the default. Peter From exarkun at divmod.com Wed Nov 9 14:50:03 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 9 Nov 2005 14:50:03 -0500 Subject: web interface In-Reply-To: Message-ID: <20051109195003.10365.1329267213.divmod.quotient.5859@ohm> On Wed, 9 Nov 2005 19:08:28 +0000, Tom Anderson wrote: >On Mon, 7 Nov 2005, Ajar wrote: > >> I have a stand alone application which does some scientific >> computations. I want to provide a web interface for this app. The app is >> computationally intensive and may take long time for running. Can >> someone suggest me a starting point for me? (like pointers to the issues >> involved in this, > >You're probably best off starting a new process or thread for the >long-running task, and having the web interface return to the user right >after starting it; you can then provide a second page on the web interface >where the user can poll for completion of the task, and get the results if >it's finished. You can simulate the feel of a desktop application to some >extent by having the output of the starter page redirect the user to the >poller page, and having the poller page refresh itself periodically. > >What you really want is a 'push' mechanism, by which the web app can >notify the browser when the task is done, but, despite what everyone was >saying back in '97, we don't really have anything like that. Yea, there's no way something like this will work: # push.tac from zope.interface import Interface, implements from twisted.internet import defer, reactor from twisted.application import service, internet from nevow import appserver, loaders, tags, rend, athena class ICalculator(Interface): def add(x, y): """ Add x and y. Return a Deferred that fires with the result. """ class Adder(object): implements(ICalculator) def add(self, x, y): # Go off and talk to a database or something, I don't know. We'll # pretend something interesting is happening here, but actually all # we do is wait a while and then return x + y. d = defer.Deferred() reactor.callLater(5, d.callback, x + y) return d class LongTaskPage(athena.LivePage): docFactory = loaders.stan(tags.html[ tags.head[ tags.directive('liveglue'), tags.title['Mystical Adding Machine of the Future'], tags.script(type="text/javascript")[""" /* onSubmit handler for the form on the page: ask the server * to add two numbers together. When the server sends the * result, stick it into the page. */ function onAdd(x, y) { var d = server.callRemote('add', x, y); var resultNode = document.getElementById('result-node'); d.addCallback(function(result) { resultNode.innerHTML = String(result); }); d.addErrback(function(err) { var s = "Uh oh, something went wrong: " + err + "."; resultNode.innerHTML = s }); resultNode.innerHTML = "Thinking..."; return false; }""", ], ], tags.body[ tags.form(onsubmit="return onAdd(this.x.value, this.y.value);")[ tags.input(type="text", name="x"), "+", tags.input(type="text", name="y"), "=", tags.span(id="result-node")[ tags.input(type="submit"), ], ], ], ]) class Root(rend.Page): docFactory = loaders.stan(tags.html[ tags.head[ tags.meta(**{"http-equiv": "refresh", "content": "0;calc"})]]) def child_calc(self, ctx): return LongTaskPage(ICalculator, Adder()) application = service.Application("Push Mechanism, like back in '97") webserver = internet.TCPServer(8080, appserver.NevowSite(Root())) webserver.setServiceParent(application) # eof Right? But maybe you can explain why, for those of us who aren't enlightened. Jean-Paul From fredrik at pythonware.com Sun Nov 27 04:48:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Nov 2005 10:48:22 +0100 Subject: Syntax References: <1133065081.696769.32570@z14g2000cwz.googlegroups.com> <20051127000528.7b86d1f5@samwise.anansi> Message-ID: Terry Hancock wrote: > > I don't think there are any *security* reasons, but > > stylistically, "import os" is greatly preferred. When > > someone else reads your code, they will immediately know > > where getcwd() comes from. > > It's not a question of "security" in the usual sense, but > the first syntax imports a lot of stuff into the current > namespace, increasing the risk of unintentionally clobbering > local names. So it's certainly "riskier" in the sense of > "likely to cause bugs". or just "likely to result in confusing error messages". >>> from os import * >>> f = open("myfile.txt", "r") Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required From mwm at mired.org Wed Nov 9 14:54:24 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 09 Nov 2005 14:54:24 -0500 Subject: Invoking Python from Python References: <1131466225.744361.7010@z14g2000cwz.googlegroups.com> <86acgeaagx.fsf@bhuda.mired.org> Message-ID: <86slu58umn.fsf@bhuda.mired.org> claird at lairds.us (Cameron Laird) writes: > I'll rein myself in and suggest an even easier introduction > to this subject: configuration files. RARELY is the correct > answer to create a new syntax, although many development > organizations give the impression that's their first choice. > ".ini"-speak is a safe-enough choice. Most interesting, > though, is to interpret Python or some subset as a configu- > ration specification, so that one has immediately not just > HOME = "/some/folder" > STEP_LIMIT = 16 > but > pool_size = cpu_count * 30 > and even > if today == "Sunday": > total_process_maximum = 8 > available in the configuration language. Neat, eh? I once carried this a step further, and used methodless classes as a configuration mechanism: class PlainFoo: # Values for a plain foo class FancyFoo(PlainFoo): # Overrides for just the things that are different The program that used this created needed lots of objects, in a variety of different flavers that were literally specified as "Just like PlainFoo, but with ...". Doing it this way made configuring things trivial. At the time, I attached "configuration variables" to instances. If I were going to do it today, I'd look into making the parent classes of the class that implements Foo dynanmic. plwm (an X11 window manager - sort of - built in top of python-xlib) carries this another step further. You configure your window manager by creating a subclass of the WindowManager (or other) class that mixes in the features you want, and sets the attributes to control specific features. It's very flexible - but at this point, the "configuration file" is a Python program, and not really suitable to use by non-programmers. > But if configuration is *that* powerful, then it can also > do great damage. How does one make Python interpretation safe? > That's a subject for another day. We're all waiting for this, somewhat impatiently :-). http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bonono at gmail.com Fri Nov 25 01:39:10 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 22:39:10 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <1132899059.919842.74190@f14g2000cwb.googlegroups.com> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> Message-ID: <1132900750.956510.16320@o13g2000cwo.googlegroups.com> bonono at gmail.com wrote: > Mike Meyer wrote: > > "bonono at gmail.com" writes: > > > Christoph Zwerschke wrote: > > >> jepler at unpythonic.net schrieb: > > >> > You can already get a set from a dictionary's keys in an efficient manner: > > >> >>>>l = dict.fromkeys(range(10)) > > >> >>>>set(l) > > >> > Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > > >> Good point. I expected that set(l) = set(l.items()) and not > > >> set(l.keys()), but the latter would not work with mutable values. See > > >> discussion with Martin. > > > puzzled. items() return tuples which I believe can be element of set ? > > > Or I misread you ? > > > > Not all tuples can be elements of a set. Elements of a set have to be > > hashable. Tuples compute their hash by hashing their contents. If > > their contents aren't hashable, the tuple isn't hashable, and hence > > can't be an element of a set. If the values in the dictionary aren't > > hashable, then the tuples returned by items() won't be hashable > > either, and hence can't be elements of a set. > > > A related issue, from the doc : > > Set elements are like dictionary keys; they need to define both > __hash__ and __eq__ methods. > > and dir(any_tuple) would show __hash__ and __eq__, would that be a bit > confusing as even though tuple has these two properties(or whatever > terms it should be called), it really depends what it contains ? > > Or in other words, tuple is hashable if and only if every object it > contains is also hashable ? > > If that is the case, would it be better to correct the doc to say such > thing ? And this, again from the doc(about mapping objects): A mapping object maps immutable values to arbitrary objects. Seems that is questionable too. a=(1,[]) d={} d[a]=1 again would give TypeError, list object are unhashable. From suma_37 at yahoo.com Mon Nov 7 05:37:18 2005 From: suma_37 at yahoo.com (sumi) Date: 7 Nov 2005 02:37:18 -0800 Subject: help-I am new to python, I have some query could sombody help me out. Message-ID: <1131359838.022430.12160@g14g2000cwa.googlegroups.com> I am very new to python , I have small query could some one help me. every time I get a new load i need to do few things like creating some dir, changing some file contents and moving some files , i would like to know if i can write a python script to do all these operation . From luismgz at gmail.com Tue Nov 8 12:31:09 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 8 Nov 2005 09:31:09 -0800 Subject: which feature of python do you like most? In-Reply-To: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: <1131471069.943024.190440@g44g2000cwa.googlegroups.com> I've never used Perl, but I know other c-like laguages, and I can tell you what I like about python: - It is concise, clear and to the point. - No useless characters like curly braces and semicolons cluttering it syntax,. - Very readable and elegant. - One obvious way to do each task, not thousands (easier to learn, easier to remember), and this way is shorter, easier and more straightforward than any other. - Great built-in data structures. - And all of its features, but very specially, list comprehensions and slicing. I can't live without them! From yaipa at yahoo.com Thu Nov 3 21:23:50 2005 From: yaipa at yahoo.com (yaipa) Date: 3 Nov 2005 18:23:50 -0800 Subject: putting an Icon in "My Computer" Message-ID: <1131071030.209405.37800@z14g2000cwz.googlegroups.com> All, I've been asked by my boss to put an Icon in WinXP's "My Computer" for a utility we use around the shop. My tool of choice is of course Python and therefore what I am using to attempt my given task. I have no trouble putting Icons in the WinXP Toolbar using Python, but have totally failed to get an Icon to appear in My Computer. Any Idea on why and maybe how to get around this using Python? Thanks, Alan From jack at performancedrivers.com Mon Nov 28 18:56:39 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 28 Nov 2005 18:56:39 -0500 Subject: Looking for small, impressive 3D-related Python script In-Reply-To: <28E540BB-4A56-46CD-8351-68E642E948EF@sbcglobal.net> References: <28E540BB-4A56-46CD-8351-68E642E948EF@sbcglobal.net> Message-ID: <20051128235639.GB7517@performancedrivers.com> On Mon, Nov 28, 2005 at 04:44:56PM -0600, Kenneth McDonald wrote: > I'm not trying to persuade my company to offer Python as a scripting > language for their product, but I am trying to give them examples of > things that Python can do easily that cannot be done easily with > their current proprietary scripting language. After that it would be > their decision. As the product is a 3D package, I'm looking for > something in this field. > > This does _not_ have to use PyOpenGL, or for that matter, any Python > 3D package. In fact, my ideal would be a Python script that simply > uses L-Systems (Lindenmayer systems) as in "The Algorithmic Beauty of > Plants", to generate plantlike OBJ files that can then be displayed > in our program. In general, something that generates an OBJ file > would probably be preferable to something that actually uses > PyOpenGL, Blender, etc, as then I can just display the OBJ file in > our program to say, "This is the sort of thing that can be easily > done by Python without recourse to any other programs". A quick google on "obj 3d python" brings up cgkit which has a tutorial page: http://cgkit.sourceforge.net/tutorials/ It state it can export in OBJ format. -jackdied From paul at boddie.org.uk Mon Nov 7 20:58:51 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Nov 2005 17:58:51 -0800 Subject: Web automation References: <1131040806.950444.210350@g49g2000cwa.googlegroups.com> <1131397945.832762.71070@g47g2000cwa.googlegroups.com> <86k6fk9k6v.fsf@bhuda.mired.org> Message-ID: <1131415131.676626.7730@g49g2000cwa.googlegroups.com> Mike Meyer wrote: > qwwee... at yahoo.it writes: > > but I supposed the everyone knew that web automation (and in general > > "automation") is only a problem in Linux. > > I don't know it. I don't believe it, either. I automate web tasks on > Unix systems (I don't use many Linux systems, but it's the same tool > set) on a regular basis. I imagine that "Web automation" is taken here to mean the automation of Web browsers, with all the advantages/issues such an approach entails. The problem on non-Windows systems is the lack of a common (or enforced) technology for exposing application object models: Mozilla has XPCOM which apparently doesn't permit the exposure of enough useful functionality to other processes for "Web automation" tasks (and whose components seem bizarre enough to defeat my casual investigations into automation with in-browser components), whilst Konqueror/KHTML is somewhat accessible via DCOP although the interfaces to much of KDE are somewhat limited. Taking the challenge on board, I decided to build on the existing KPart plugin work done with PyKDE [1] and produce a component which exposes active documents using DCOP [2]. Combined with an extended version of qtxmldom [3] the result is a system which permits out-of-process automation of KHTML and thus Konqueror with the documents available using a PyXML-style DOM. Currently, the work is in an early phase and there's a lot of learning about DCOP and PyKDE to be done, but I think the concept is more or less worked out. If only GNOME and KDE had stuck with CORBA, though... :-/ Paul P.S. Of course, the existing KPart plugins permit in-browser embedding which is easily good enough for many automation tasks, and there are plenty of examples of moderately useful tools and scripts to prove this point. In the revised plugins collection [2], there's a plugin which extracts hCalendar information, for example. [1] http://www.boddie.org.uk/david/Projects/Python/KDE/index.html [2] http://www.boddie.org.uk/python/kpartplugins.html [3] http://www.boddie.org.uk/python/qtxmldom.html From baudelaire_2c at yahoo.fr Fri Nov 4 18:22:34 2005 From: baudelaire_2c at yahoo.fr (N. Pourcelot) Date: Sat, 05 Nov 2005 00:22:34 +0100 Subject: exec behaviour In-Reply-To: References: <436b8ed9$0$7577$626a54ce@news.free.fr> Message-ID: <436bed3b$0$32423$636a15ce@news.free.fr> Thanks for you reply. I added locals() to my exec statment, so it worked, but I wasn't so sure about my interpretation of the problem. Fredrik Lundh wrote: > N. Pourcelot wrote: > > >>I can't understand some specific behaviour of the exec statment. >> >>For example, say that I create such a class A : >> >>class A: >> def __init__(self): >> self.n = 3 >> self.m = None >> def h(self, ini): >> n = self.n >> m = self.m >> if ini: exec("def m(x): return n+x"); self.m=m >> else: m(7) >> >>Now : >>obj = A() >>obj.h(1) >>obj.h(0) >> >>I get : >> >>Traceback (most recent call last): >> File "", line 1, in ? >> File "", line 9, in h >> File "", line 1, in m >>NameError: global name 'n' is not defined > > > exec only supports local and global scopes; the "n" inside the exec statement > is a not a local, so it's assumed to be a global variable. > > (Python's lexical scoping requires the compiler to look for free variables in inner > scopes before generating code for the outer scope; it cannot do that for exec, for > obvious reasons). > > > > > From google at alankemp.com Tue Nov 22 23:02:28 2005 From: google at alankemp.com (Alan Kemp) Date: 22 Nov 2005 20:02:28 -0800 Subject: Accessing a database from a multithreaded application Message-ID: <1132718548.824776.130760@g44g2000cwa.googlegroups.com> Hi, I have a problem that is half python, half design. I have a multithreaded network server working, each client request spawns a new thread which deals with that client for as long as it is connected (think ftp style rather than http style connections here). Each thread gets passed a reference to the main server to access things like the list of connected clients, global data, etc. Now I want to add a database to store usernames and other user data. I grabbed a copy of pysqlite2 which I have used successfully in the past in single-threaded applications. My initial plan was for the server to create a single connection and cursor and then just use some sort of mutex to control access to it from the various threads. However, apparently you can only access the cursor from the thread on which it was created... Can someone suggest a better (ie, valid) strategy for this? Should I be using a Queue to make a list of db requests/results to get accross the thread boundary (erg, that sounds nasty)? Should each client thread create its own connection/cursor to the database? Would that even work, wont there be locking issues? Any suggestions or pointers in the direction of more information would be greatly appreciated. Thanks for your time, Alan From dduerrenmatt at swissonline.ch Fri Nov 18 16:38:08 2005 From: dduerrenmatt at swissonline.ch (David Duerrenmatt) Date: Fri, 18 Nov 2005 22:38:08 +0100 Subject: func(*params) Message-ID: Hi there For some reasons, I've to use Python 1.5.2 and am looking for a workaround: In newer Python versions, I can call a function this way: func = some_function func(*params) Then, the list/tuple named params will automatically be "expanded" and n=len(params) arguments will be submitted. Python 1.5.2 doesn't support this kind of function call. I could use some workaround like: func(params[0],params[1]...) but since the number of items in params varies and depends on the mapped function "some_function", this isn't a good solution. Another idea is to use exec(), don't know whether this is safe... Any recommondations or tricks? Thanks, david From fredrik at pythonware.com Thu Nov 24 05:40:37 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Nov 2005 11:40:37 +0100 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org><86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: Neil Hodgson wrote: > Yes, the rule has obvious shortcomings, but OTOH if it had enabled > reasonable formal verification... I somehow find it hard to believe that you could write a multi-exit function that cannot be trivially and automatically converted to a single-exit function, for further analysis... From steve at holdenweb.com Wed Nov 23 11:33:24 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Nov 2005 16:33:24 +0000 Subject: wxPython Licence vs GPL In-Reply-To: References: Message-ID: John Perks and Sarah Mount wrote: > we have some Python code we're planning to GPL. However, bits of it were > cut&pasted from some wxPython-licenced code to use as a starting point > for implementation. It is possible that some fragments of this code > remains unchanged at the end. > Whether or not some fragments of code remain unchanged at the end of your project, if you start out with a piece of source code lifted from wxPython then what you have created is definitely a "derivative work" and, as such, you must take into account the wxPython license in your licensing of the derivative work. > How should we refer to this in terms of copyright statements and bundled > Licence files? Is there, say, a standard wording to be appended to the > GPL header in each source file? Does the original author need to be > named as one of the copyright holders, or that ours is a derivative work > from his? Which of these would be required under the terms of the > Licence, and which by standard practice / courtesy? > You'll have to read the wxPython license in order to find out the answer to that question. > (This assumes the wxPython Licence is compatible with the GPL -- if not, > do we just cosmetically change any remaining lines, so none remain from > the orignal?) > That won't stop your code from being a derivative work. You'll need to take licensing and copyright issues a little more seriously before you release anything. 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 martin at v.loewis.de Fri Nov 11 20:15:29 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 12 Nov 2005 02:15:29 +0100 Subject: weird problem with os.chmod In-Reply-To: References: <43753C13.2010609@colannino.org> Message-ID: <43754232$0$1145$9b622d9e@news.freenet.de> James Colannino wrote: > Ok, so further research revealed that 0600 is actually the octal > representation for 384 (which makes sense.) So then, I guess my > question would have to be, is there a way for me to make Python aware > that the 0600 I'm passing to int() is octal and not decimal so that I > will get 384 instead of 600? Try this: http://docs.python.org/lib/built-in-funcs.html#l2h-39 Regards, Martin From codecraig at gmail.com Thu Nov 17 08:41:01 2005 From: codecraig at gmail.com (py) Date: 17 Nov 2005 05:41:01 -0800 Subject: How to - import code not in current directory In-Reply-To: <3u3fddFurbi3U2@individual.net> References: <1132233527.222443.139470@g14g2000cwa.googlegroups.com> <3u3fddFurbi3U2@individual.net> Message-ID: <1132234860.961767.209600@z14g2000cwz.googlegroups.com> Claudio Grondi wrote: > so this should work in your case: > > import sys > sys.path.append("C:\some\other\directory") > import bar ...that will certainly work. Only issue is that each time I start up foo.py in the python shell I have to retype those three lines....kind of why I was hoping for a environment variable or path setting that i could stick in. This will do for now... From antonyliu2002 at yahoo.com Tue Nov 29 18:17:18 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Tue, 29 Nov 2005 15:17:18 -0800 (PST) Subject: Problem with the maxent package Message-ID: <20051129231718.379.qmail@web35801.mail.mud.yahoo.com> First of all, thank all of you who guided me through the readline library for enabling bash-like python interpreter. This has been taken care of nicely. I am trying to use the maxent package written by Zhang Le from here: http://homepages.inf.ed.ac.uk/s0450736/maxent_toolkit.html#download The binary package gives me error messages when I tried calling it from my python script. Then I attempted to compile the source code of the maxent packatge, only to find this: [antony at goofy maxent-20041229]$ ... ... checking for main in -lz... yes checking for main in -lg2c... no libg2c not found, this should be shipped with GNU Fortran compiler. configure gives up. [antony at goofy maxent-20041229]$ [antony at goofy maxent-20041229]$libg2c /usr/lib/libg2c.so.0.0.0 /usr/lib/libg2c.so.0 [antony at goofy maxent-20041229]$ I don't know how to let the installation know the path of the libg2c library. Anyone know how to go about this please? Thanks. __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From skip at pobox.com Mon Nov 21 13:42:14 2005 From: skip at pobox.com (skip at pobox.com) Date: Mon, 21 Nov 2005 12:42:14 -0600 Subject: ignore specific data In-Reply-To: <1132596504.619762.237610@g47g2000cwa.googlegroups.com> References: <1132596504.619762.237610@g47g2000cwa.googlegroups.com> Message-ID: <17282.5382.820636.561054@montanaro.dyndns.org> pkilambi> I would like to ignore a block of lines and consider the pkilambi> rest.. so if the block starts with pkilambi> "start of block............." pkilambi> fjesdgsdhfgdlgjklfjdgkd pkilambi> jhcsdfskdlgjkljgkfdjkgj pkilambi> "end of block" pkilambi> I want to ignore this while processing the file .This block pkilambi> could appear anywhere in the file.It could at the start or end pkilambi> or even middle of file content. How about (untested): class FilterBlock: def __init__(self, f, start, end): self.f = f self.start = start self.end = end def __iter__(self): return self def next(self): line = self.f.next() if line == self.start: line = self.f.next() while line != self.end: line = self.f.next() return line Then use it like filterfile = FilterBlock(open("somefile", "r"), "start of block..........", "end of block") for line in filterfile: process(line) I'm not sure what you mean by all the dots in your start of block line. If "start of block" can be followed by other text, just use if line.startswith(self.start): instead of an exact comparison. Skip From could.net at gmail.com Tue Nov 1 10:12:03 2005 From: could.net at gmail.com (could ildg) Date: Tue, 1 Nov 2005 23:12:03 +0800 Subject: hello, I want to change n bytes of a binary file In-Reply-To: References: <311b5ce10511010648y33063589se0dbd5281b29af4e@mail.gmail.com> Message-ID: <311b5ce10511010712r7c1d1b1fia3bc4787fe6e0775@mail.gmail.com> On 11/1/05, Fredrik Lundh wrote: > > "could ildg" wrote: > > > I want to encrypt a very large birany file, > > but if to change the whole file, it will take very long time, > > so I just want to change n(n is an int) bytes of the file. > > but when I turned to the file I/O of python, I found that file object > can > > only read and write strings, > > so how can I do the binary stuff? > > 8-bit strings contain bytes. > > > I want a encrypt function like below: > > def encrypt(filename,n): > > f = open(filename,"rb+") > > > a=f.read(n) > > b = encrypt(a) ^^^^^^^^Thank you~~,but where is the encrypt defined? f.seek(0) # rewind > f.write(b) > f.close() > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mail.comcast.net Fri Nov 18 21:37:35 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Fri, 18 Nov 2005 18:37:35 -0800 Subject: Confused about namespaces References: <1132355063.709395.92580@g44g2000cwa.googlegroups.com> <1132356583.703129.241070@g47g2000cwa.googlegroups.com> <1132358984.915609.306380@g44g2000cwa.googlegroups.com> <1132362337.808127.248870@g14g2000cwa.googlegroups.com> Message-ID: <1h68jg8.1v3kx72f4i1jzN%aleax@mail.comcast.net> KvS wrote: > > There's no reason not to just "import wx" if you want that. > > Yes, that's clear. But if you would make some huge application that has > a large number of nested modules, each importing the former one, then > avoiding the use of "from ... import *" would mean that you have to use > long references like foo1.foo2.... to get to the lowest modules plus Not at all -- you may perfectly well "import a.b.c.d as e" and use e as the reference throughout the importing module. But the point is, modules should be MODULAR (duh) -- if I 'import x' I should NOT rely on what x itself imports (and so on transitively), just on what x ``exports'', so to speak, at its TOP level. The Law of Demeter in its simplified form "if you have more than one dot in your reference you're doing things wrong" applies. In fact, the many-dots form of module naming is intended for nested PACKAGES, *NOT* for "modules which import each other". > that you'd have to check each module for imports outside this tree. Why would you have to check any module for such "outside imports"? I don't see the need for any checks. If you just simply forget the very _existence_ of "from X import *", your Python code can only grow better as a result. I earnestly hope it disappears come Python 3.0 time... Alex From fairwinds at eastlink.ca Mon Nov 14 14:03:55 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Mon, 14 Nov 2005 15:03:55 -0400 Subject: Dictionary of tuples from query question In-Reply-To: Message-ID: <67370C2F-5541-11DA-AE36-000A27B3B070@eastlink.ca> Thanks Fredrik for your help. Really short and efficient - very nice! Regards, David On Monday, November 14, 2005, at 12:12 PM, Fredrik Lundh wrote: > I meant to write > > d = {} > for index, record in enumerate(cursor.fetchall()): > d[index+1] = tuple(record) > > which can be shorted to > > d = dict((k+1, tuple(v)) for k, v in enumerate(x)) > > in recent versions of Python. From nehortle at schaelec.com.au Tue Nov 29 06:30:15 2005 From: nehortle at schaelec.com.au (Hortles) Date: Tue, 29 Nov 2005 22:30:15 +1100 Subject: No subject Message-ID: hello, I have just downloaded the mac os x version of python and when i open the PythonIDE it just quits straight away. Is there something I'm am doing wrong. Thanks, Allan From bonono at gmail.com Sun Nov 20 11:31:20 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 08:31:20 -0800 Subject: Underscores in Python numbers In-Reply-To: References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: <1132504280.760237.132540@z14g2000cwz.googlegroups.com> D H wrote: > Steve Holden wrote: > > David M. Cooke wrote: > >> One example I can think of is a large number of float constants used > >> for some math routine. In that case they usually be a full 16 or 17 > >> digits. It'd be handy in that case to split into smaller groups to > >> make it easier to match with tables where these constants may come > >> from. Ex: > >> > >> def sinxx(x): > >> "computes sin x/x for 0 <= x <= pi/2 to 2e-9" > >> a2 = -0.16666 66664 > >> a4 = 0.00833 33315 > >> a6 = -0.00019 84090 > >> a8 = 0.00000 27526 > >> a10= -0.00000 00239 > >> x2 = x**2 > >> return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10)))) > >> > >> (or least that's what I like to write). Now, if I were going to higher > >> precision, I'd have more digits of course. > >> > > Right, this is clearly such a frequent use case it's worth changing the > > compiler for. > > Yes it is. > In that one example he used digit grouping 5 more times than I've > used lambda in my life. Remember people use python as a data format as > well (see for example JSON). > It's a simple harmless change to the parser: ignore underscores or > spaces in numeric literals. As others have mentioned, Ruby supports > this already, as do Ada, Perl, ML variants, VHDL, boo, nemerle, and others. But that requirement can be served easily with something like this : a2=my_decimal("-0.16666 66664") From stefan.arentz at gmail.com Fri Nov 4 03:24:16 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 04 Nov 2005 09:24:16 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: <87acgku8gf.fsf@keizer.soze.com> Antoon Pardon writes: ... > > Ah yes. Well, good luck with that. You seem to have decided that it is not > > sane and who am I to argue with that. It depends on your state of mind :-) > > I can just say the opposite, that you seem to have decided that it is > sane. I have. I like the Python model. > > The model makes sense in my opinion. If you don't like it then there are > > plenty of other languages to choose from that have decided to implement > > things differently. > > And again this argument. Like it or leave it, as if one can't in general > like the language, without being blind for a number of shortcomings. Personally I don't see it as a shortcoming. > It is this kind of recations that make me think a number of people is > blindly devoted to the language to the point that any criticism of > the language becomes intollerable. No not at all. Just look at all the PEPs and the changes in the language that have been made in the past. Python is very much community driven and that shows in it's progress. You on the other hand keep talking about emo things like 'sane' and 'madness' without giving any technical backing about these problems that you are having with the language. Snap out of that, make it a real discussion and maybe something good will happen. Or not :-) S. From aleax at mail.comcast.net Wed Nov 23 23:20:02 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 20:20:02 -0800 Subject: (newbie) N-uples from list of lists References: <1132776015.567869.214570@g14g2000cwa.googlegroups.com> <1132799696.603772.323700@g44g2000cwa.googlegroups.com> <1132801693.407770.215630@g43g2000cwa.googlegroups.com> <1h6huuv.3o2ah01wodl9qN%aleax@mail.comcast.net> <1132804276.718930.221680@g14g2000cwa.googlegroups.com> Message-ID: <1h6hxos.14d030f1yqkcdbN%aleax@mail.comcast.net> bonono at gmail.com wrote: ... > > An example of recursion elimination in Python can be found at > > > > > Thanks, so it seems that it is only doing the "stacking" oneself rather > than relies on the recursive calls(which does the stack for you). Or in > other worlds, a way to get around the recursion limitation but seems to > be harder to understand in this case. Yep, that's recursion elimination for you -- once in a while it will guide you to a "truly" nonrecursive solution that you had not considered, but mostly it's just an optimization (in almost ANY language, generally -- recursion in most languages stacks up everything whether it needs to or not, with elimination you get to stack up the minimal needed amount of state, so it can be faster) fully including the "obfuscation" typical of optimizations;-) Alex From david.bear at asu.edu Tue Nov 22 23:05:06 2005 From: david.bear at asu.edu (David Bear) Date: Tue, 22 Nov 2005 21:05:06 -0700 Subject: email module documentation Message-ID: <1391261.ocLkZXfqrF@teancum> I'm confused about how to use the email module in python 2.4.x I'm using python packaged with suse 9.3. >From the module documetation at http://docs.python.org/lib/node597.html I found the following example (items cut): import email ... msg = email.message_from_file(fp) .. Yet, when I try this I get the message Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'message_from_file' so I dir(email) reveals: ['__builtins__', '__doc__', '__file__', '__name__', 'cStringIO', 'email', 'getMessage', 'sys'] This is nothing like the documentation on python.org. Any idea what I am missing? -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From bobueland at yahoo.com Sun Nov 20 04:16:33 2005 From: bobueland at yahoo.com (bobueland at yahoo.com) Date: 20 Nov 2005 01:16:33 -0800 Subject: Where can I find string.translate source? References: <1132472291.390282.82380@g43g2000cwa.googlegroups.com> Message-ID: <1132478193.158337.204710@f14g2000cwb.googlegroups.com> Thanks Mike and Fredrik. In my Python installation there is no directory called Objects. I use Windows and I downloaded Python from http://www.python.org/download/ As I looked closer I saw that the link # Python 2.4.2 Windows installer (Windows binary -- does not include source) which clearly says that it doesn't include source. So in order to see the source I had to download # Python 2.4.2 source (for Unix or OS X compile) And in that download there is a directory called Objects and there is file called stringobjects.c where one can find the implementation of translate. From fredrik at pythonware.com Tue Nov 15 17:51:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Nov 2005 23:51:18 +0100 Subject: Default method arguments References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com><437a1e7a$0$6131$636a15ce@news.free.fr> Message-ID: Steven D'Aprano wrote: >> Another solution to this is the use of a 'marker' object and identity test: >> >> _marker = [] >> class A(object): >> def __init__(self, n): >> self.data =n >> def f(self, x = _marker): >> if x is _marker: >> x = self.data >> print x > > I would like to see _marker put inside the class' scope. That prevents > somebody from the outside scope easily passing _marker as an argument to > instance.f. if you don't want people to be able to easily pass _marker as an argument to the f method, you probably shouldn't use it as the default value. From cito at online.de Wed Nov 23 14:54:45 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 20:54:45 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> References: <1132733531.265895.71900@g49g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com schrieb: > It seems to be though as "ordered dictionary" are slowly to be confined > to only "ordered on order of change to the dictionary". "Ordered dictionary" means that the keys are not an ordinary set like in an ordinary dictionary, but an "ordered set." I think this definition is pretty straightforward and common. An ordered set is the same as a unique list, i.e. a list where all elements are unique. When there is automatical ordering using a comparison function, I would not speak of an "ordered directory", but of a "sorted directory." This would be basically a dictionary plus a comparison function. The keys would always be iterated in the order given by the comparison function. It would be nice to have a sorted dictionary as well, even if you can achieve the same by calling the sorted built-in on the keys. Think of a sorted directory as a subclass of ordered directories. Implementing it that way would even have perfomance benefits if the keys are inserted using the bisect algorithm. This is better than calling sorted() on the keys of an ordinary dictionary many times. By the way, you will find the same terminology in Smalltalk, where "SortedCollection" is a subclass of "OrderedCollection". -- Christoph From *firstname*nlsnews at georgea*lastname*.com Fri Nov 4 13:40:53 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Fri, 04 Nov 2005 18:40:53 GMT Subject: when and how do you use Self? References: Message-ID: <*firstname*nlsnews-E00C3A.13405504112005@news.verizon.net> In article , "Tieche Bruce A MSgt USMTM/AFD" wrote: > I am new to python, > Could someone explain (in English) how and when to use self? > I have been reading, and haven't found a good example/explanation is a good explanation of just about all of Python. You should read it. It explains when to use "self". ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From nyamatongwe+thunder at gmail.com Sat Nov 19 19:55:36 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 20 Nov 2005 00:55:36 GMT Subject: path module / class In-Reply-To: <8u6dnWEcZ6-6AuPeRVn-gg@powergate.ca> References: <1132164123.917694.255200@o13g2000cwo.googlegroups.com> <8u6dnWEcZ6-6AuPeRVn-gg@powergate.ca> Message-ID: Peter Hansen: > Compelling to whom? I wonder if it's even possible for Guido to find > compelling anything which obsoletes much of os.path and shutil and > friends (modules which Guido probably added first and has used the most > and feels most comfortable with). To me, most uses of path.py are small incremental improvements over os.path rather than being compelling. Do a number of small improvements add up to be large enough to make this change? There is a cost to the change as there will be two libraries that have to be known to understand code. Does someone have an example application that moved to path.py with a decrease in errors or noticeable decrease in complexity? Could all path manipulation code be switched or is coverage incomplete? The duplication argument should be answered by looking at all the relevant modules and finding a coherent set of features that work with path.py without overlap so that the obsolete methods can be deprecated. If adding path.py leads to a fuzzy overlapping situation where os.path is occasionally useful then we are complicating the user's life rather than simplifying it. Neil From leszczynscyno at spamyaho.ocom Sat Nov 5 18:09:16 2005 From: leszczynscyno at spamyaho.ocom (Andy Leszczynski) Date: Sat, 05 Nov 2005 17:09:16 -0600 Subject: pickle - recursion - stack size limit - MS windows Message-ID: I need to pickle quite complex objects and first limitation was default 200 for the recursion. sys.setrecursionlimit helped, but still bigger objects fail to be pickled because of XP stack size limitation. Any idea how to get around the problem ... A. From sjdevnull at yahoo.com Thu Nov 10 12:36:43 2005 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 10 Nov 2005 09:36:43 -0800 Subject: Pythonising the vim (e.g. syntax popups) -> vimpst In-Reply-To: References: <200511091609.09613.email@christoph-haas.de> <200511100052.01043.r.roelofsen@tuxed.de> Message-ID: <1131644203.723980.185230@f14g2000cwb.googlegroups.com> Christoph Haas wrote: > But Vim scripting looked even evil for me... and > I've been working with Perl for a decade. :) Vim scripting is nasty, but thankfully you don't really need to use it any more. You can write all your code in python with just a one-line hook to map it to a key. On the topic, I did something like this that you might find handy; the end result is that if you type a = myfunc( then the arguments for myfunc are displayed in the status line. If you hit , then the full python docs (if any) are shown (I'm working on having that show surrounding comments/docstrings for followed functions, but that code is busted up something awful at the moment and I haven't gone back to look at it). It's a complete work in progress, it could be terribly broken. I'll try to get it more polished/functional and put it up on sourceforge or somewhere. The order of lookups for prototypes is as follows: 1. Try to follow tags; if there is a tag, grab the line in question (and any further lines until reaching a ":"). 2. Failing that, look in a help dictionary; I generated mine from the info version of the Python docs, using a simple Python script. 3. Fail and show nothing. A couple of caveats: 1. This uses the command area. So you either need to turn off "showmode" or set "cmdheight" to 2 or more; otherwise, the help text will be clobbered immediately by the INSERT prompt. 2. The help dictionary is a dumb idea, it should be in a gdbm file or something--right now it increases the size of a running gvim by 600KB or so after the first time I use the help function (and that first lookup is slow) because it's reading it a huge chunk of the vim docs. 3. The code abuses the preview window, which I don't care about because I never use the preview window for anything else. I would expect that the user-visible effect of this will be to close any preview windows you have open any time you type an open-paren. 4. It really works best in gvim; in a command-line vim it may recenter your windows and have other jumpiness. I tried for a while to figure out a workaround and gave up. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Vim code (put in ~/.vimrc) function! DocParen() py vimrc.print_help() return "(" endfunction inoremap :echo b:helpString inoremap ( =DocParen():echo b:shortHelp Python code (put in ~/.vim/vimrc.py) import vim def cur_x(): return vim.current.window.cursor[1] def cur_y(): return vim.current.window.cursor[0] def snag_help(current): vim.command("let v:errmsg=''") vim.command("silent! ptag %s"%current) if vim.eval("v:errmsg"): return "" vim.command("silent! winc P") help = vim.current.line.strip() if help.startswith("def") or help.startswith("class"): while not vim.current.line.strip().endswith(":"): vim.command("+") help = help + " "+vim.current.line.strip() try: help = help.split("def ", 1)[1] except: pass if help.endswith(":"): help = help[:-1] vim.command("silent! winc p") vim.command("silent! winc z") return help def print_help(): global docDict if not docDict: import pyhelp docDict = pyhelp.docDict currWord = vim.current.line.strip() for ch in " .": try: currWord = currWord.split(ch)[-1] except: pass help snag_help(currWord) if not help: try: help = docDict[currWord] except: help = "" if help.find("(self, ") > 0: help=help.replace("(self, ", "(") if '"' in help: help=help.replace('"', '\\"') shortHelp = help if len(vim.windows) == 1: truncate = vim.current.window.width-20 else: truncate = int(vim.eval("&columns")) -1 if len(help)>truncate: shortHelp=help[:truncate] vim.command('let b:helpString="%s"'%help) vim.command('let b:shortHelp="%s"'%shortHelp) From donald.welch at hp.com Tue Nov 29 15:43:14 2005 From: donald.welch at hp.com (dwelch) Date: Tue, 29 Nov 2005 12:43:14 -0800 Subject: newbie question concerning formatted output In-Reply-To: References: Message-ID: <438cbda5$1@usenet01.boi.hp.com> Thomas Liesner wrote: > Hello all, > > i am having some hard time to format the output of my small script. I am > opening a file which containes just a very long string of hexdata > seperated by spaces. Using split() i can split this string into single > words and print them on stdout. So far so good. But i want to print always > three of them in a single line and after that a linebreak. > > So instead of: > > 3905 > 3009 > 0000 > 4508 > f504 > 0000 > 3707 > 5a07 > 0000 > etc... > > i'd like to have: > > 3905 3009 0000 > 4508 f504 0000 > 3707 5a07 0000 > etc... > > This is the codesnippet i am using: > > #!/usr/bin/python > > import string > inp = open("xyplan.nobreaks","r") > data = inp.read() > for words in data.split(): > print words > inp.close() > > Any hints? > > TIA, > ./Tom Might be more than you need, but I've employed "TextFormatter" (http://www.faqts.com/knowledge_base/view.phtml/aid/4517) to good effect. -Don From aleax at mail.comcast.net Fri Nov 11 00:46:37 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Thu, 10 Nov 2005 21:46:37 -0800 Subject: [ x for x in xrange(10) when p(x) ] References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131627394.890394.200070@g44g2000cwa.googlegroups.com> <4373bcbc.150778327@news.oz.net> <1131675601.931303.177890@g14g2000cwa.googlegroups.com> Message-ID: <1h5tz2c.1lmc7tlk7ge03N%aleax@mail.comcast.net> bonono at gmail.com wrote: > > >>> list (x for x in xrange(20) if x<5 or iter([]).next()) > > [0, 1, 2, 3, 4] > > > > Or a bit more readably: > > >>> def stop(): raise StopIteration > > ... > > >>> list (x for x in xrange(20) if x<5 or stop()) > > [0, 1, 2, 3, 4] > > > > IOW, your "when condition(x)" (IIUIC) can be spelled "if condition(x) or > > stop()" > If it is a single loop, takewhile/dropwhile is perfectly fine but as I > mentioned in another post, it is nested and the condition needs > surrounding scope so seperate function and StopIteration doesn't work > as it breaks out of the whole thing expression. Can you give one example where this stop() function wouldn't work and your hypothetical ``when'' would? I don't see how "it breaks out of the whole thing expression" -- it terminates ONE for-clause (and what else would your cherished ``when'' do?). Alex From eternalsquire at comcast.net Thu Nov 17 22:03:41 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 17 Nov 2005 19:03:41 -0800 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <437a5980$0$18815$636a55ce@news.free.fr> <1132097897.576546.165220@o13g2000cwo.googlegroups.com> Message-ID: <1132283021.856821.311240@g44g2000cwa.googlegroups.com> >You have not been working with the right people. They do exist, but they >are rare. Elucidate? From samckain at southslope.net Thu Nov 10 21:00:06 2005 From: samckain at southslope.net (Steve) Date: Thu, 10 Nov 2005 20:00:06 -0600 Subject: SuSe 10.0 missing Idle References: Message-ID: Joseph Garvin wrote: > Steve wrote: > >>Hello, >> >> Hopefully this is not to of topic. I just installed SuSe >> 10.0 >> and although python installed but no Idle. I can't seem to find it >> in >>the list of available packages either. I was wondering if someone >>might steer me in the right direction. I've just started learning >>python and would really like to get Idle back or failing that a >>reccommendation of another IDE for python? >> >>Thanks in Advance >>Steve >> >> > SuSE probably has a seperate package, something like python-tk, that > will install IDLE. Look for that, some distros don't like to install > idle by default because it also means installing the Tk toolkit that > it uses. Thanks, I'll give that a try Steve From jeff at schwabcenter.com Wed Nov 9 14:56:41 2005 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Wed, 09 Nov 2005 19:56:41 GMT Subject: Floating numbers and str In-Reply-To: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> References: <1131565949.678342.39890@g44g2000cwa.googlegroups.com> Message-ID: Tuvas wrote: > I would like to limit a floating variable to 4 signifigant digits, when > running thorugh a str command. Ei, > > > x=.13241414515 > y=str(x)+" something here" > > But somehow limiting that to 4 sign. digits. I know that if you use the > print statement, you can do something like %.4d, but how can I do this > with converting the number to a string? Thanks! %d for a floating-point type? Is that right? Anyway, ITYW: "%.4g" % x E.g: >>> x=.13241414515 >>> y="%.4g something here" % x >>> print y 0.1324 something here >>> From fredrik at pythonware.com Mon Nov 14 11:35:27 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Nov 2005 17:35:27 +0100 Subject: newbie help needed References: <20051114162607.42068.qmail@web35907.mail.mud.yahoo.com> Message-ID: "john boy" wrote: > I am running the following program: > > def print Multiples (n, high): > i = 1 > while i <= high: > print n*i, ' \t' , > i = i + 1 > print > def printMultTable (high): > i = 1 > while i <= high: > print Multiples (i, high) > i = i + 1 > printMultiples(8,8) > printMultTable(8) > How can I get rid of the top row? by not calling "printMultiples" before you call "printMultTable", perhaps? that is, changing printMultiples(8,8) printMultTable(8) to printMultTable(8) should do the trick. From bignose+hates-spam at benfinney.id.au Thu Nov 10 22:19:41 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Nov 2005 14:19:41 +1100 (EST) Subject: Abstract Base Classes Message-ID: Howdy all, Okay, so Guido doesn't like Abstract Base Classes[0], and interfaces are the way of the future[1]. But they're not here now, and I understand ABCs better. I want my modules to (sometimes) define an abstract base exception class, that all other exceptions in that module inherit from. class FooException(Exception): """ Base class for all FooModule exceptions """ class FooBadFilename(FooException): """ Raised when a bad filename is used in a foo """ class FooUnknownBar(FooException, KeyError): """ Raised when an unknown bar is used with a foo """ However, there should never be an exception raised of class FooException, and in fact I want that to cause an appropriate error to be raised from the module. Normally, I'd pick some key part of the functionality of the class, and cause that to raise NotImplementedError. It's then the responsibility of subclasses to override that. However, in the case of exceptions, I don't want to override *any* functionality; everything should be provided by the base classes. It'd be messy to have to override something in every subclass just to ensure the abstraction of the module base exception. I've tried doing this in the __init__(): class FooException(Exception): """ Base class for all FooModule exceptions """ def __init__(self): raise NotImplementedError, \ "%s is an abstract class for exceptions" % self.__class__ When I use this, I discovered to my horror that the subclasses were calling FooException.__init__ -- which I though wasn't supposed to happen in Python! It's also rather semantically weird, to my eye. Can I do something tricky with checking base classes in the FooException.__init__() ? [0] Although he's apparently been quoted earlier as saying he did. He's changed his mind[1] since then. [1] -- \ "The shortest distance between two points is under | `\ construction." -- Noelie Alito | _o__) | Ben Finney From onurb at xiludom.gro Thu Nov 3 04:19:18 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 03 Nov 2005 10:19:18 +0100 Subject: how to write a blog system with Python In-Reply-To: <1130986622.788569.225120@o13g2000cwo.googlegroups.com> References: <1130986622.788569.225120@o13g2000cwo.googlegroups.com> Message-ID: <4369d617$0$18073$626a14ce@news.free.fr> ice wrote: > I am a fresh here , and I have no idea of it. > Do you have any comments? > Learn Python Learn web programming Write the specs for your blog system Design the solution Implement it -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python at hope.cz Sat Nov 5 03:13:18 2005 From: python at hope.cz (Lad) Date: 5 Nov 2005 00:13:18 -0800 Subject: How can I do this in Python? In-Reply-To: <1131140647.140956.12850@z14g2000cwz.googlegroups.com> References: <1131118052.827738.235590@f14g2000cwb.googlegroups.com> <1131122051.701419.108200@g43g2000cwa.googlegroups.com> <1131140647.140956.12850@z14g2000cwz.googlegroups.com> Message-ID: <1131178398.195075.111300@z14g2000cwz.googlegroups.com> Can you please explain in more details (1) choice? Thanks Regards, L From apardon at forel.vub.ac.be Fri Nov 4 04:58:20 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 09:58:20 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> Message-ID: Op 2005-11-04, Steve Holden schreef : > Antoon Pardon wrote: >> Op 2005-11-03, Stefan Arentz schreef : >> >>>Antoon Pardon writes: >>> >>>... >>> >>> >>>>>>No matter wat the OO model is, I don't think the following code >>>>>>exhibits sane behaviour: >>>>>> >>>>>>class A: >>>>>> a = 1 >>>>>> >>>>>>b = A() >>>>>>b.a += 2 >>>>>>print b.a >>>>>>print A.a >>>>>> >>>>>>Which results in >>>>>> >>>>>>3 >>>>>>1 >>>>> >>>>>I find it confusing at first, but I do understand what happens :-) >>>> >>>>I understand what happens too, that doesn't make it sane behaviour. >>>> >>>> >>>>>But really, what should be done different here? >>>> >>>>I don't care what should be different. But a line with only one >>>>referent to an object in it, shouldn't be referring to two different >>>>objects. >>> >>>It doesn't. >> >> >> Yes it does. If the b.a refers to the instance variable, then an >> AttributeError should be raised, because the instance variable doesn't >> exist yet, so you can't add two to it. >> > Excuse me. The statement > > a += 2 > > causes a to refer to a different object after the assignment than it did > before. So does the statement But the 'a' is both times in the same namespace. > self.a += 2 In this case the 'a' is not necessarily both times in the same name space. > So why are you so concerned that the pre-assignment reference comes from > a different scope to the post-assignment reference? The fact remains > that after both assignments the rebound name can no longer (ever) be > used to refer to its former referent without a further rebinding taking > place. I concerned with the a refering to different variables. A variable being a name in a specific namespace. >> If the b.a refers to the class variable then two should be added to it. >> > Wring, wring, wring. (Sorry, got that wrong :-) > >> Neither happens instead we get some hybrid in which an instance varible >> is created that gets the value of class variable incrented by two. >> > Yes. So does this mean you also have a problem with > > def f(x): > x += 2 > > g = 3 > print f(g) > > When the function call executes, the name x is bound to an object in the > call's containing scope. Is it then your contention that the augmented > assignment in the function should add two to that object, changing the > value of g? Whether I have a problem with this specific behaviour or not is irrelevant. In this case we have only one namespace with an 'x'. So searching for 'x' will not result in different variables being found. > It doesn't, it simply proceeds along the lines of all Python assignments > and resolves the name as a reference to a specific object. It then > computes a new value from the referenced object and the augmented > assignment operator's right operand, and rebinds the name to the > newly-computed value. > > Please stop talking about variables. No I think variable is the right term here. It refers to a name in a specific namespace. > Although augmented assignment operators have the *option* of updating > objects in place, surely not even you can require that they do so when > they are bound to an immutable object such as an integer. No but I can require that the namespace to which a name is resolved, doesn't change during the operation. >>>It doesn't touch the *class variable* A.a which is still 1. >> > Why "should" it? Why, why, why? And gain, just for good measure, why? > Augmented assignment to a function argument doesn't modify the passed > object when immutable, and you have no problem with that (I know as I > write that this is just asking for trouble, and it will turn out that > you also find that behavior deeply controversial ...) > >> >> But it accesses the class variable. >> > Repeat after me: "Python assignment binds values to names". But not just to a name, it binds a name in a specific namespace. > When I write > > class something: > a = 1 > def __init__(self, val=None): > if val: > self.a += val > > then in the last statement the augmented assignment rebinds "self.a" > from the class "variable" to a newly-created instance "variable". I am > of course using the word "variable" here in a Pythonic sense, rather > than in the sense that, say, a C programmer would use. In Python I > prefer to talk about binding names because talking of variables leads > people to expect that a name is bound to an area of memory whose value > is modified by assignment, but this is in fact not so. > > The initial access to self.a uses the defined name resolution order to > locate a value that was bound to the name "a" in class scope. So what? > This is a long-documented fact of Python life. It's *supposed* to be > that way, dammit. That it is documented, doesn't make it sane behaviour. Otherwise all companies had to do was to document there bugs. In a line like b.a += 2, you only have one reference to a name to be resolved in a spefied namespace (hierarchy). Since there is only one reference I don't think it is sane that two resolutions are done with two different variables as a result. > I fail to understand why this is such a problem for you. But then it's > clear from long past experience that our perceptions of Python's > execution model differ quite radically, and that I seem to find it quite > satisfactory overall, whereas you are forever banging on about what > "should" be true of Python and what Python "should" do. Which, as is > probably obvious by now, I sometimes find just a teeny bit irritating. > Kindly pardon my tetchiness. > > I suppose ultimately I'm just more pragmatic than you. It has nothing to do with being more pragmatic. Being pragmatic is about how you handle things with real life projects. It has little to do with the degree in which you agree with the design of the tool you have to work with. I would say I am more pragmatic than most defenders of python, because when it comes done to do my work, I just use python as best as I can, while a lot of people here seem to think that every little criticism I have is enough to go and look for a different language. > Plus I started > using Icon, whose assignment semantics are very similar, back in the > 1970's, so Python's way of doing things fits my brain quite nicely, > thank you. So, people can probably say that about any language they started with. That a language suits a certain persons brain, may say more about the person than about the language. -- Antoon Pardon From steve at REMOVEMEcyber.com.au Tue Nov 15 21:30:40 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 16 Nov 2005 13:30:40 +1100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <1132082783.353359.69900@g49g2000cwa.googlegroups.com> <8dgkn1d8k28ibttdfoe3b5c392gi36uijn@4ax.com> <1132092377.695554.117840@g49g2000cwa.googlegroups.com> Message-ID: <437A99D0.6020603@REMOVEMEcyber.com.au> lmaycotte at gmail.com wrote: > Maybe this helps: Unfortunately, it doesn't. If you read the sample code the original poster first gave, you will see that Py's example is virtually the same as yours: [original code] def foo(inputVal): if isinstance(inputVal, (list, tuple)): for val in inputVal: # do stuff It uses the same program logic, only the implementation is different: your code tests the object's type, and compares it to the type of list and tuple. Py's code tests the object's type, comparing it to lists and tuples. Type testing gives less information than using isinstance, and takes more work to do it. For instance, Py's code will correctly work with subclasses of lists, yours will wrongly reject them. Check Py's requirements carefully: "I have function which takes an argument. My code needs that argument to be an iterable (something i can loop over)...so I dont care if its a list, tuple, etc." Notice the "etc"? There are lots of iterables other than lists and tuples. There are xrange objects, files, strings, buffers, sub-classes of all of those, classes that implement __getitem__(), classes that implement next(), and probably more things that I have forgotten. Your code doesn't check for any of those. -- Steven. From yuxi at ece.gatech.edu Sat Nov 12 03:30:07 2005 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Sat, 12 Nov 2005 03:30:07 -0500 Subject: Python obfuscation In-Reply-To: <1h5tx6n.ayer08s58osaN%aleax@mail.comcast.net> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131639786.958533.45070@z14g2000cwz.googlegroups.com> <1h5tx6n.ayer08s58osaN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > There is no effective manner of protecting your code, except running it > only on well-secured machines you control yourself. If you distribute > your code, in ANY form, and it's at all interesting to people with no > interest in respecting the law, then, it WILL be cracked (and if users > choose to respect the law, then you need no "protecting"). Indeed. An this extends to web services too. If you have input which can be observed (or even better, controlled) and output that can be observed too, one would be able to infer the workings of the code (reverse engineering in one of its purest forms). If your business strategy relies heavily on a proprietary algorithm or even something as weak as lock-in via a proprietary "un-interoperable" data format, then web services is not the final answer. It may work for certain applications (Microsoft's for example) where the cost of reverse engineering is equivalent to the cost of building from scratch. From rs at natchie.mine.nu Tue Nov 15 10:25:49 2005 From: rs at natchie.mine.nu (Rusty Shackleford) Date: Tue, 15 Nov 2005 15:25:49 GMT Subject: Need advice on subclassing code Message-ID: Hi -- We have some code that returns an object of a different class, depending on some parameters. For example: if param x is 1 and y is 1, we make an object of class C_1_1. if param x is 1 and y is 2, we make an object of class C_1_2. C_1_1 and C_1_2 share a common C ancestor, and in practice may be identical, but theoretically, could have the same function name with two different implementations underneath. We have a file where all the C_X_Y classes are defined. It looks sort of like this: class C_1_1(C): """Creates a x=1 and y=1 class""" def __init__(self): C.__init__(self, 1, 1) class C_1_2(C): """Creates a x=1 and y=2 class""" def __init__(self): C.__init__(self, 1, 2) 99% of the specific classes do the exact same thing. For a tiny few, the class definition looks like this: class C_3_5(C): """Creates a x=3, y=5 class.""" def __init__(self): C.__init__(self, 3, 5) def foo(self): """Redefine the default C.foo() function.""" return 99 The reason for this is that we want to allow different classes to do non-standard behavior. In practice, however, it turns out that most of the time, we don't need anything special. Is this the best solution? Is there some way of doing a default vs. non-default deal, without having to manually hardcode all the different possible subclasses? Thanks for the help. -- A better way of running series of SAS programs: http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles From strombrg at dcs.nac.uci.edu Fri Nov 25 16:04:39 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Fri, 25 Nov 2005 21:04:39 GMT Subject: CGI question Message-ID: What's the best way of converting this: 'hide\\?http://www.dedasys.com/articles/programming_language_economics.html\x012005-07-20 14:48' ...to something easily usable in a python CGI script? Thanks! From samrobertsmith at gmail.com Sun Nov 20 22:23:00 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 20 Nov 2005 19:23:00 -0800 Subject: global definition Message-ID: <1d987df30511201923n5ec45401qfcdaed796b2ab1d7@mail.gmail.com> I have a code here. I understand i can not draw lines without the global definition of lastX and lastY. But still confused by its use. when should we use global definition? from Tkinter import * root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) frame = c lastX="" lastY="" def click(event): global lastX, lastY if lastX != "": c.create_line(lastX,lastY,event.x,event.y,fill="white") lastX = event.x lastY = event.y c.bind('<1>',click) c.pack() root.mainloop() From cito at online.de Sat Nov 26 05:49:50 2005 From: cito at online.de (Christoph Zwerschke) Date: Sat, 26 Nov 2005 11:49:50 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <86lkzcgvpq.fsf@bhuda.mired.org> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > I think you're trying to tweak the wrong definition. Types are > immutable if their instances are immutable. I'm not trying to tweak it, but to gain more clarity about what is actually meant when you talk about "mutable" types and objects and whether it suffices to use these terms as long as you speak about built-in datatypes. Tuples have been considered an immutable type since generations, becaue the elements of a tuple cannot be changed (i.e. the elements themselves, not their values). Likewise, they should be considered a hashable type because they have a proper hash function that can be used if all elements are hashable. Still, you can create instances of this immutable/hashable data type which are mutable/not hashable. So in the docs it will be important to be clear and emphasize that the *objects* have to be immutable/hashable, not only their types. > So whether or not a tuple containing a mutable object is > immutable depends on whether you define a immutable as "the object > can't change" or "the objects value can't change". Right - if you have an actual tuple instance like (a,) and a is a list, you can argue whether it should be considered mutable or not. But you cannot argue whether it is hashable or not. It's simply not hashable. In so far, speaking about whether an object is hashable is more precise (well-defined) than asking whether it is mutable, you're right. > Do you think it's really necessary to specify "has a __hash__ method > that returns a value", as opposed to just "has a __hash__ method"? I think it is necessary to require that it has a "proper" __hash__ function. As far as I understand you can always add a __hash__ method. Not only invalid __hash__ methods like in this case: class mylist0(list): def __hash__(self): return None But you can also easily add valid __hash__ methods: class mylist1(list): def __hash__(self): return 0815 class mylist2(list): def __hash__(self): return id(self) In the case of mylist1, everything is ok including semantics, but performance suffers dramatically. In mylist2, performance is great, but semantics suffers greatly. Which of these user-defined types would you call "hashable"? Technically speaking, both probably are, so you can indeed use list objects of both types as keys of a dictionary - but I think there should be a hint in the docs that you need to have a "proper" hash function if you want your dictionary to be performant and show the usually expected behavior. -- Christoph From cito at online.de Thu Nov 24 19:09:45 2005 From: cito at online.de (Christoph Zwerschke) Date: Fri, 25 Nov 2005 01:09:45 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <43863D80.6010808@v.loewis.de> References: <43850a7a$0$8074$9b622d9e@news.freenet.de> <43863D80.6010808@v.loewis.de> Message-ID: Martin v. L?wis schrieb: > Your original question was "could it be changed, and should it be > changed?" As the answer to the first part is already "no", the > second part really doesn't raise. Right of course. The second part of the question was rather hypothetical (in the sense of "if we could start with Python from scratch, would it then be desirable"). > In a set, all elements are different. In Python, this means that, for > any two elements X and Y of a set, X!=Y. Now, consider this set: > a = [1] > b = [1,2] > S = set(a,b) > a.append(2) > Now, a==b, so the inherent set property breaks. In theory, this should > cause S to contain only a single element; the other one should > disappear. I just started to see these problems as well. I believed that the immutability of set elements had only technical reasons (hashing etc.) but your're right, it has also semantical reasons. In the above case, a or b would have to magically disappear, and even if that would be possible it would be completely unclear which of the two, and what would happen if you subsequently do a.append(3)? Should it magically appear again? So I understand you will get into very hot water if you try to implement sets with mutable elements. > This is not only hard to implement (removal from a set > would have to remove all duplicates, iterating over a set would have > to skip over duplicates) - there is also another semantical issue: > If one element is skipped/dropped, which of these (a or b)? I should have read your posting fully before writing the above ;-) -- Christoph From bdesth.quelquechose at free.quelquepart.fr Sun Nov 20 17:27:52 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 20 Nov 2005 23:27:52 +0100 Subject: Is Python weak on the web side? In-Reply-To: References: Message-ID: <4380ede9$0$14665$626a14ce@news.free.fr> Tony a ?crit : > If I'd like to learn Python for web-development, what are the options > available? There are too many *good* options for web developpement in Python. > Thanks. tony From jmdeschamps at gmail.com Tue Nov 8 21:41:38 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 8 Nov 2005 18:41:38 -0800 Subject: Goto XY In-Reply-To: <1131503541.804184.320620@o13g2000cwo.googlegroups.com> References: <1131499644.561039.16420@g14g2000cwa.googlegroups.com> <1131501865.133982.97930@z14g2000cwz.googlegroups.com> <1131502335.530040.58260@g47g2000cwa.googlegroups.com> <1131503541.804184.320620@o13g2000cwo.googlegroups.com> Message-ID: <1131504098.851545.224190@z14g2000cwz.googlegroups.com> Like David said above... ;-) From nyamatongwe+thunder at gmail.com Tue Nov 29 19:24:09 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 30 Nov 2005 00:24:09 GMT Subject: windows paging Q In-Reply-To: References: Message-ID: Gerry Blais: > My program has a memory usage of 30 MB according to the task manager, > and is doing 1000+ page faults / second (page fault delta, high speed > refresh rate). > > With memory available, any idea why I'm paging so much, and what I > might do about it? Many page faults are soft faults and don't go to disk. Others are caused by reading files. Run perfmon for more details and from the memory performance object select page reads to see hard page faults. Neil From sybrenUSE at YOURthirdtower.com.imagination Fri Nov 4 05:07:56 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 4 Nov 2005 11:07:56 +0100 Subject: help converting some perl code to python References: <1131094909.984993.32330@z14g2000cwz.googlegroups.com> Message-ID: eight02645999 at yahoo.com enlightened us with: > the problem is the '..' operator in perl. Is there any equivalent in > python? any suggestions ? I have a suggestion: stop assuming we know perl, and explain what this '..' operator does. 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 donn at u.washington.edu Thu Nov 3 11:57:10 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 03 Nov 2005 08:57:10 -0800 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: In article , Magnus Lycka wrote: ... > On the other hand: > > >>> class C: > ... a = [1] > ... > >>> b=C() > >>> b.a += [2] > >>> b.a > [1, 2] > >>> C.a > [1, 2] > > I can understand that Guido was a bit reluctant to introduce > += etc into Python, and it's important to understand that they > typically behave differently for immutable and mutable objects. As far as I know, Guido has never added a feature reluctantly. He can take full responsibility for this misguided wart. Donn Cave, donn at u.washington.edu From aleax at mail.comcast.net Tue Nov 15 14:19:15 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 15 Nov 2005 11:19:15 -0800 Subject: best way to discover this process's current memory usage, cross-platform? References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132080864.280909.51540@g44g2000cwa.googlegroups.com> Message-ID: <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> matt wrote: > Perhaps you could extend Valgrind (http://www.valgrind.org) so it works > with python C extensions? (x86 only) Alas, if it's x86 only I won't even look into the task (which does sound quite daunting as the way to solve the apparently-elementary question "how much virtual memory is this process using right now?"...!), since I definitely cannot drop support for all PPC-based Macs (nor would I WANT to, since they're my favourite platform anyway). Alex From godoy at ieee.org Mon Nov 7 06:10:32 2005 From: godoy at ieee.org (Jorge Godoy) Date: 07 Nov 2005 09:10:32 -0200 Subject: PyFLTK - an underrated gem for GUI projects References: Message-ID: <87acgg3e8n.fsf@jupiter.g2ctech> aum writes: > What I'm saying is that there are many basic projects being written for > these toolkits, whose functionality could be completely supported by > PyFLTK. When only a smaller set of widgets is needed, there's a stronger > case for using lighter widget libraries - especially FLTK, because you'll > get way more functionality per line of code, and finish your project > faster, than if using the bigger toolkits with their application-level red > tape - the extra lines of code you have to write to get things done. At least on Linux world, it is easier to find Qt or GTK than FLTK. Not having to deploy new base libraries for another project when there are other available is a big plus, IMHO. Specially if you have no control over the politics of updating servers, installing extra software, etc. And it would sound really weird asking the admin to install new software on the server or on workstations to provide a GUI layer for a more complex project just after using a lighter one... "Why not using the same stuff for both?" is the question I hear from them. Installing things mean, usually: - checking licenses - checking vulnerabilities - convincing admin / IT staff that it is needed and there's no "already installed" alternative - maintenance - tests on upgrading the environment - tests on deployment (who knows if there's something that might cause a clash or interfere with other apps?) and a few more stuff. Doing all that just because one app might use a lighter toolkit doesn't look interesting. On the other hand, if the environment requires lighter libs -- the software will be embedded in something --, then it is fine doing all these because of that. > If travelling off-road for a few weeks and driving over minefields in > enemy territory, take the Hummer. But for ordinary use, like commuting to > work, visiting friends, shopping etc, using anything more than the Honda > 4-cylinder sedan is IMHO a waste of resources. You can choose only one vehicle and you don't know where you'll be sent. Which will you pick? > Similarly, coding something in wx when FLTK will suffice is a waste of > time, effort, disk space, CPU cycles and memory. If wx is already there, installing FLTK starts being a waste of resources, disk space, CPU cycles, memory (it won't be shared with other apps...), etc. -- Jorge Godoy From cito at online.de Sun Nov 20 19:27:22 2005 From: cito at online.de (Christoph Zwerschke) Date: Mon, 21 Nov 2005 01:27:22 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > if you restructure the list somewhat > d = ( > ('pid', ('Employee ID', 'int')), > ('name', ('Employee name', 'varchar')), > ('sal', ('Salary', 'float')) > ) > you can still loop over the list > ... > but you can easily generate an index when you need it: > index = dict(d) That's exactly the kind of things I find myself doing too often and what I was talking about: You are using *two* pretty redundant data structures, a dictionary and a list/tuple to describe the same thing. Ok, you can use a trick to automatically create the dictionary from the tuple, but still it feels somewhat "unnatural" for me. A "ordered dictionary" would be the more "natural" data structure here. I also wanted to mention the uglyness in the definition (nested tuples), but then I understood that even an ordered dictionary would not eliminate that uglyness, since the curly braces are part of the Python syntax and cannot be used for creating ordered dictionaries anyway. I would have to define the ordered dictionary in the very same ugly way: d = odict(('pid', ('Employee ID', 'int')), ('name', ('Employee name', 'varchar')), ('sal', ('Salary', 'float'))) (Unless the Python syntax would be extend to use double curly braces or something for ordered dictionaries - but I understand that this is not an option.) -- Christoph From aleax at mail.comcast.net Tue Nov 1 22:17:35 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 1 Nov 2005 19:17:35 -0800 Subject: Storing empties References: <1130539752.667045.183460@g14g2000cwa.googlegroups.com> <1130638902.048806.183580@g43g2000cwa.googlegroups.com> <1130647542.669549.300360@g43g2000cwa.googlegroups.com> <1h57spy.bpig8y1g0rvzfN%aleaxit@yahoo.com> <1130650215.537552.231990@g49g2000cwa.googlegroups.com> <1h58k4p.12xd7rj1t5peh0N%aleaxit@yahoo.com> <1h5bepj.q0sqsnbqqgjrN%aleax@mail.comcast.net> Message-ID: <1h5d3k0.32mnkz17x2xh6N%aleax@mail.comcast.net> Aahz wrote: ... > >>>the canonical idiom when you need such distinction is: > >>> > >>>_not_there = object() ... > >> What's your preferred idiom when you're dealing with storable objects? > > > >What's a "storable object"? You mean, something that can be pickled, or > >passed to the .write method of a file object, or stored in a database, > >or what else? > > Pickled and/or stored in a DB. Relational databases have the concept of NULL specifically to indicate "there is NOTHING here". I love it. For pickling, object() as a unique "nothing here, NOT EVEN a None" marker (AKA sentinel) works fine. Alex From dwahler at gmail.com Tue Nov 1 15:24:37 2005 From: dwahler at gmail.com (David Wahler) Date: 1 Nov 2005 12:24:37 -0800 Subject: callback for ctypes In-Reply-To: References: Message-ID: <1130876677.389031.126690@g47g2000cwa.googlegroups.com> James Hu wrote: > Hi, gurus, > > I would like to use ctypes to implement callback function for QImage > Camera to capture image asynchronously, and I have the c++ code of > callback, but I am totally in the dark, the ctypes tutorial is not good > enough for me to do that, does someone know where to dig more info for > ctypes callback implementation? > > Thanks, > > James Ctypes is designed to interface with C code, not C++. C++ compilers perform name mangling to allow function overloading and virtual functions. To use ctypes, you'll need to know the exact details of how your compiler translates C++ code--which is certainly a non-trivial task. Also, I can't find any references for this "QImage Camera". Could you post some additional information? -- David From pythonnew at gmail.com Sun Nov 13 16:30:19 2005 From: pythonnew at gmail.com (Ben Bush) Date: Sun, 13 Nov 2005 13:30:19 -0800 Subject: open source and pure python Message-ID: <8c11e4350511131330vf1efb33x710f3d715e3d094b@mail.gmail.com> Is there any package written in pure python code? I know lots of packages borrow the functions from other languages such as C or FORTRAN. So it is still black box to me because I do not know these languages. Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From samrobertsmith at gmail.com Mon Nov 21 05:49:56 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 21 Nov 2005 02:49:56 -0800 Subject: duplicate items in a list Message-ID: <1d987df30511210249g599223a1i13967fd4d47488d3@mail.gmail.com> I used the following method to remove duplicate items in a list and got confused by the error. >>> a [[1, 2], [1, 2], [2, 3]] >>> noDups=[ u for u in a if u not in locals()['_[1]'] ] Traceback (most recent call last): File "", line 1, in ? TypeError: iterable argument required From http Mon Nov 28 16:17:55 2005 From: http (Paul Rubin) Date: 28 Nov 2005 13:17:55 -0800 Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> <8664qcv6i5.fsf@bhuda.mired.org> Message-ID: <7x64qcii9o.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > For those of us not following this thread closely, can you identify cases > where tuples are mutable, not hashable or can't be used as dictionary keys? > I've never encountered any such cases. t = ([1,2], [3,4]) From lycka at carmen.se Fri Nov 4 10:27:28 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 04 Nov 2005 16:27:28 +0100 Subject: Cheapest pocket device to code python on In-Reply-To: <1131076503.645113.309940@g49g2000cwa.googlegroups.com> References: <1131076503.645113.309940@g49g2000cwa.googlegroups.com> Message-ID: theboringdays at gmail.com wrote: > What is the cheapest/affordable pocket device that I can code python > on? I think the closest I have seen is pocketpc from this page: A used Fujitsu Lifebook running Linux and fairly large pockets? ;) There is some version of Python running on Palms, but it's stripped down, and I haven't tried it. From fredrik at pythonware.com Fri Nov 11 10:48:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 16:48:38 +0100 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com><1131506094.767452.156780@o13g2000cwo.googlegroups.com><1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: Norman Silverstone wrote: > > did you test the script? here's a simulator: > > < snip> > > Fredrik, thank you very much indeed for taking the trouble to show me the > way. I am sorry that I made the comment I did, that will teach me to read > more carefully. It is said that there is no fool like an old fool and, as > I am approaching 78 years old, I think I qualify. It is also said that you > are never too old to learn so I am trying. > > Now, I put the script you gave into an editor and ran it , (I use Ubuntu > Linux by the way). It certainly showed how the computer arrived at the > number guessed but guessed the number itself and gave me no chance to say > whether high or low. I noticed also that the numbers were all greater than > 50 and the loop ran until the number guessed was 100, then it stopped. > Perhaps you can point out to me how I should go about debugging. debugging? the script I posted was intended to show you that given an honest human (simulated by the raw_input function), the posted algorithm found the right answer for all values in the given range. (if the algorithm had been broken, the simulator wouldn't have finished). if you want to play yourself, use Steven's original code, and follow the in- structions... From mwm at mired.org Sat Nov 26 04:46:15 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Nov 2005 04:46:15 -0500 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> <86oe49wyky.fsf@bhuda.mired.org> <86acfsgols.fsf@bhuda.mired.org> Message-ID: <86sltjg2s8.fsf@bhuda.mired.org> Steven D'Aprano writes: > But if you *do* redistribute it, then you must live up to conditions in > the licence. If you aren't willing to do that, use software with a > different licence. That's a restriction on redistribution. > The only restriction is that you can't give those people fewer, > weaker rights than you got That's a restriction on redistribution. > I would still like to find out what sense of "restricting distribution" > you think the GPL does. You named the restrictions yourself. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bretthoerner at gmail.com Thu Nov 3 21:28:49 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 3 Nov 2005 18:28:49 -0800 Subject: putting an Icon in "My Computer" In-Reply-To: <1131071030.209405.37800@z14g2000cwz.googlegroups.com> References: <1131071030.209405.37800@z14g2000cwz.googlegroups.com> Message-ID: <1131071329.475037.289140@g47g2000cwa.googlegroups.com> > I've been asked by my boss to put an Icon in WinXP's "My Computer" for > a utility we use around the shop. My tool of choice is of course > Python and therefore what I am using to attempt my given task. I have > no trouble putting Icons in the WinXP Toolbar using Python, but have > totally failed to get an Icon to appear in My Computer. Any Idea on > why and maybe how to get around this using Python? I'm pretty sure the My Computer menu is limited to devices and special Windows folders like My Documents, etc. I've never seen a program add an icon there, and I don't think its allowed through the API. From fredrik at pythonware.com Thu Nov 17 15:02:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Nov 2005 21:02:48 +0100 Subject: os.spawnl error References: <1132257061.597353.70670@g43g2000cwa.googlegroups.com> Message-ID: Salvatore wrote: > Does someone already had ths problem ? > >>>> os.spawnl(os.P_NOWAIT,'c:\windows\notepad.exe') > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\os.py", line 565, in spawnl > return spawnv(mode, file, args) > OSError: [Errno 22] Invalid argument that string doesn't contain what you think: >>> print "c:\windows\notepad.exe" c:\windows otepad.exe you can use "raw" string literals to get around this: >>> os.spawnl(os.P_NOWAIT, r'c:\windows\notepad.exe') more here: http://docs.python.org/tut/node5.html#SECTION005120000000000000000 From neildunn at gmail.com Sat Nov 26 22:00:48 2005 From: neildunn at gmail.com (neildunn at gmail.com) Date: 26 Nov 2005 19:00:48 -0800 Subject: Nested list comprehensions Message-ID: <1133060448.284028.238680@f14g2000cwb.googlegroups.com> Hey guys: >>> [(i,j,k) for i in range(1,j) for j in range(1,k) for k in range(1,5)] [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4)] >>> def a(): ... print [(j,k) for j in range(1,k) for k in range(1,5)] ... >>> a() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in a UnboundLocalError: local variable 'k' referenced before assignment Why is it that I can execute the nested list comprehension in the intepreter but if the same line is within a method declaration I get an unbound reference error? Is this a bug or am I missing some deep rule? Regards, Neil Dunn From ms at cerenity.org Tue Nov 8 18:47:39 2005 From: ms at cerenity.org (Michael) Date: Tue, 08 Nov 2005 23:47:39 +0000 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131440653.015221.324460@g43g2000cwa.googlegroups.com> Message-ID: <43715368$0$27993$ed2619ec@ptn-nntp-reader02.plus.net> pinkfloydhomer at gmail.com wrote: > Is there a way to make reference to the last element of a list, to use > as a shorthand: Yes. It's not wise to use, since this is brittle and will fail hard for you, but since you're interested, this is how you /could/ do it: (largely) # First of all create a mechanism for creating and handling symbolic # references class ref(object): def __init__(self, val): self._val = val def set_val(self, val): exec("global %s\n%s = %s" % (self._val, self._val, repr(val))) def get_val(self): return eval(self._val) val = property(get_val, set_val) Now we can play with this. Note the word *PLAY* . >>> lst = ["1","2","3","4"] >>> y = ref("lst[-1]") >>> y.val '4' >>> y.val = 10 >>> y.val 10 >>> lst ['1', '2', '3', 10] >>> i = 1 >>> z = ref("i") >>> z.val = 10 >>> i 10 Once again, note the word *play* - don't use this in __anything__ :-) Python binds values to names. As a result what you're after when asking for ref := &lst[len(lst) - 1] And then for ref to actually refer to that last item, you have to realise that you're asking for an indirection on the name "lst[-1]". Short of doing silly things with eval and exec (which you really don't want to do), you can't do this. However, it's python, so of course you *can*, but just because you *can* do something doesn't mean that you *should*. You'll note that in order to make the reference to the plain mutable value (i) work the set_val had to mark the value as global, which isn't quite right. (You might be able to trick it into using the "right" scope using lambda somehow, maybe) Once again, don't use it! (hopefully of interest though) Regards, Michael. -- http://kamaelia.sourceforge.net/ From bonono at gmail.com Sun Nov 20 21:48:09 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 18:48:09 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132531775.399671.93120@o13g2000cwo.googlegroups.com> Message-ID: <1132541289.132250.229430@z14g2000cwz.googlegroups.com> Peter Hansen wrote: > bonono at gmail.com wrote: > > Using the same logic, we don't need types other than string in a DBMS > > as we can always convert a string field into some other types when it > > is needed. > > You mean, like SQLite does? (http://www.sqlite.org/datatypes.html) > Yup, they are using similar logic. From http Sat Nov 5 22:19:29 2005 From: http (Paul Rubin) Date: 05 Nov 2005 19:19:29 -0800 Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> <7x4q6q7f6b.fsf@ruckus.brouhaha.com> <86hdaqsfjo.fsf@bhuda.mired.org> <7x3bmafrip.fsf@ruckus.brouhaha.com> <86d5lescfd.fsf@bhuda.mired.org> Message-ID: <7x8xw2ea4e.fsf@ruckus.brouhaha.com> Mike Meyer writes: > > It's only -because- of those licenses that there's any reason not to > > bundle. > > Actually, there are other reasons, just as there are reasons besides > licensing for not simply including third party libraries into the > standard library. I'm not talking about 3rd party libraries, I'm talking about 3rd party documentation for modules that are already in the Python standard library. For example, if someone wrote a good Tkinter manual that were licensed in a way that the PSF could drop it into the Python distro, then PSF should certainly consider including it. The same goes for good docs about urllib2, or various other modules that currently have lousy docs. > > I found > > http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html > > to be a pretty good tutorial, though incomplete as a reference. > > Thanks for the URL, but that's just a short list of links, most of > which I've already seen. Sorry, I meant: http://infohost.nmt.edu/tcc/help/pubs/tkinter/ (html) http://www.nmt.edu/tcc/help/pubs/tkinter.pdf (pdf of same) You've probably seen this manual already. From cjw at sympatico.ca Fri Nov 11 09:55:06 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 11 Nov 2005 09:55:06 -0500 Subject: Abstract Base Classes In-Reply-To: References: Message-ID: Ben Finney wrote: > Howdy all, > > Okay, so Guido doesn't like Abstract Base Classes[0], and interfaces > are the way of the future[1]. But they're not here now, and I > understand ABCs better. This is a very interesting discussion - not all of it understandable to me. Are interfaces really in our future? I found the contributions of "steffen" particularly appealing. Interfaces seem to add another level of complexity without significant benefit. Colin W. > > I want my modules to (sometimes) define an abstract base exception > class, that all other exceptions in that module inherit from. > > class FooException(Exception): > """ Base class for all FooModule exceptions """ > > class FooBadFilename(FooException): > """ Raised when a bad filename is used in a foo """ > > class FooUnknownBar(FooException, KeyError): > """ Raised when an unknown bar is used with a foo """ > > However, there should never be an exception raised of class > FooException, and in fact I want that to cause an appropriate error to > be raised from the module. > > Normally, I'd pick some key part of the functionality of the class, > and cause that to raise NotImplementedError. It's then the > responsibility of subclasses to override that. > > However, in the case of exceptions, I don't want to override *any* > functionality; everything should be provided by the base classes. It'd > be messy to have to override something in every subclass just to > ensure the abstraction of the module base exception. > > I've tried doing this in the __init__(): > > class FooException(Exception): > """ Base class for all FooModule exceptions """ > def __init__(self): > raise NotImplementedError, \ > "%s is an abstract class for exceptions" % self.__class__ > > When I use this, I discovered to my horror that the subclasses were > calling FooException.__init__ -- which I though wasn't supposed to > happen in Python! > > It's also rather semantically weird, to my eye. > > Can I do something tricky with checking base classes in the > FooException.__init__() ? > > > [0] Although he's apparently been quoted earlier as saying he did. > He's changed his mind[1] since then. > > [1] > From noah at noah.org Thu Nov 3 20:24:11 2005 From: noah at noah.org (Noah) Date: 3 Nov 2005 17:24:11 -0800 Subject: How can I package a python script and modules into a single script? In-Reply-To: <1131039605.019088.31540@o13g2000cwo.googlegroups.com> References: <1131030933.425241.142800@o13g2000cwo.googlegroups.com> <3bmd220k.fsf@python.net> <1131039605.019088.31540@o13g2000cwo.googlegroups.com> Message-ID: <1131067451.505450.53630@f14g2000cwb.googlegroups.com> Freeze also packages the python interpreter into a binary. I need a cross platform solution that just packages the scripts. I expect the user to already have python installed. Yours, Noah From tiarno at sas.com Wed Nov 30 11:03:16 2005 From: tiarno at sas.com (Tim Arnold) Date: Wed, 30 Nov 2005 11:03:16 -0500 Subject: pyparsing and LaTeX? Message-ID: Anyone parsing simple LaTeX constructs with pyparsing? I'm playing around with it (and looking at John Hunter's matplotlib stuff), but I thought I'd ask here if anyone had other TeX/LaTeX examples. thanks, --Tim Arnold From bonono at gmail.com Mon Nov 21 00:42:53 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 20 Nov 2005 21:42:53 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <43814eaa.343166777@news.oz.net> <1132549972.254320.287490@g44g2000cwa.googlegroups.com> Message-ID: <1132551773.109499.292170@g47g2000cwa.googlegroups.com> Ben Finney wrote: > bonono at gmail.com wrote: > > [sort by] some other metadata that is not present in the data. > > [...] > > Of course, you may say, just put another column that represent > > this(some reporting programs I have seen do it this way) and that is > > an option but not the only option. > > It's a pretty good option, and very commonly used. It's known as the > "Schwartzian transform", or more descriptively, the "Decorate, Sort, > Undecorate" pattern. > Whether it is a good option is judged by the person implement it as he is the one seeing the whole thing, and not some snippet(or concept) on the usenet. From lee at example.com Sat Nov 19 18:00:12 2005 From: lee at example.com (Lee Harr) Date: Sat, 19 Nov 2005 23:00:12 GMT Subject: Is there a way to create a button in either pygame or livewires? References: <437e7373$0$20261$88260bb3@news.atlantisnews.com> Message-ID: <08Off.13734$cg.2239@news02.roc.ny> > Is there a way to create a button in either pygame or livewires, that is > able to be clicked and when clicked sends a command to restart the program? > You could try something like this using pygsear (http://www.nongnu.org/pygsear/) The button can call either start() which just makes a new Game instance in the same process, or full_restart() which starts a new process and quits the current one. from pygsear import Game, Widget from pygsear.locals import RED class G(Game.Game): def initialize(self): print 'starting up...' self.button = Widget.SpriteTextButton(self.window, "Restart", size=40, color=RED, padding=20) self.events.add(self.button.events) self.button.set_callback(self.restart) self.button.set_position((200, 100)) self.sprites.add(self.button) def restart(self, ev): print 'restarting...' #start() full_restart() self.quit = True def start(): g = G() g.mainloop() def full_restart(): import os import sys cmd = 'python %s &' % sys.argv[0] os.system(cmd) if __name__ == '__main__': start() From mwm at mired.org Sat Nov 5 06:26:09 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 06:26:09 -0500 Subject: Using Which Version of Linux References: Message-ID: <861x1v72um.fsf@bhuda.mired.org> blahman (blah at blah.blah) writes: > ok, i m going to use Linux for my Python Programs, mainly because i > need to see what will these fork() and exec() do. So, can anyone tell > me which flavour of linux i should use, some say that Debian is more > programmer friendly, or shold i use fedora, or Solaris. Because these > three are the only ones i know of that are popular and free. You seem a bit confused. Solaris isn't a Linux distribution, it's (System V) Unix. Linux isn't Unix - it's a Unix look-like. *BSD is Unix, but they can't call it that for licensing reasons. "Programmer-friendly" is pretty vague. Gentoo is the only Linux distro I've run into (which excludes a *lot* of Unix distros) that I'd consider programmer friendly, because it doesn't split packages up into "user stuff" and "developer stuff". That means you have to install two packages instead of one if you want to build things against that software. On the other hand, it uses it's own "package" manager - emerge - so you can't take advantage of rpms/debs from other systems (or you couldn't last time I looked into it). It also installs the least amount of "bundled" software, which I consider a programmer friendly behavior. Personally, I run FreeBSD - and I like gentoo because it has a lot in common with a BSD distribution. FreeBSD is the most popular of the BSDs. BSDs differ from Linuxen in that a BSD distribution is an integrated whole - the kernel and userland are maintained by the same group, in the same repository. So the number of BSD kernels to choose from is much greater than the number of Linux kernels, but the number of BSD distributions is much fewer. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rurpy at yahoo.com Wed Nov 23 19:44:45 2005 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 23 Nov 2005 16:44:45 -0800 Subject: about sort and dictionary In-Reply-To: References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> Message-ID: <1132793085.808501.279500@g44g2000cwa.googlegroups.com> Magnus Lycka wrote: > rurpy at yahoo.com wrote: > > a reminder" that the change is inplace. How arrogant! While > > I'm sure the designers had kindly intentions. my memory, though > > bad, is not that bad, and I object to being forced to write code > > that is more clunky than need be, because the designers thought > > they needed to help me with my memory. > > Such as being arm-twisted into writing horrible things > like x = sorted(l) instead of x = l.sort()? The first statement is not the same as the second. > It sounds a > bit as if someone locked you into a cellar and forced > you to program Python, just to torture you. I guess the > next step will be the comfy armchair! ;) > > Python has its roots in ABC, a language intended for > teaching programming to beginners, and it goes to great > lengths to make it easy to do things right. In my opinion, "do things right" is my fundamental beef with Python. Dispite claims, I don't believe Python's designers have a monopoly on the definition of "right". > it also avoids the mistake of introducing hurdles in a > vain attempts to prevent programmer mistakes. Such hurdles > typically lead to ugly workarounds. There are a few cases > when things don't work as some people would expect them > to work, but I think there are good resons for that. > > I'm surprised that you don't complain about not being able > to do "while x = f(): ..." while you're at it. That's also > a restriction of the kind you seem to rebel against. I would have but fortunately the introduction of iterators spared you from having to read about that :-) > I'm pretty sure Guido didn't think a bit about *your* > memory capacity when he designed Python, but rather wanted > to avoid spending his and other programmers' time on helping > people with yet another set of silly bugs. I serious doubt sort's return value of lack thereof made any measurable difference in the time spent helping people. > > There is much about Perl's rich functionality that is very worthy. > > Unfortunately, as you know, it's syntax leaves a lot to be desired. > > Which is mainly a consequence of TMTOWTDI... > If you want something more perlish, but with somewhat more > sane syntax, you might want to try Ruby. From jabel at plus.net Fri Nov 18 09:19:41 2005 From: jabel at plus.net (John Abel) Date: Fri, 18 Nov 2005 14:19:41 +0000 Subject: Python on linux In-Reply-To: <1132321509.20073.24.camel@wrkstn6> References: <1132321509.20073.24.camel@wrkstn6> Message-ID: <437DE2FD.1070901@plus.net> Here's one I used a while back. Returns a dict containing details per partition def _getAvailPartitions(): validTypes = [ 'ufs', 'nfs', 'reiserfs' ] mntTab = file( '/etc/mtab', 'r' ) drvDetails = {} for mntLine in mntTab: splitLine = mntLine.split() if splitLine[2] in validTypes: partDesc = splitLine[1] mntPart = os.statvfs( partDesc ) totalSize, totalFree = mntPart[ statvfs.F_BLOCKS ] , mntPart[ statvfs.F_BFREE ] totalInode, totalIFree = mntPart[ statvfs.F_FILES ] , mntPart[ statvfs.F_FFREE ] drvDetails[ partDesc ] = [ mntPart[ statvfs.F_FRSIZE ], ( totalSize, totalFree ), (totalInode, totalIFree) ] return drvDetails Amol Behl wrote: >Hi i wanted to know how can i find disk size on linux platform using >python. Also any info on how i can partition the hard disk, etc will be >welcome thank you. > > From mwm at mired.org Sat Nov 19 23:08:38 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 19 Nov 2005 23:08:38 -0500 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: <86hda8hsft.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 19 Nov 2005 13:08:57 -0500, Peter Hansen wrote: >> Umm... in other words, "the underscore is under-used so let's assign >> some arbitrary meaning to it" (to make the language more like Perl >> perhaps?). > > +1 > > I *really* don't like the idea of allowing underscores in numeric > literals. Firstly, for aesthetic reasons: I think 123_456 is seriously > ugly. Secondly, for pragmatic reasons, I think it is too easy to mistype > as 123-456. I know that Python can't protect you from typing 9-1 instead > of 901, but why add special syntax that makes that sort of error MORE > common?) I've seen at least one language (forget which one) that allowed such separators, but only for groups of three. So 123_456 would be valid, but 9_1 would be a syntax error. This kind of thing might help with the detecting typos issue, and probably won't be noticed by most users. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ark at acm.org Sun Nov 27 13:57:18 2005 From: ark at acm.org (Andrew Koenig) Date: Sun, 27 Nov 2005 18:57:18 GMT Subject: Which license should I use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com><863blkijjv.fsf@bhuda.mired.org> <87sltklawy.fsf_-_@lucien.dreaming> Message-ID: ""Bj?rn Lindstr?m"" wrote in message news:87sltklawy.fsf_-_ at lucien.dreaming... > Mike Meyer writes: > If they have the rights to the code, they can sell it, under the GPL or > any license of their choosing. In addition, if you GPL it, your employer > will be able to sell it, just like anyone else. If they have the rights to the code, you don't get to decide on the terms under which it will be distributed (if at all) -- they do. From bokr at oz.net Sat Nov 12 06:31:41 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 12 Nov 2005 11:31:41 GMT Subject: about try statement References: Message-ID: <4375ce41.286335849@news.oz.net> On Sat, 12 Nov 2005 10:20:08 +0100, Sybren Stuvel wrote: >Shi Mu enlightened us with: >> very hard for me to understand the difference between try...except >> and try...finally > >Within a 'try' block, if an exception is called and a matching >'except' block is found, that block will be used to handle the >expression. > >From the documentation of the "return" keyword: "When return passes >control out of a try statement with a finally clause, that finally >clause is executed before really leaving the function." Note that >there is no talk about exceptions in this. > Which is because in the finally block the exception is still "live" and will take effect as soon as the finally block is left, e.g., >>> try: ... try: 1/0 ... finally: print 'exception can not bypass finally' ... except Exception, e: ... print '%s: %s' %(e.__class__.__name__, e) ... exception can not bypass finally ZeroDivisionError: integer division or modulo by zero Or to make the point about return >>> def foo(den): ... try: ... try: return 1/den ... finally: print 'exception can not bypass finally' ... except Exception, e: ... print '%s: %s' %(e.__class__.__name__, e) ... return 'succeeded in returning something' ... >>> foo(0) exception can not bypass finally ZeroDivisionError: integer division or modulo by zero 'succeeded in returning something' >>> foo(1) exception can not bypass finally 1 Regards, Bengt Richter From grig.gheorghiu at gmail.com Fri Nov 18 16:56:37 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 18 Nov 2005 13:56:37 -0800 Subject: Los Angeles Python Users' Group, anyone? In-Reply-To: <1132335706.182177.58370@g14g2000cwa.googlegroups.com> References: <1132335706.182177.58370@g14g2000cwa.googlegroups.com> Message-ID: <1132350997.680412.137540@f14g2000cwb.googlegroups.com> mortenbagai at gmail.com wrote: > Hi, > > I was rifling through python.org to see if there was an existing Python > user's group for the Los Angeles area. Doesn't seem like it, so maybe > we should start one? I'm interested in helping with the coordination of > activities etc. > > Since everybody living in greater L.A. area is likely to have > superhuman tolerance for traffic and commuting times, I see no reason > why an L.A users' group couldn't cover the whole > LA/Valley/Burbank/Glendale/Pasadena/Long Beach/etc sprawl. > > Anyone interested, please email me at: m AT bagai DOT com > > Thanks! > > /Morten Hi, Morten I'm the organizer of the SoCal Piggies. Please subscribe to the mailing list and you'll get all the messages regarding our next meetings. We're planning to meet for dinner in December (probably Dec. 7th) at a restaurant in Pasadena. Check out the mailing list archives for details. Hope to see you at our next meetings! Grig Grig From p at ulmcnett.com Thu Nov 10 16:06:11 2005 From: p at ulmcnett.com (Paul McNett) Date: Thu, 10 Nov 2005 13:06:11 -0800 Subject: exceptions, internals (introspection?) In-Reply-To: <4373ae4a$1@nntp.zianet.com> References: <4373ae4a$1@nntp.zianet.com> Message-ID: <4373B643.4040205@ulmcnett.com> ej wrote: > I have often wondered how to get at other internals, such as the name of > the current function, file, line number I am in? The arguments to the > current function, etc. Others have given you information on how to get at the stack trace. But regarding getting at some of the other internals you are talking about: >>> import inspect >>> help(inspect) Back to exceptions, you can also provide your own global exception handler by overriding sys.excepthook (drop in your own function). -- Paul McNett http://paulmcnett.com http://dabodev.com From zach at in.tu-clausthal.de Sun Nov 27 17:15:40 2005 From: zach at in.tu-clausthal.de (Gabriel Zachmann) Date: Sun, 27 Nov 2005 23:15:40 +0100 Subject: ownership problem? In-Reply-To: References: Message-ID: > the problem isn't determining who owns it, the problem is determining > who's supposed to release it. that's not a very common problem in a that's about what i meant. i think, in c++, the "ownership problem" means the problem to determine who and when is to delete an object, or to keep track thereof. The object could be something as simple as a list element. Best regards, Gabriel. -- /-----------------------------------------------------------------------\ | Any intelligent fool can make things bigger, more complex, | | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \-----------------------------------------------------------------------/ From suma_37 at yahoo.com Wed Nov 9 07:01:00 2005 From: suma_37 at yahoo.com (sumi) Date: 9 Nov 2005 04:01:00 -0800 Subject: Hi, from my login i want to login as a other user , In-Reply-To: <4371e131$0$19929$626a54ce@news.free.fr> References: <1131533184.096101.49940@g49g2000cwa.googlegroups.com> <4371e131$0$19929$626a54ce@news.free.fr> Message-ID: <1131537660.853452.124790@z14g2000cwz.googlegroups.com> Hi, i am very new to python , it is just 2 days i started reading abt it. I did not understand the above statement. what i want to do is , i want to login as a super user eg : $su xyz , and then i need to enter the passwd, i want to do these steps using python , how can i do it?????????? From bokr at oz.net Tue Nov 22 15:16:13 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 22 Nov 2005 20:16:13 GMT Subject: Converting a flat list to a list of tuples References: <1132657034.642992.112780@g44g2000cwa.googlegroups.com> Message-ID: <43837bf7.485835644@news.oz.net> On Tue, 22 Nov 2005 13:37:06 +0100, =?ISO-8859-1?Q?Andr=E9?= Malo wrote: >* Duncan Booth wrote: > >> metiu uitem wrote: >> >> > Say you have a flat list: >> > ['a', 1, 'b', 2, 'c', 3] >> > >> > How do you efficiently get >> > [['a', 1], ['b', 2], ['c', 3]] >> >> That's funny, I thought your subject line said 'list of tuples'. I'll >> answer the question in the subject rather than the question in the body: >> >> >>> aList = ['a', 1, 'b', 2, 'c', 3] >> >>> it = iter(aList) >> >>> zip(it, it) >> [('a', 1), ('b', 2), ('c', 3)] > >Though it looks nice, it's an implementation dependant solution. What if >someone changes zip to fetch the second item first? > That would be a counter-intuitive thing to do. Most things go left->right in order as the default assumption. Regards, Bengt Richter From bignose+hates-spam at benfinney.id.au Wed Nov 16 16:57:24 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Nov 2005 08:57:24 +1100 (EST) Subject: running functions References: Message-ID: Gorlon the Impossible wrote: > I'm not sure how to phrase this question. I have a Python function > that sends MIDI messages to a synth. When I run it, I of course have > to wait until it is finished before I can do anything else with > Python. Is it possible to run this function and still be able to do > other things with Python while it is running? Is that what threading > is about? Threads are a complex answer. Subprocesses are a less complex answer. (good sigmonster, have a biscuit) -- \ "I have yet to see any problem, however complicated, which, | `\ when you looked at it in the right way, did not become still | _o__) more complicated." -- Paul Anderson | Ben Finney From christopherlmarshall at yahoo.com Fri Nov 11 13:10:20 2005 From: christopherlmarshall at yahoo.com (christopherlmarshall at yahoo.com) Date: 11 Nov 2005 10:10:20 -0800 Subject: testing C code with python References: <1131661106.277887.308690@z14g2000cwz.googlegroups.com> Message-ID: <1131732620.885285.128020@g43g2000cwa.googlegroups.com> I have recently started using tcl to do this with C++ code and will soon be switching to doing it with python. I think it is a fantastic way to arrange to test C++ and C code. Python makes an excellent test-harness, and writing interfaces for complex units of C++ code to enable them to be tested from Python is an valuable exercise in itself. It forces you to make your code inspectable and brings up all sorts of important design issues that otherwise would never occur to you. It was a lot of work to get started with this but once you put in the initial effort, it gets eaiser to maintiain. And the payoff is that it lets you write regression tests easily so that would be too hard to do otherwise. From cito at online.de Wed Nov 23 16:21:59 2005 From: cito at online.de (Christoph Zwerschke) Date: Wed, 23 Nov 2005 22:21:59 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <4383b600.500692667@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383b600.500692667@news.oz.net> Message-ID: <4384DD77.9080303@online.de> Bengt Richter wrote: > >>> from odictb import OrderedDict > >>> d1 = OrderedDict([(1, 11), (2, 12), (3, 13)]) > >>> d1 > {1: 11, 2: 12, 3: 13} > >>> d1[1:] > {2: 12, 3: 13} > >>> d1[0:1] + d1[2:3] > {1: 11, 3: 13} > >>> d1.reverse() > >>> d1 > {3: 13, 2: 12, 1: 11} > >>> d1.insert(1, (4,14)) > >>> d1 > {3: 13, 4: 14, 2: 12, 1: 11} > >>> d1.items() > [(3, 13), (4, 14), (2, 12), (1, 11)] > >>> d1.keys() > [3, 4, 2, 1] > >>> d1.values() > [13, 14, 12, 11] > >>> d1[1:2] > {4: 14} > >>> d1[-1:] > {1: 11} > > Que mas? Eso es exactamente lo que yo queria haber! -- Chris From steve at REMOVETHIScyber.com.au Fri Nov 4 10:22:04 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 02:22:04 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> Message-ID: On Fri, 04 Nov 2005 09:03:56 +0000, Antoon Pardon wrote: > Op 2005-11-03, Steven D'Aprano schreef : >> On Thu, 03 Nov 2005 13:01:40 +0000, Antoon Pardon wrote: >> >>>> Seems perfectly sane to me. >>>> >>>> What would you expect to get if you wrote b.a = b.a + 2? >>> >>> I would expect a result consistent with the fact that both times >>> b.a would refer to the same object. >> >> class RedList(list): >> colour = "red" >> >> L = RedList(()) >> >> What behaviour would you expect from len(L), given that L doesn't have a >> __len__ attribute? > > Since AFAICT there is no single reference to the __len__ attribute that > will be resolved to two different namespace I don't see the relevance. Compare: b.a += 2 Before the assignment, instance b does not have an attribute "a", so class attribute "a" is accessed. You seem to be objecting to this inheritance. len(L) => L.__len__() Instance L also does not have an attribute "__len__", so class attribute "__len__" is accessed. You don't appear to object to this inheritance. Why object to one and not the other? If you object to b.a resolving to b.__class__.a, why don't you object to L.__len__ resolving to L.__class__.__len__ also? Perhaps you don't object to that half of the problem. Perhaps you object to the assignment: you expect that assigning to b.a should assign to b.__class__.a instead. Should assigning to L[0] assign to L.__class__[0] also, so that all lists share not only the same behaviour, but also the same data? [snip] >> b is a name, and any reference to b (in the same namespace) will refer >> to the same object. At least until you rebind it to another object. > > But some namespaces take great care not to allow a rebinding that would > result in the same name being resolved to a different namespace during > this namespace's lifetime. And some take great care to allow such a rebinding, because that is the right thing to do to make inheritance work correctly. >> But b.a is not a name, it is an attribute lookup, > > An other implementation detail. b.a is a name search of 'a' in the > namespace b. Factually incorrect. b.a is the name search for 'a' in the namespaces [note plural] of b, b.__class__, and any superclasses of b, *in that order*. Do you object to import searching multiple directories? Why do you object to attribute resolution searching multiple namespaces? [snip] >>> I think it even less sane, if the same occurce of b.a refers to two >>> different objects, like in b.a += 2 >> >> Then it seems to me you have some serious design problems. Which would >> you prefer to happen? >> >> # Scenario 1 >> # imaginary pseudo-Python code with no inheritance: class Paragraph: >> ls = '\n' # line separator >> >> para = Paragraph() >> para.ls >> >>=> AttributeError - instance has no attribute 'ls' >> >> >> # Scenario 2 >> # imaginary pseudo-Python code with special inheritance: >> class Paragraph: >> ls = '\n' # line separator >> >> linux_para = Paragraph() >> windows_para = Paragraph() >> windows_para.ls = '\n\r' # magically assigns to the class attribute >> linux_para.ls >> >>=> prints '\n\r' >> >> # Scenario 3 >> # Python code with standard inheritance: >> class Paragraph: >> ls = '\n' # line separator >> >> linux_para = Paragraph() >> windows_para = Paragraph() >> windows_para.ls = '\n\r' >> linux_para.ls >> >>=> prints '\n' >> >> > I don't see the relevance of these pieces of code. In none of them is > there an occurence of an attribute lookup of the same attribute that > resolves to different namespaces. Look a little more closely. In all three pieces of code, you have a conflict between the class attribute 'ls' and an instance attribute 'ls'. In the first scenario, that conflict is resolved by insisting that instances explicitly define an attribute, in other words, by making instance attribute ONLY search the instance namespace and not the class namespace. In the second scenario, that conflict is resolved by insisting that instance.name assigns to instance.__class__.name, just as you asked for. The third scenario is the way Python actually operates. -- Steven. From lycka at carmen.se Thu Nov 24 09:52:52 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 24 Nov 2005 15:52:52 +0100 Subject: defining the behavior of zip(it, it) (WAS: Converting a flat list...) In-Reply-To: <1132782865.993175.92340@g43g2000cwa.googlegroups.com> References: <1132772142.500020.16360@g44g2000cwa.googlegroups.com> <1132782865.993175.92340@g43g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Oh, find a need to shut other up ? > Oh, find a need to get the last word? /Magnus P.S. Yes, this *is* a test. From mde at micah.elliott.name Thu Nov 10 14:36:42 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Thu, 10 Nov 2005 11:36:42 -0800 Subject: Pythonising the vim (e.g. syntax popups) -> vimpst In-Reply-To: <1131644203.723980.185230@f14g2000cwb.googlegroups.com> References: <200511091609.09613.email@christoph-haas.de> <200511100052.01043.r.roelofsen@tuxed.de> <1131644203.723980.185230@f14g2000cwb.googlegroups.com> Message-ID: <20051110193642.GB18475@kitchen.client.attbi.com> On Nov 10, sjdevnull at yahoo.com wrote: > vim... I'll try to get it more polished/functional and put it up on > sourceforge or somewhere. Change "sourceforge or somewhere" to: http://www.vim.org/scripts/add_script.php -- _ _ ___ |V|icah |- lliott http://micah.elliott.name mde at micah.elliott.name " " """ From vinjvinj at gmail.com Wed Nov 9 13:01:34 2005 From: vinjvinj at gmail.com (vinjvinj) Date: 9 Nov 2005 10:01:34 -0800 Subject: Using python for writing models: How to run models in restricted python mode? In-Reply-To: References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> Message-ID: <1131559294.110953.292150@f14g2000cwb.googlegroups.com> Unfortunately this in not an options since all the processes share objects in memory which are about 1gig for each node. Having a copy of this in each user process is just not an options. I think I'm going to use RestrictedPython from zope3 svn which should take care of 70-80 % of the problem. From larry.bates at websafe.com Tue Nov 15 09:04:54 2005 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 15 Nov 2005 08:04:54 -0600 Subject: AJAX => APAX? Or: is there support for python in browsers? In-Reply-To: References: Message-ID: <4379EB06.1050508@websafe.com> Roger Erens wrote: > Hello, > > I remember that the first time I read about Python as a programming > language was when reading the W3C's HTML 4.01 specification a few years > ago. In the section on objects, images and applets > (http://www.w3.org/TR/html401/struct/objects.html) an example was given > like > >

> > > This user agent cannot render Python applications. > > > It's also in the XHTML2.0 specification. Now, is this just a theoretical > example? Or is there a browser that _does_ support python scripts? Or do > we have to place our bets on the Mozilla 1.9 milestone with hard work > being done by Mark Hammond? > > I'm asking because of all the AJAX hype going on. I'd like rather not > delve too deep into JavaScript and use Python instead. > > Any insights to be shared? > > Cheers, > Roger Take a look at this kit: http://www.mochikit.com/ It seems that this is a python programmer that has created JavaScript functions that "feel" a lot like Python. May just be a transitional way to go, but I thought it was interesting anyway. -Larry Bates From juergenkemeter at gmx.de Wed Nov 30 03:06:15 2005 From: juergenkemeter at gmx.de (=?iso-8859-1?Q?J=FCrgen_Kemeter?=) Date: Wed, 30 Nov 2005 21:06:15 +1300 Subject: import Excel csv - files Message-ID: <000001c5f584$f90e7690$6106a8c0@samsungx30> Hi! I have to import all data, stored in an Excel workbook, into a PostgreSQL-database. Herefore, I export Excel spreadsheets as .csv - files. My actual Python script imports this csv-file, and generated PostgreSQL files (.psql), which contain the SQL statements for filling in the database with the Excel data. My actual Problem: The Excel workbook contains several spreadsheets. These are linked through Hyperlinks, and contain several cell comments. How can I export these comments and Hyperlinks using Python? My aim is to store these in a corresponding PostgreSQL table. If it helps, I can send the Excel workbook, and an example .csv-file, via email. I enclosed the script for less email traffic. cheers, Juergen -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: importCSV.zip Type: application/x-zip-compressed Size: 3294 bytes Desc: not available URL: From peter at engcorp.com Fri Nov 11 20:52:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Nov 2005 20:52:57 -0500 Subject: how to start a process and get it's pid? In-Reply-To: References: <43745C93.70907@sitasoftware.lu> <1131713940.819881.6320@g43g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Daniel Crespo wrote: >>>>>>os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") >>>1944 >> >>I don't get the correct PID. >> >>When I do os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") >>I get 168 (for example), while in the tasklist appears notepad.exe with >>the 2476 PID. > > not sure, but the return value looks like a PID, so maybe you're seeing the > PID for the cmd.exe instance used to run the program. or something. I believe it's documented here http://docs.python.org/lib/os-process.html that the return value is not the PID but the "process handle". I believe this can be converted to the PID with a convenient pywin32 call though at the moment I can't recall which. Googling quickly suggests that win32process.GetWindowThreadProcessId(handle) will do the trick (the second item returned is the PID), but I'm fairly sure there's a simpler approach if you keep looking. I recall there being a Cookbook recipe related to this too.... -Peter From csubich.spam.block at spam.subich.block.com Fri Nov 4 09:24:41 2005 From: csubich.spam.block at spam.subich.block.com (Christopher Subich) Date: Fri, 04 Nov 2005 09:24:41 -0500 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: Steven D'Aprano wrote: > On Thu, 03 Nov 2005 14:13:13 +0000, Antoon Pardon wrote: > > >>Fine, we have the code: >> >> b.a += 2 >> >>We found the class variable, because there is no instance variable, >>then why is the class variable not incremented by two now? > > > Because b.a += 2 expands to b.a = b.a + 2. Why would you want b.a = > to correspond to b.__class__.a = ? Small correction, it expands to b.a = B.a.__class__.__iadd__(b.a,2), assuming all relevant quantities are defined. For integers, you're perfectly right. From steve at REMOVEMEcyber.com.au Thu Nov 3 01:31:39 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 03 Nov 2005 17:31:39 +1100 Subject: Getting a function name from string References: <436943e0$0$2083$edfadb0f@dtext02.news.tele.dk> Message-ID: <4369AECB.8000701@REMOVEMEcyber.com.au> David Rasmussen wrote: > If I have a string that contains the name of a function, can I call it? > As in: > > def someFunction(): > print "Hello" > > s = "someFunction" > s() # I know this is wrong, but you get the idea... py> eval("someFunction()") 'Hello' py> eval(s)() # note the second pair of brackets 'Hello' See also exec -- but before you use either eval or exec, make sure you are fully aware of the security implications. Whatever a user could do to your system by sitting down in front of it with a Python interactive session open and typing commands at the keyboard, they can also do remotely if you call exec on input they provide. So you probably don't want to be calling exec on strings that you get from random users via a website. It has been my experience that, more often than not, any time you think you want to evaluate strings, you don't need to. For instance, instead of passing around the name of the function as a string: s = "someFunction" eval(s)() you can pass around the function as an object: s = someFunction # note the lack of brackets s() -- Steven. From eternalsquire at comcast.net Tue Nov 15 18:38:17 2005 From: eternalsquire at comcast.net (The Eternal Squire) Date: 15 Nov 2005 15:38:17 -0800 Subject: Python obfuscation In-Reply-To: <437a5980$0$18815$636a55ce@news.free.fr> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <437a5980$0$18815$636a55ce@news.free.fr> Message-ID: <1132097897.576546.165220@o13g2000cwo.googlegroups.com> My point exactly. A good application of moderate to large size (100K lines of code) is about as large as a single person can write without automation, hence it is of an effort comparable in scope and creativity to a novel. From hancock at anansispaceworks.com Thu Nov 3 13:28:09 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 3 Nov 2005 19:28:09 +0100 (CET) Subject: No subject Message-ID: <20051103182809.C34911E4002@bag.python.org> On Thursday 03 November 2005 07:28 am, venk wrote: > Microsoft can create a competing version of Windows. TCP/IP became a > standard long before Microsoft even acknowledged it's existence. So did > ASCII, the IBM BIOS, and serial ports, to name just a few. Does the > term > "ISO standard" mean anything to you? Regrettably, the assumption that "ISO Standard" = "Open Standard" seems not to hold. I have found a number of ISO standards that are not meaningfully open. I am still a little confused about why anyone would do that. Regarding whether Microsoft has committed a "crime", I believe Tim Daneliuk was attempting to draw the distinction between "criminal" and "civil" offenses, and indeed, I do believe Microsoft has only ever been indicted with the latter. This is a pretty big distinction in the US, I don't know how other countries characterize offenses. For example, one of the big points about so-called "software piracy" is that the recording and movie industry has been trying very hard to conflate "copyright violation" with "theft" -- but the former is only a civil offense, and the latter criminal. Big difference. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From fredrik at pythonware.com Sun Nov 20 16:49:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Nov 2005 22:49:22 +0100 Subject: Delays getting data on sys.stdin.readline() ? References: <86u0e8gc73.fsf@bhuda.mired.org> <6addebae0511201303o60eae3bbp731fb1a4cb4d103@mail.gmail.com> Message-ID: Christian Convey wrote: > So here's what I don't get: If "producer" was retaining its output for > a while for the sake of efficiency, I would expect to see that effect > when I just run "producer" on the command line. That is, I would > expect the console to not show any output from "producer" until > "producer" terminates. But instead, I see the output immediately. So > why, when I pipe the output to "consumer", doesn't "consumer" get > access to that data as its produced unless "consumer" is explicitely > calling sys.stdout.flush(). > > Any thoughts? your terminal is not a pipe. $ man stdout ... CONSIDERATIONS The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline is printed. This can produce unexpected results, especially with debugging output. The buffering mode of the standard streams (or any other stream) can be changed using the setbuf(3) or setvbuf(3) call. Note that in case stdin is associated with a termi? nal, there may also be input buffering in the terminal driver, entirely unrelated to stdio buffering. (Indeed, normally terminal input is line buffered in the kernel.) This kernel input handling can be modified using calls like tcsetattr(3); see also stty(1), and termios(3). ... From robert.kern at gmail.com Mon Nov 28 17:14:21 2005 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 28 Nov 2005 14:14:21 -0800 Subject: Long integer arrays in Python; how? /Carl In-Reply-To: References: Message-ID: Carl wrote: > I have the following problem > > import Numeric > dim = 1 > bits = 32 > v = Numeric.zeros((dim, bits), 'l') > for j in range(bits): > v[0][j] = 1L << bits - j - 1 > > The problem is the last assignment, which is not valid, since the integer is > on the right hand side is to large to be assigned to an array element. Use Numeric.UnsignedInt32 as the data type. -- 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 smitty_one_each at bigfoot.com Sat Nov 12 03:49:31 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Sat, 12 Nov 2005 03:49:31 -0500 Subject: What do you use as symbols for Python ? References: <4372f88a$0$31833$636a15ce@news.free.fr> Message-ID: <87zmoa45es.fsf@bigfoot.com> >>>>> "Gary" == Gary Herron writes: Gary> Erik Max Francis wrote: >> Pierre Barbier de Reuille wrote: > > > >>When you need some symbols in your program, what do you use in >> Python ? >>> >>> For example, an object get a state. This state is more >>> readable if expressed as a symbols, for example "opened", >>> "closed", "error". Typically, in C or C++, I would use an >>> enum for that: enum OBJECT_STATE { opened, closed, error >>> } >>> >>> >> > OPENED, CLOSED, ERROR = range(3) >> >> object.state = OPENED >> >> Gary> Another similar approach that keeps those values together in Gary> a single namespace is this (my favorite): Gary> class State: OPENED, CLOSED, ERROR = range(3) Gary> Then you can refer to the values as State.OPENED Gary> State.CLOSED State.ERROR Gary> The extra clarity (and slight wordiness) of the dotted Gary> notation seems, somehow, quite Pythonic to me. Gary> Gary Herron I think Zoran Isailovski has the last word on the topic: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 From fredrik at pythonware.com Fri Nov 11 16:42:16 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 22:42:16 +0100 Subject: about widget construction kit References: <1d987df30511111331m56785915i33fab94093f3a8c8@mail.gmail.com> Message-ID: Shi Mu wrote: > I tried to install WCK(Widget Construction Kit (WCK)): > > C:\Python23>python tkinter3000-1.0-20031212\setup.py install > Traceback (most recent call last): > File "tkinter3000-1.0-20031212\setup.py", line 23, in ? > WCK_VERSION = setuplib.find_version("WCK/__init__.py") > File "C:\wget2\tkinter3000-1.0-20031212\setuplib.py", line 74, in find_version > for line in open(filename).readlines(): > IOError: [Errno 2] No such file or directory: 'WCK/__init__.py' > > I checked my files and found there is a __init__.py and got confused > why the error came out? if you're using windows, please use a prebuilt version of the WCK. I also recommend using the 1.1b1 release; it's a lot better than 1.0. if you really want to build it yourself, and you have the right compilers and all Tcl/Tk build files in the right places, change to the source directory before running the setup script. From mwm at mired.org Wed Nov 16 14:10:22 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 16 Nov 2005 14:10:22 -0500 Subject: Addressing the last element of a list References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> <1131442540.244858.290110@z14g2000cwz.googlegroups.com> <1131443023.638868.212340@f14g2000cwb.googlegroups.com> <1131605261.41961@yasure> <1131639368.806010.76080@o13g2000cwo.googlegroups.com> <1131639576.624736.32800@z14g2000cwz.googlegroups.com> <863bm46zbh.fsf@bhuda.mired.org> <86r79ji8lt.fsf@bhuda.mired.org> <86k6f9r9sh.fsf@bhuda.mired.org> Message-ID: <863blwpfxd.fsf@bhuda.mired.org> Antoon Pardon writes: > Op 2005-11-15, Mike Meyer schreef : >> Antoon Pardon writes: >>>>> Like having an assignment operator (let use @= for it) next to a >>>>> (re)bind operator. >>>>> We could then have something like the following. >>>>> a = 5 >>>>> b = a >>>>> a @= 7 >>>>> b ==> would result in 7. >>>> You've just overwritten the object referred to by the token "5" in the >>>> source code with the value 7, so you get: >>>> print 5 >>>> 7 >>> You have a valid point, but I think a different approach is possible. >>> Don't make the distinction between mutable and immutable types but >>> between mutable and immutable objects. So an int wouldn't be an >>> immutable type, but 5 would be an immutable object. >>> So the code above I gave would throw an exception, but the following >>> might work. >>> a @= 5 >>> b = a >>> b @= 7 >>> a ==> would result in 7. >> >> Which solves that issue but brings up - well, more issues. What >> happens if the third line is 'b @= "seven"'? Does this require an >> extra level of indirection in the implementation? Avoiding that kind >> of thing was the reason for suggesting this: > > It depends on how far you want to go. > > I think one can argue that in case of an inplace replacement, this > only makes sense if the two objects belong to the same class. So > no extra level of indirection is then required. Now factor in inheritance. Do users of this facility have to worry about static OO typing? That is, two objects that are otherwise completely interchangeable will raise an exception if you try to assign one to a variable holding the other, because they have the wrong type. That seems unpythonic. > Otherwise it really depends on how the builtin objects are implemented. > For user classes, a somewhat simplistic implementation could be > something like: > > def '@=' (one, two): > one.__dict__.clear() > one.__dict__.update(two.__dict__) Wouldn't one.__dict__ = dict(**two.__dict__) be a bit better? Anyway, this won't' work if the class of one of the objects has slots. >> The critical thing is that this doesn't introduce any new facilities >> into the language, just some new syntax, so there's no implementation >> impact. In fact, if you're willing to put up with some notational >> abuse, we can do this now: >> >> class Ref(object): >> _unbound = object() >> def __new__(cls, value = _unbound): >> """We're an object, but need to ignore the optional argument.""" >> >> return object.__new__(cls) >> >> def __init__(self, value = _unbound): >> """Bind the optional value, if provided.""" >> if value is not self._unbound: >> self._value = value >> >> def __pos__(self): >> """Return value, if bound.""" >> try: >> return self._value >> except AttributeError: >> raise ValueError, "%s object does not have a value stored." % \ >> self.__class__.__name__ >> >> def __iadd__(self, value): >> self._value = value >> return self >> >> Usage: >> >>>>> x = Ref.Ref() >>>>> x += 23 >>>>> +x >> 23 >>>>> a = x >>>>> x += 25 >>>>> +a >> 25 >>>>> a += "this is a test" >>>>> +x >> 'this is a test' >> >> Since it doesn't have real lannguage support, things like +x += 25 >> don't work. That's the only obvious gotcha. Maybe ~ would be a better >> prefix. > > I'm a bit puzzled on how you would implement this as real language > support. As far as I understand this only works with Ref objects. Correct. That's the point. > You can't do something like the following. > > l = [3, 7] > a = Ref(l[0]) > > Instead you would have to do something like > l = [Ref(3), Ref(7)] > a = l[0] > > So it seems that if you want to use this idea for implementing langauge > support you will have to wrap all objects in a Ref internally and this > seems some kind of extra indirection too. No, the idea is to expose this class to the user. They would have to explicitly wrap objects that they want to be able to be get a reference to. Other object types can be implemented without having to worry about assigning to them. If you want to assign to an object, you cdreate it as a Ref. You still have to have a special syntax so you can distinguish assigning to a Ref from binding a name, and getting the value of the Ref vs. getting the Ref. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Fri Nov 4 12:32:51 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Nov 2005 17:32:51 +0000 Subject: How can I do this in Python? In-Reply-To: <1131122051.701419.108200@g43g2000cwa.googlegroups.com> References: <1131118052.827738.235590@f14g2000cwb.googlegroups.com> <1131122051.701419.108200@g43g2000cwa.googlegroups.com> Message-ID: David Wahler wrote: > Lad wrote: > >>Hi, >>I have a web program and a user can have access to a page only after he >>logged in. >>So, the program comes with a Login form and the user logins.But I do >>not know how to return the user back to where he came from, after a >>successful login. >> >>Something like this: >> >>PageWhereUserMustBeLogin -------->UserSigned----->- >> >>^------<---------------------------------------------------<----| >> >> >>Thank you for help >> >>L. > > > You'll need to either use a hidden form field or check the HTTP > "Referer" header to determine the page the user was on. Then, just use > an HTTP redirect to send them back to that page. > > Are you using a particular web application framework, or separate CGI > scripts? > Another alternative might be to serve a script that sent the browser back 2 pages in its history, as long as server state hasn't changed in the meantime. 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 cito at online.de Tue Nov 22 14:45:00 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 20:45:00 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <438258f2.411334718@news.oz.net> Message-ID: Magnus Lycka schrieb: >> I still believe that the concept of an "ordered dictionary" ("behave >> like dict, only keep the order of the keys") is intuitive and doesn't >> give you so much scope for ambiguity. > Sure. Others think so too. The problem is that if you and these other > people actually write down exactly how this unambigous ordered dict > should behave, you'll end up with a dozen different sets of semantics, > which can be divided in at least three main groups. That's the point where I dare to disagree. As I have pointed out in another posting in this thread, all other implementations have the same semantics for the basic behavior. I cannot see three different groups. Again, what's so surprising as the "natural" semantics described here: http://mail.python.org/pipermail/python-dev/2005-March/052041.html -- Christoph From dndfan at hotpop.com Wed Nov 16 06:14:33 2005 From: dndfan at hotpop.com (The Prophet) Date: 16 Nov 2005 03:14:33 -0800 Subject: Data Transmission Crash Course Required In-Reply-To: References: <1132091256.975440.34840@f14g2000cwb.googlegroups.com> Message-ID: <1132139673.006576.97230@g47g2000cwa.googlegroups.com> Thank you both for the suggestions. I will look into both of them, as I am eager to learn new things about Python. From mjkeyes at sbcglobal.net Mon Nov 28 10:13:16 2005 From: mjkeyes at sbcglobal.net (Matt Keyes) Date: Mon, 28 Nov 2005 07:13:16 -0800 (PST) Subject: Data Structure in Python like STL Stack? In-Reply-To: <20051128151115.GA8570@unpythonic.net> Message-ID: <20051128151316.82058.qmail@web81503.mail.mud.yahoo.com> I didn't know the list has a pop function - that is what I was looking for. Thanks for the help! jepler at unpythonic.net wrote: What property of the STL stack is important to you? You can use a Python list as a stack. It has methods append() and pop() which run in amortized-constant-time. It can be tested for empty/nonempty in constant time too (if st: # stack is not empty). Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From juho.schultz at helsinki.fi Fri Nov 4 08:16:26 2005 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Fri, 04 Nov 2005 15:16:26 +0200 Subject: Not Equal to Each Other? In-Reply-To: <1131107444.116585.153760@o13g2000cwo.googlegroups.com> References: <1131066067.980875.223790@g43g2000cwa.googlegroups.com> <436ace8a.66565105@news.oz.net> <1131107444.116585.153760@o13g2000cwo.googlegroups.com> Message-ID: ale.of.ginger at gmail.com wrote: > How do I 'define' set? Is there something to include (like import > random)? > set is a built-in type in Python 2.4 If you use 2.3 you can use the sets module with "import sets" > while (choice == 3) and len(set(cellboard[0:8]))==len(cellboard[0:8]): > # DEFINE TWO RANDOM VARIABLES (ONE FOR ARRAY, ONE FOR NUMBER > VALUE) > solvingrandom = random.randint(1,9) > cellboardrandom = random.randint(0,8) > set(cellboard[0:8]) > > # CHECK TO MAKE SURE THE RANDOMLY ASSIGNED CELL DOES NOT HAVE A > VALUE > if (cellboard[cellboardrandom] is not ('1' or '2' or '3' or '4' > or '5' or '6' or '7' or '8' or '9')): > cellboard[cellboardrandom] = solvingrandom > > The above is my code (right now it will only work for the first row's > numbers). Anything else I need to add? > Simplify your code a bit: '2' is not ('1' or '2' or '3' or '4' or '5' or '6' or '7' or '8' or '9') evaluates to True '1' is not ('1' or '2' or '3' or '4' or '5' or '6' or '7' or '8' or '9') evaluates to False Somehow I do not believe you want that behavipur. If cellboard contains characters, you could use: if (cellboard[cellboardrandom] not in '123456789') for integers, the following should work: if not (1 <= cellboard[cellboardrandom] <= 9) Using None to code empty cells, you could even have: if (cellboard[cellboardrandom] is None) From lycka at carmen.se Fri Nov 11 08:34:27 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 11 Nov 2005 14:34:27 +0100 Subject: Python obfuscation In-Reply-To: <1131639786.958533.45070@z14g2000cwz.googlegroups.com> References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131639786.958533.45070@z14g2000cwz.googlegroups.com> Message-ID: petantik wrote: > Alex Martelli wrote: >>I think that's feeble protection. If you have valuable code, and >>distribute it, people WILL crack it -- just check the warez sites for >>experimental proof... EVERYTHING that people are really interested in >>DOES get cracked, no matter what tricky machine-code the "protections" >>are coded in. >> >>There's ONE way to have uncrackable code -- don't distribute it, but >>rather put it up on the net on a well-secured machine under your >>control, available as (say) a webservice (subscription-only, pay per >>use, or whatever business model you want). ... > I think that is not workable because it is easy to say the the internet > is available everywhere. > > It is not available in developing countries... Erh, the internet is certainly spreading to most of the world, and there is an abundance of cracked and pirated software in the poorer countries in the world, so the obfuscation part has certainly proven not to work there. From john106henry at hotmail.com Tue Nov 8 11:10:25 2005 From: john106henry at hotmail.com (John Henry) Date: 8 Nov 2005 08:10:25 -0800 Subject: Invoking Python from Python Message-ID: <1131466225.744361.7010@z14g2000cwz.googlegroups.com> Hi all, I have a need to create a Python script on the fly from another Python program and then execute the script so created. Do I need to invoke Python through os.spawnl or is there a better way? Thanks, -- John From bonono at gmail.com Tue Nov 8 04:35:40 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 8 Nov 2005 01:35:40 -0800 Subject: Addressing the last element of a list In-Reply-To: <1131442291.100013.177610@g44g2000cwa.googlegroups.com> References: <1131440401.916748.309740@g43g2000cwa.googlegroups.com> <1131441127.076800.59110@o13g2000cwo.googlegroups.com> <1131442291.100013.177610@g44g2000cwa.googlegroups.com> Message-ID: <1131442540.244858.290110@z14g2000cwz.googlegroups.com> what do you mean by alias ? a = b now both a and b refers to the same object. pinkfloydhomer at gmail.com wrote: > So there is no way in Python to make an alias for an object? > > /David From jeremy+complangpython at jeremysanders.net Thu Nov 10 04:57:38 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Thu, 10 Nov 2005 09:57:38 +0000 Subject: Using python for writing models: How to run models in restricted python mode? References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> <1131559294.110953.292150@f14g2000cwb.googlegroups.com> Message-ID: vinjvinj wrote: > Unfortunately this in not an options since all the processes share > objects in memory which are about 1gig for each node. Having a copy of > this in each user process is just not an options. I think I'm going to > use RestrictedPython from zope3 svn which should take care of 70-80 % > of the problem. I wonder whether it is possible to fork() the program, restricting the memory usuage for the forked program. In most unix variants, forked programs share memory until that memory is written to. Of course this may not be useful if there's data going back and forth all the time. -- Jeremy Sanders http://www.jeremysanders.net/ From rrr at ronadam.com Mon Nov 7 13:40:50 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 07 Nov 2005 18:40:50 GMT Subject: Tkinter- Building a message box In-Reply-To: <1131387846.676519.184420@g44g2000cwa.googlegroups.com> References: <1131387846.676519.184420@g44g2000cwa.googlegroups.com> Message-ID: Tuvas wrote: > I've been trying to build a fairly simple message box in tkinter, that > when a button is pushed, will pop up a box, that has a line of text, an > entry widget, and a button, that when the button is pushed, will return > the value in the line of text. However, while I can read the value of > the button, I want to wait till the button is pushed to return the > value. Any ideas of how I could do this? The way I do it is to set self.result in the dialog to the return value just before closing and exiting. And then instead of openiug the dialog directly I use a function to pass and sometimes modify the values to the dialog and then return the dialog.result value after it's closed. Something like... def domydialog(*args, **kwds): # # Check and modify args or kwds here if needed. # mydialog(*args, **kwds) return mydialog.result Cheers, Ron From bokr at oz.net Sun Nov 13 19:56:02 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 14 Nov 2005 00:56:02 GMT Subject: Hash map with multiple keys per value ? References: Message-ID: <4377b61c.411226191@news.oz.net> On Fri, 11 Nov 2005 22:55:53 +0000, Chris Stiles wrote: >Hi -- > >I'm working on something that includes the concept of multiple aliases for a >particular object, where a lookup for any of the aliases has to return all the >others. The hack way of doing this was to have a dictionary where each >entry consisted of a list of all the aliases - with multiple references to the >same list from the various dictionary entries corresponding to each alias. > >Is there an easier and cleaner way of doing this ? Is there example code >floating around that I might have a look at ? > [OT about on-T missing post] I see my post on google http://groups.google.com/group/comp.lang.python/msg/7d6056940048f1b6 but I haven't seen it yet on my newsreader. Is it not showing for anyone else either? I am wondering what's happening. Usually it's only a matter of minutes, not a day and counting ;-/ Regards, Bengt Richter From free.condiments at gmail.com Thu Nov 17 22:30:14 2005 From: free.condiments at gmail.com (Sam Pointon) Date: 17 Nov 2005 19:30:14 -0800 Subject: Hot to split string literals that will across two or more lines ? References: Message-ID: <1132284614.326121.252250@g49g2000cwa.googlegroups.com> > print "a string which is very loooooo" \ > + "ooooong." Minor pedantry, but the plus sign is redundant. Python automatically concatenates string literals on the same logical line separated by only whitespace. From gh at ghaering.de Mon Nov 7 09:11:59 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 07 Nov 2005 15:11:59 +0100 Subject: Python and PL/SQL In-Reply-To: <1131369305.252487.30220@o13g2000cwo.googlegroups.com> References: <1131369305.252487.30220@o13g2000cwo.googlegroups.com> Message-ID: <436F60AF.1060004@ghaering.de> vb_bv wrote: > Does Pyton PL/SQL programming language of Oracle support? Python supports calling Oracle PL/SQL procedures. Here's an example using the cx_Oracle database adapter: >>> import cx_Oracle >>> con = cx_Oracle.connect("outlinetest/soca at soca_tsn") >>> cur = con.cursor() >>> cur.execute(""" ... BEGIN ... PKG_Test.Test; ... END; ... """) cx_Oracle also works with all types I needed, including passing ARRAYs to stored procedures, and getting REFCURSORs back. -- Gerhard From jmdeschamps at gmail.com Sun Nov 6 07:28:35 2005 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 6 Nov 2005 04:28:35 -0800 Subject: Python doc problem example: gzip module (reprise) In-Reply-To: <436dc164.259807483@news.oz.net> References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> <7x4q6q7f6b.fsf@ruckus.brouhaha.com> <86hdaqsfjo.fsf@bhuda.mired.org> <7x3bmafrip.fsf@ruckus.brouhaha.com> <86d5lescfd.fsf@bhuda.mired.org> <7x8xw2ea4e.fsf@ruckus.brouhaha.com> <436dc164.259807483@news.oz.net> Message-ID: <1131280114.971847.125580@g43g2000cwa.googlegroups.com> Sorry but I take exception on this subject. I still think Fredrik's Intro to Tkinter is still more usable ... Grayson's book uses PMW extensively, and a lot is about specific widgets of that library. This actually brings us back to the jest of F. previous post, that documentation is question of multiple source reference, and yes that you have to work the field (Google search, newgroups, cookbooks, source-code, et al) a little bit to get some information. In time, one goes from newbie to casual-user, to regular-user and createds his own setof useful references ... Simple ready-to-eat recipes are just that - fast-food for the mind! (Ok some of it is delicious, even nourishing ;-) ) From steve at holdenweb.com Thu Nov 3 07:56:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Nov 2005 12:56:10 +0000 Subject: Class Variable Access and Assignment In-Reply-To: <7xpsphlxri.fsf@ruckus.brouhaha.com> References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <7xpsphlxri.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: > >>>class A: >>> a = 1 >>>b = A() >>>b.a += 2 >>>print b.a >>>print A.a >>>Which results in >>>3 >>>1 >>> >> >>I don't suppose you'd care to enlighten us on what you'd regard as the >>superior outcome? > > > class A: > a = [] > b = A() > b.append(3) > print b.a > print a.a > > Compare and contrast. append() guarantees to modify a mutable object in place. Augmented assignment operations don't,but are "normally" equivalent to name = name operator value In the former case exactly such semantics are implemented. I still don;t see anyone suggesting a better outcome for the augmented assignment. 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 gdamjan at gmail.com Wed Nov 23 22:10:45 2005 From: gdamjan at gmail.com (Damjan) Date: Thu, 24 Nov 2005 04:10:45 +0100 Subject: Unicode in MIMEText Message-ID: Why doesn't this work: from email.MIMEText import MIMEText msg = MIMEText(u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430') msg.set_charset('utf-8') msg.as_string() Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/email/Message.py", line 129, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python2.4/email/Generator.py", line 82, in flatten self._write(msg) File "/usr/lib/python2.4/email/Generator.py", line 113, in _write self._dispatch(msg) File "/usr/lib/python2.4/email/Generator.py", line 139, in _dispatch meth(msg) File "/usr/lib/python2.4/email/Generator.py", line 180, in _handle_text payload = cset.body_encode(payload) File "/usr/lib/python2.4/email/Charset.py", line 366, in body_encode return email.base64MIME.body_encode(s) File "/usr/lib/python2.4/email/base64MIME.py", line 136, in encode enc = b2a_base64(s[i:i + max_unencoded]) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128) -- damjan From callum at gmail.com Tue Nov 22 19:10:10 2005 From: callum at gmail.com (Callum Prentice) Date: 22 Nov 2005 16:10:10 -0800 Subject: Simple photo collage using Python and PIL Message-ID: <1132704610.945593.16100@g47g2000cwa.googlegroups.com> i need a "script" that i can use locally as well as online that will: * create a large (maybe something like 2k x 2k) master image in memory * open a text file and read all the lines from it (maybe 1000 lines max) * each line is composed of an x, y, name and a png image filename * for each line, open the png image and position it in the master image at the location given by x & y * save off the master image to a png at the end i've been told python and the python image library can help me - i haven't used either before so can anyone give me some pointers to get me started please - it feels like it's probably just a few lines of code for an expert (no validation required - i'll be the only one using it) any help much appreciated. -- cal From duncan.booth at invalid.invalid Mon Nov 28 09:18:18 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Nov 2005 14:18:18 GMT Subject: General question about Python design goals References: Message-ID: Antoon Pardon wrote: > I'm sure I could come up with an other example where I would like > to have both some list method and use it as a dictionary key and > again people could start about that implementation having some > flaws and give better implementations. > > I'm just illustrating that some list-like methods with tuples > could be usefull. > But you aren't illustrating that at all. You came up with an example which showed, at least to me, a good argument why tuples should *not* have list methods. If you can come up with a better example that would be good; if any other example is as flawed then perhaps it shows that your basic assumption is wrong. From bearophileHUGS at lycos.com Wed Nov 23 16:26:10 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 23 Nov 2005 13:26:10 -0800 Subject: Mixed types and variants Message-ID: <1132781170.172321.321750@z14g2000cwz.googlegroups.com> Notes: - This email is about Mark Dufour's Shed Skin (SS) (http://shed-skin.blogspot.com), but the errors/ingenuousness it contains are mine. My experience with C++ is limited still. - The following code comes from a discussion with Mark. One of the purposes of SS is to produce fast-running programs (compiling a subset of Python code to C++), to do this it accepts some compromises in the type flexibility used by the programs, at the moment is doesn't allow mixed types (like mixed typed dicts). A future version of SS may support variant types, that are usually quite slow, but they may allow SS to use mixed types. If a SSPython program processes a lot of fixed typed data and few variants, the speed of this program can be roughly the same, but the range of programs that SS can successfully compile can be increased. A variant type may allow SS to manage a dict like this too: d = {1:"2", "1":2} Or a list created dynamically like this: l = [[1,2], [], [], [[3],[4]], [5,[6,7]]] You can find some C++ variant types: cdiggins::any boost::any boost::variant But it seems that these only support 'value types', so how to put a class pointer in such a variant and dynamically call a method? Something like this fails: #include "cdiggins.hpp" #include class bert { public: int zooi() { return 345; } }; int main() { cdiggins::any a = 42; a = new bert(); printf("%d\n", a.zooi() ); } If this is not possible, such variants don't look very useful in general for SS. My possible answers: - "Value" types only can be better than nothing, because such variants can be used to make mixed dicts, those mixed lists, etc. Some functionality reduction is better than an even bigger functionality reduction. - Maybe the boost::variant sourcecode can be modified to allow such functionality too, or part of it. But this may require a LOT of work on the C++ implementation (Mark's idea: maybe a better solution would be to fall back to CPython classes somehow to implement variants...). - Maybe someone here can suggest some other variant type, or some other solution. Bye and thank you, bearophile From deets at nospam.web.de Wed Nov 9 04:10:10 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Nov 2005 10:10:10 +0100 Subject: Installing Tkinter on knoppix In-Reply-To: References: Message-ID: <3tdsnjFsdo3aU2@uni-berlin.de> Jon Monteleone wrote: > Greetings, > Does anybody have a website where I can download a copy of Tkinter to install onto > knoppix? > Is it a pretty straightforward install? Knoppix is debian-based - you can use apt-get. But installing on a CD is impossible - do you want to alter the packages that come with a knoppix? Then you need to create your own distribution based on it (which should be doable, as the plethorea of *ix-distros shows). On a persisted knoppix, just use the above mentioned apt-get. Regards, Diez From Achim.Dahlhoff at t-online.de Tue Nov 29 03:01:52 2005 From: Achim.Dahlhoff at t-online.de (Achim Dahlhoff) Date: Tue, 29 Nov 2005 00:01:52 -0800 Subject: Instantiating classes which are derived from built-in types. Message-ID: Hi. I'm trying to find out the diffrence between normal classes and classes derived from built-in types. (Which is causing me trouble trying to instantiate a class using C API calls) >>> class A: ... pass ... >>> class B(dict): ... pass ... >>> type(A) >>> type(B) >>> When I have a handle to A as a PyObject, I can create an instance using PyInstance_New(). When I have a handle to B, this does not work as the function wants a class PyObject. I found that the API function PyType_GenericNew() can create something from the B type, but it does not call any constructors. (using the 'dict' here is an example. In my case, I'm using a self-defined type I'm using as an API into the C++ part of the software.) Anyone know how an object could be instantiated using a handle to B? thanks, Achim Dahlhoff. From grante at visi.com Fri Nov 18 14:40:18 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 18 Nov 2005 19:40:18 -0000 Subject: Choose meaningful subjects for posts [was: Re: newb ?] References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> <86u0eaj5ed.fsf@bhuda.mired.org> Message-ID: <11nsbh2r64kb9ae@corp.supernews.com> On 2005-11-18, Mike Meyer wrote: >>> http://www.catb.org/~esr/faqs/smart-questions.html#bespecific >>> before you post your next question. If I can't tell from the subject line what the thread is about, I almost never read it. >> Note also that the subject line on an existing thread can be changed, >> though not everyone's software will track the changes, unfortunately. It's >> always worth taking the time to make sure the subject line really does >> describe the subject of your message > > [Since we're giving posting advice.] > > By the same token, don't use a reply to start a new thread. Some software > *will* keep it in the thread, and if they had killed the thread, they won't > see your posts. They don't even have to kill the original thread. By just not expanding the thread they won't see the "new" thread hidden inside the old one. This problem seems to be especially prevelent in c.l.p. (as are fractured threads). I think it's due to people who read the group via an e-mail gateway (particularly the ones who get the digest service). Obligatory aside: I'm completely baffled why anybody would choose the mailing list format over Usenet. I don't even read mailing lists via mailing lists. I recommend gmane.org's NNTP server for all your mailing list needs. -- Grant Edwards grante Yow! It's so OBVIOUS!! at visi.com From paul at boddie.org.uk Thu Nov 10 19:07:56 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Nov 2005 16:07:56 -0800 Subject: Recompile AST? References: <1131657716.197347.167740@g47g2000cwa.googlegroups.com> <4373d1cb.156169219@news.oz.net> Message-ID: <1131667676.954609.211800@o13g2000cwo.googlegroups.com> Bengt Richter wrote: > I've also posted sporadic musings about the possibilities for AST-transforming > custom import functions to do optimizations and macros and special forms etc., > but no one seemed much interested (or maybe they quietly went off to do > something of their own ;-) For an example of AST transformations, take a look at the libxml2macro.py script in the libxml2dom distribution [1]: it contains code which transforms ASTs based on simple rules (changing method calls to function calls) as well as the magic sequence of instructions to generate .pyc files from ASTs. Originally, the analysis distribution [2] also compiled modified ASTs to Python bytecode, but such activities didn't really fit in with the goals of that particular project. Paul [1] http://www.python.org/pypi/libxml2dom [2] http://www.python.org/pypi/analysis From roccomoretti at hotpop.com Wed Nov 16 13:11:41 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 16 Nov 2005 12:11:41 -0600 Subject: Proposal for adding symbols within Python In-Reply-To: <437aeb20$0$21050$636a55ce@news.free.fr> References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> <87psp2ao7s.fsf@lucien.dreaming> <437aeb20$0$21050$636a55ce@news.free.fr> Message-ID: Pierre Barbier de Reuille wrote: > Rocco Moretti a ?crit : > [...] > >> >>I did, but I still don't see why it is an argument against using >>strings. The point you may not appreciate is that (C)Python already uses >>strings to represent names, as an important part of its introspective >>abilities. >> > > > Well, I'm well aware of that, but I'm also well aware that's (as you > said yourself) specific to C-Python, so can just *cannot* rely on > strings being used as symbols in the language. It's true that a different implementation of Python may use a different internal storage system for names, but as long as the semantics are the same as CPython, it really doesn't doesn't matter what the internal storage is. That is to say, as long as the other implementation of Python has __getattr__ and __dict__, you can use strings to represent names, regardless of how the interpreter stores them internally. > The point is, why don't provide the programmer to express just what he > needs (that is, some symbolic value like "opened", "blocked", ...) and > let the interpreter use whatever he think is more efficient for him ? It's just that, for the current interpreters and usage of "symbol-like" construct, the efficiency gained by the interpreter choosing how to represent symbols is probably *far* outweighed by the inefficiency and hassle of implementing and maintaining the symbol syntax in the existing interpreters. Besides, "have the programmer specify intent, and allow the interpreter to substitute a more efficient implementation on the off chance that interpreter can or wants to" doesn't have much cache in the Python community.(1) The interpreter could get more efficiency if it knew a list was fixed length, or contained only ints, or knew that a for loop was looping over consecutive integers, instead of a random list. But despite the possibility that there might exist, at some time in the future, a Python interpreter which *might* optimize such things, we haven't thrown in variable declarations or integer loop syntaxes yet. As I've mentioned before, the key to getting feature put into the language is compelling use cases. Find a (non-hypothetical) Python program or library which would be improved by addition of , and where the existing alternatives are inadequate. Lacking that, any attempt to get a feature into the language is an uphill battle. > But why say a name is a > *string* when it is just an implementation detail ??? Isn't Python > mainly about allowing the programmer to concentrate on important stuff ? One could flip it around and say that names *not* being strings are an implementation detail - after all, what is a name in your source code, besides just a string of ASCII characters? Having just names and strings simplifies things as well - you have only two items to convert between, as opposed to three items (names, symbols and strings). - (1) The future of Python seems to be towards the PyPy way, where the interpreter will analyze your code, and automagically determine the most efficient implementation for your particular use case. From m.amenchar1 at chello.nl Sat Nov 5 20:34:22 2005 From: m.amenchar1 at chello.nl (Mostapha Amenchar) Date: Sun, 6 Nov 2005 02:34:22 +0100 Subject: python problems Message-ID: <000c01c5e272$36f03c30$f708a33e@tadkant91wjg77> http://maven.smith.edu/~thiebaut/classes/111/111.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Wed Nov 30 20:06:11 2005 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 30 Nov 2005 17:06:11 -0800 Subject: wxPython installation issues on Debian In-Reply-To: <438E4984.1010804@ulmcnett.com> References: <1132795557.301034.92000@o13g2000cwo.googlegroups.com> <1133373197.812027.135740@g44g2000cwa.googlegroups.com> <1133388676.563922.55190@g14g2000cwa.googlegroups.com> <438E4984.1010804@ulmcnett.com> Message-ID: Paul McNett wrote: > amhoov at yahoo.com wrote: > >>Thanks a lot for the clarification. I don't have a compelling reason >>not to use 2.3 other than having to install the modules I've already >>set up for 2.4. Not really a big deal. Looks like I'll be switching to >>2.3. > > Umm, for what it's worth: I'm on Ubuntu (a Debian derivative), using Python > 2.4.2 and wxPython 2.6. The wxPython was installed using 'apt-get install > python-wxGtk2.6'. > > So I don't know why you say you need to use Python 2.3 as I don't even have that > on my system. Although Ubuntu is a Debian derivative, it does have different packages. At the moment, Debian's default Python is 2.3 although one can also install Python 2.4, and most Python packages in Debian have been built for both (that's why I erroneously recommended installing the apparently nonexistant python2.4-wxgtk2.4). However, it appears that the maintainer of the Debian wxPython is not building packages for both Python 2.3 and 2.4. The maintainer of the Ubuntu wxPython package apparently is. -- 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 lycka at carmen.se Tue Nov 8 09:41:45 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 08 Nov 2005 15:41:45 +0100 Subject: Lie Hetland book: Beginning Python.. In-Reply-To: References: Message-ID: Vittorio wrote: > Nonetheless, I was unable to find any documentation about such a > different behaviour between Pysqlite and Pysqlite2; from my beginner > point of view the Pysqlite (Magnus' version) paramstyle looks a better > and more pythonic choice and I don't grasp the Pysqlite2 developers' > intentions deviating from that way. Please note that the DB-APIs let you use a foreign language, SQL, in Python strings. Having SQL look Pythonic is hardly a virtue. SQL should look SQLic! The SQL standards clearly state that '?' is the correct symbol for dynamic SQL placeholders. For embedded SQL (which is really moot for Python) it's ':NAME', but '%s' has nothing to do with SQL. Pysqlite supports both '?' and ':NAME', but no longer '%s', which is a blessing in my book. Please note that while there is a rough correspondence between the placeholders in SQL and %s and friends in Python strings, they are far from the same. With SQL placeholders and separately passed parameters, proper implementations of database servers will prevent SQL injection attacks and provde a much better performance than if you build an SQL string with Python's %-operator and %s etc in the SQL string. Proper SQL parameter passing will also mean that parameter quoting is handled for you. On the other hand, you can only use placeholders in certain positions in SQL, so you might need %s as well in SQL strings too, if you for instance need to determine the table to search from in runtime. Using the same symbol for both string substitutions and SQL placeholder such as pysqlite 1 and the MySQL interface does, is not really a bright idea in my opinion. Who thinks this is pretty? sql = "SELECT %s FROM %s WHERE %s = %%s" cur.execute(sql % (col,table,search_col), (param,)) I think it's less confusing with: sql = "SELECT %s FROM %s WHERE %s = ?" cur.execute(sql % (col,table,search_col), (param,)) With %s as placeholder, it's easy to do either... sql = "SELECT %s FROM %s WHERE %s = %s" cur.execute(sql % (col,table,search_col,param)) If you do this, you won't have any help with quoting, you are suceptible to SQL injection attacks, and your performance won't improve if the same query is performed repeatedly with different values for param, since the database server will make a new query execution plan every time. :( or... sql = "SELECT %s FROM %s WHERE %s = %s" cur.execute(sql, (col,table,search_col,param)) If this works with your DB driver, it's likely to be really broken and just work as the previous example. In other words you don't have the benefits in performance, convenience or security that parameter passing provides in dynamic SQL. Of course, the "proper" way, with %s-substitution for e.g. table names and ? for parameters is also open for SQL injection attacks if the values in the strings col, table and search_col above are user input, but since they are plain SQL identifiers, they are much easier to check than arbitrary search values. You'd probably have a set of allowed values, and check that the input was in that set. They are also less likely to come from an untrusted source. The DB-API spec is available at http://python.org/peps/pep-0249.html It's a good read. You could also look at: http://www.thinkware.se/epc2004db/ > I would be very grateful if someone would cast a light over > Pysqlite/Pysqlite2 discrepancies. I'm afraid I haven't seen that anywhere. Some of the more subtle changes probably results from the difference between SQLite 2 and SQLite 3, since these are the versions those Python libraries wrap. As you can see in http://initd.org/tracker/pysqlite/wiki/PysqliteVersions you can use pysqlite 1.1 if you want to use the old pysqlite 1 API. Pysqlite2 is documented here: http://initd.org/pub/software/pysqlite/doc/usage-guide.html It contains a fair amount of examples, but unfortunately no direct comparision with pysqlite 1. From tdwdotnet at gmail.com Fri Nov 25 17:33:44 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Fri, 25 Nov 2005 22:33:44 +0000 Subject: How to find the port a server is listening on (from within the server) Message-ID: <9afea2ac0511251433o5a93718ci@mail.gmail.com> How can I find the port a server is listening on - at the commented line in the code below. (ie self.serving_on_port_num = ????? ) I have googled a lot. :-( ------------------------------------------------------------------ class BaseSrvr(SocketServer.ThreadingMixIn, SocketServer.TCPServer): def server_bind(self): """Override server_bind to store the server name.""" try: SocketServer.TCPServer.server_bind(self) host, port = self.socket.getsockname() self.server_name = socket.getfqdn(host) self.server_port = port except: print "*******server bind except************" class RequestHandler(SocketServer.StreamRequestHandler): def handle(self): self.incoming_port = self.client_address[1] #===> self.serving_on_port_num = ????? # The number of the serving port not the connecting port def StartServer(port): server = BaseSrvr(('', int(port) ), RequestHandler ) server.serve_forever() if __name__ == '__main__': StartServer(port) ------------------------------------------------------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Wed Nov 9 23:12:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 10 Nov 2005 04:12:46 +0000 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <1131595096.310029.98740@g43g2000cwa.googlegroups.com> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131595096.310029.98740@g43g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > "bonono at gmail.com" wrote: > > >>Alex Martelli wrote: >> >>>This becomes a valid list comprehension by writing 'if' instead of >>>'when'. >> >>valid, yes. efficient, I am not sure. >> >>[ x for x in xrange(10000000) if p(x) ] >> >>means I need to go through the whole range even if p = lambda x: x < 2 > > > Itertools is your friend in this case: > >>>>from itertools import takewhile >>>>list(takewhile(p, xrange(10000000))) > > [0, 1] Maybe, but the code also implies an esoteric knowledge that the trught value of the predicate is monotonically decreasing (in a Boolean sense). This would not be true if (e.g.) p = lambda x: x % 2 == 0. So while itertools.takewhile can save you unnecessary computations, such savings rely on provable conditions of the predicate which are frequently false. 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 christopherlmarshall at yahoo.com Thu Nov 10 21:33:32 2005 From: christopherlmarshall at yahoo.com (christopherlmarshall at yahoo.com) Date: 10 Nov 2005 18:33:32 -0800 Subject: derived / base class name conflicts In-Reply-To: References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> Message-ID: <1131676411.993022.63210@f14g2000cwb.googlegroups.com> Steve Juranich wrote: > This should prove most enlightening: > > import Tkinter > dir(Tkinter.Canvas) > > Huh? Chris Marshall From tim.golden at viacom-outdoor.co.uk Mon Nov 28 09:43:44 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 28 Nov 2005 14:43:44 -0000 Subject: speeding up Python when using wmi Message-ID: <9A28C052FF32734DACB0A288A3533991044D237E@vogbs009.gb.vo.local> [rbt] > Here's a quick and dirty version of winver.exe written in Python: [.. snip ..] > It uses wmi to get OS information from Windows... it works well, but > it's slow... too slow. Is there any way to speed up wmi? > In the past, I used the platform and sys modules to do some of what > winver.exe does and they were rather fast. However, since switching to > wmi (for a more accurate representation) thinngs have gotten slow... > real slow. > I suppose this could be a wmi only issue not related at all to Python. In short, I recommend replacing the wmi module by the underlying calls which it hides, and replacing Tkinter by a win32gui MessageBox. The wmi module does some magicish things which are useful for interactive browsing, but will only slow you down if you know exactly what you need. As you don't need anything more than a native message box, don't bother with GUI loops etc. Windows will do that for you in a Modal Dialog (here message box). This was going to be a longer post comparing versions, but in short running this code: import win32gui import win32com.client for os in win32com.client.GetObject ("winmgmts:").InstancesOf ("Win32_OperatingSystem"): win32gui.MessageBox ( 0, os.Properties_ ("Caption").Value + "\n" + \ os.Properties_ ("TotalVisibleMemorySize").Value + "\n" + \ os.Properties_ ("Version").Value + "\n" + \ os.Properties_ ("CSDVersion").Value, "Platform Info", 0 ) is nearly as fast as running its VBS equivalent: For Each os in GetObject("winmgmts:").InstancesOf ("Win32_OperatingSystem") WScript.Echo os.Caption & VbCr & _ os.TotalVisibleMemorySize & VbCr & _ os.Version & VbCr & _ os.CSDVersion & VbCr Next So, if you want to use Python, you could use the script above, but if you don't care, use VBScript, which probably has a favoured place in the Windows World (tm). TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From yongsheng.yang at gmail.com Wed Nov 9 21:03:45 2005 From: yongsheng.yang at gmail.com (david) Date: 9 Nov 2005 18:03:45 -0800 Subject: Looking Python script to compare two files In-Reply-To: <1131587940.702181.314750@g44g2000cwa.googlegroups.com> References: <1131587940.702181.314750@g44g2000cwa.googlegroups.com> Message-ID: <1131588225.446267.318260@f14g2000cwb.googlegroups.com> Hello Tim: One more thing: There some Python scripts that can extract text from PDF or WORD file? Thx From bdesth.quelquechose at free.quelquepart.fr Tue Nov 8 20:28:39 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 09 Nov 2005 02:28:39 +0100 Subject: Diff. between Class types and classic classes In-Reply-To: References: <1131454786.272355.314740@z14g2000cwz.googlegroups.com> <4370ba00$0$7529$626a14ce@news.free.fr> Message-ID: <437146a3$0$19243$626a54ce@news.free.fr> Colin J. Williams a ?crit : > bruno at modulix wrote: > >> venk wrote: >> >>> Hi, >>> can some one properly explain the differences between class types and >>> classic classes? ... Still face problems in identifying what is what. >> >> >> >> I'm not sure I understand your question. Are you talking about the diff >> between old-style and new-style classes, or the diff between classes and >> metaclasses ? >> > "new" classes inherit from object. Classic classes do not. (snip) > > I hope that this helps. Colin, I don't personaly need much help with this !-) In fact, your answer is almost the same as the one I was going to post - before I re-read the OP's question. And I'm still not sure that what the OP is looking for. From lycka at carmen.se Mon Nov 7 13:10:49 2005 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 07 Nov 2005 19:10:49 +0100 Subject: when and how do you use Self? In-Reply-To: References: Message-ID: Tieche Bruce A MSgt USMTM/AFD wrote: > Well, thanx for all the ... useful information. > > I thought that I would try, but this has turned out to be a waist of my time. As with all studying, it might be somewhat time consuming to filter out the useful stuff in a sea of information. You did get correct and useful advice from two Python luminaries. If you can't see that in all the noise, it's all your loss. From twic at urchin.earth.li Mon Nov 21 13:50:51 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 21 Nov 2005 18:50:51 +0000 Subject: Any royal road to Bezier curves...? In-Reply-To: References: Message-ID: On Sun, 20 Nov 2005, Warren Francis wrote: > Basically, I'd like to specify a curved path of an object through space. > 3D space would be wonderful, but I could jimmy-rig something if I could > just get 2D... Are bezier curves really what I want after all? No. You want a natural cubic spline: http://mathworld.wolfram.com/CubicSpline.html This is a fairly simple curve, which can be fitted through a series of points (called knots) in space of any dimensionality, without the need to specify extra control points (unlike a Bezier curve), and which has the nice property of minimising the curvature of the curve - it's the shape you'd get if you ran a springy wire through your knots. It usually looks pretty good too. Google will help you find python implementations. There are other kinds of splines - Catmull-Rom, B-spline (a generalisation of a Bezier curve), Hermite - but they mostly don't guarantee to pass through the knots, which might make them less useful to you. In the opposite direction on the mathematical rigour scale, there's what i call the blended quadratic spline, which i invented as a simpler and more malleable alternative to the cubic spline. It's a piecewise parametric spline, like the cubic, but rather than calculating a series of pieces which blend together naturally, using cubics and linear algebra, it uses simple quadratic curves fitted to overlapping triples of adjacent knots, then interpolates ('blends') between them to draw the curve. It looks very like a cubic spline, but the code is simpler, and the pieces are local - each piece depends only on nearby knots, rather than on all the knots, as in a cubic spline - which is a useful property for some jobs. Also, it's straightforward to add the ability to constrain the angle at which the curve passes through a subset of the knots (you can do it for some knots, while leaving others 'natural') by promoting the pieces to cubics at the constrained knots and constraining the appropriate derivatives. Let me know if you want more details on this. To be honest, i'd suggest using a proper cubic spline, unless you have specific problems with it. tom -- ... a tale for which the world is not yet prepared From bokr at oz.net Fri Nov 18 15:32:21 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 18 Nov 2005 20:32:21 GMT Subject: Yield in a wrapper function References: <1132319319.419585.9600@g44g2000cwa.googlegroups.com> Message-ID: <437e39cc.141216368@news.oz.net> On 18 Nov 2005 05:08:39 -0800, "peterbe at gmail.com" wrote: >This works exactly as you would expect:: > > from time import sleep > def foo(on='ABC'): > for e in list(on): > sleep(1) > yield e > >When I run this on the command line It takes about 3 seconds to >complete and the first letter is shown after 1 second. >But, how do I wrap the function somewhere else:: > > from time import sleep > def foo(on): > for e in list(on): > sleep(1) > yield e > > def wrapper(x): > if x < 0: > return foo('ABC') > else: > return foo('XYZ') > >When I run this, variable three letters are shown and it takes 3 >seconds for the whole thing to complete. The problem is that the whole >iteration is glogged up in the wrapper() function because the first >letter is shown after 3 seconds and then all letters are shown at the >same time. > >How do I wrap functions that return iterators? ...if possible. > Make the wrapper itself an iterable? E.g., is this the effect you wanted? >>> from time import sleep >>> def foo(on): ... for e in on: ... sleep(1) ... yield e ... >>> def wrapper(x): ... if x < 0: ... for e in foo('ABC'): yield e ... else: ... for e in foo('XYZ'): yield e ... >>> wrapper(-1) >>> import sys >>> for c in wrapper(-1): sys.stdout.write(c); sys.stdout.flush() ... ABC>>> >>> for c in wrapper(+1): sys.stdout.write(c); sys.stdout.flush() ... XYZ>>> Regards, Bengt Richter From bonono at gmail.com Wed Nov 9 13:53:01 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 9 Nov 2005 10:53:01 -0800 Subject: Python obfuscation In-Reply-To: References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> Message-ID: <1131562381.449032.299630@g14g2000cwa.googlegroups.com> How effective can it be when python is designed to make writing this kind of code hard(hopefully impossible) ? The most effective would be renaming function and may be variables but if the functions are kept short, they would at most looks like haskell ;-) Fredrik Lundh wrote: > hmm. is google down today? > > http://www.lysator.liu.se/~astrand/projects/pyobfuscate/ > > pyobfuscate is a source code obfuscator: It makes Python source code > hard to read for humans, while still being executable for the Python > interpreter. > > From 8273grkci8q8kgt at jetable.net Thu Nov 17 22:40:45 2005 From: 8273grkci8q8kgt at jetable.net (Lars Kellogg-Stedman) Date: Thu, 17 Nov 2005 21:40:45 -0600 Subject: Zope vs Php References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> <86br0in877.fsf@bhuda.mired.org> <87hdaa3brc.fsf@jupiter.g2ctech> <86oe4iljz4.fsf@bhuda.mired.org> Message-ID: > While I'm at it - how does KID do for things that aren't HTML? I've taken a brief look over the Kid documentation. It looks like Kid is in the same class of solutions as Zope's TAL (or Perl's Petal). In particular, a Kid template is always a valid XML document, so your designers can open a Kid template in their favorite HTML editor and it won't cause any weird errors. Similarly, you can open the template in a browser while you're working on layout, which I've certainly found useful working with Petal. There's a Kid language specification here: http://kid.lesscode.org/language.html There's a standlone Python TAL implementation here: http://www.owlfish.com/software/simpleTAL/ -- Lars -- Lars Kellogg-Stedman <8273grkci8q8kgt at jetable.net> This email address will expire on 2005-11-23. From jandre_balt at yahoo.co.uk Wed Nov 16 11:37:31 2005 From: jandre_balt at yahoo.co.uk (Jandre) Date: 16 Nov 2005 08:37:31 -0800 Subject: Script to export MySQL tables to csv References: <1131623709.334036.58800@g43g2000cwa.googlegroups.com> Message-ID: <1132159051.905611.256180@o13g2000cwo.googlegroups.com> Thnaks to everybody for their input. I have found a quick fix for now. MySQL dump allows me to export the data to XML which can easily be compared. This will help me for now and the project will have to wait until I have some more time. Regards Jandre From nico-NoSp at m-tekNico.net Tue Nov 29 15:20:08 2005 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Tue, 29 Nov 2005 21:20:08 +0100 Subject: Death to tuples! In-Reply-To: <86y839ux1j.fsf@bhuda.mired.org> References: <86y839ux1j.fsf@bhuda.mired.org> Message-ID: <438d4cb3_3@newsgate.x-privat.org> > The new intended use is as an immutable sequence type, not a > "lightweight C struct". The new name to denote this new use - > following in the footsteps of the set type - is "frozenlist". The > changes to the implementation would be adding any non-mutating methods > of list to tuple, which appears to mean "index" and "count". Yeah, I like this! "frozenlist" is nice, and we get a "real" immutable sequence for a change. -- Nicola Larosa - nicoNoSp at m-tekNico.net She was up the learning curve like a mountain goat. -- WasterDave on Slashdot, October 2005 From adelacuadras at udd.cl Mon Nov 14 09:58:29 2005 From: adelacuadras at udd.cl (Andres de la Cuadra) Date: Mon, 14 Nov 2005 11:58:29 -0300 Subject: Pregunta sobre python Message-ID: Hola, me llamo Andres de la cuadra, soy un usuario de python en chile y me gustar?a saber como puedo cerrer un programa a trav?s de python. Yo se que con la librer?a os puedo ejecutar programas, pero no e encontrado una librer?a para poder cerrarlos Gracias From walterbrunswick at sympatico.ca Wed Nov 2 00:01:53 2005 From: walterbrunswick at sympatico.ca (Walter Brunswick) Date: Wed, 2 Nov 2005 00:01:53 -0500 Subject: Importing Modules References: Message-ID: The purpose is rather irrelevant. The modules could be used for an assortment of tasks. By conditionals I mean if the name of a module contains a substring, such as "asdf" (i.e. "asdf" in module) or matches a pattern of some sort, for example, all modules which match the regex "module[\d]+\.py", which could be "module5.py" or "module11199.py" or "module345.py". From cito at online.de Tue Nov 22 16:06:12 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 22:06:12 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> Message-ID: > d1[0:0] + d1[2:2] ==> OrderedDict( (1, 11), (3, 13) ) Oops, sorry, that was nonsense again. I meant d1[0:1] + d1[1:2] ==> OrderedDict( (1, 11), (3, 13) ) > Ordered dictionaries could allow slicing and concatenation. Some operations such as concatenation need of course special considerations, since the keys must stay unique. A concatenation of ordered dicts with overlapping keys should probably give an IndexError. -- Christoph From aleax at mail.comcast.net Mon Nov 14 23:31:10 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Mon, 14 Nov 2005 20:31:10 -0800 Subject: best way to discover this process's current memory usage, cross-platform? References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <43795CBC.2020107@REMOVEMEcyber.com.au> Message-ID: <1h61a4x.15mt3h7199q48tN%aleax@mail.comcast.net> Steven D'Aprano wrote: > Not sure if I should start a new thread or not, but > since this is closely related, I'll just leave it as is. > > Alex Martelli wrote: > > > Having fixed a memory leak (not the leak of a Python reference, some > > other stuff I wasn't properly freeing in certain cases) in a C-coded > > extension I maintain, I need a way to test that the leak is indeed > > fixed. > > I would like to investigate how much memory is used by > Python objects. My motive is 98% pure intellectual > curiosity and 2% optimization. I believe that's the purpose of the PySizer project (one of the "Google Summer of Code" projects), which was recently announced on this group (I'm sure any search engine will be able to direct you to it, anyway). I have not checked it out, because my purpose is different -- mine is not a Python-related leak at all, just a leak within C code (which happens coincidentally to be a Python extension module). Alex From stefan.arentz at gmail.com Thu Nov 3 09:37:54 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 03 Nov 2005 15:37:54 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> Message-ID: <874q6tlrul.fsf@keizer.soze.com> Stefan Arentz writes: > Antoon Pardon writes: > > ... > > > Fine, we have the code: > > > > b.a += 2 > > > > We found the class variable, because there is no instance variable, > > then why is the class variable not incremented by two now? > > Because it really is executed as: > > b.a = b.a + 2 > > 1. get 't'b.a and store it in a temporary 't' (found the instance) Oops. 1. get b.a and store it in a temporary 't' (found the class variable 'a') S. From mwm at mired.org Wed Nov 30 23:15:26 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 23:15:26 -0500 Subject: HTML parsing/scraping & python References: Message-ID: <86br01mp0h.fsf@bhuda.mired.org> Sanjay Arora writes: > We are looking to select the language & toolset more suitable for a > project that requires getting data from several web-sites in real- > time....html parsing/scraping. It would require full emulation of the > browser, including handling cookies, automated logins & following > multiple web-link paths. Multiple threading would be a plus but not > requirement. Believe it or not, everything you ask for can be done by Python out of the box. But there are limitations. For one, the HTML parsing module that comes with Python doesn't handle invalid HTML very well. Thanks to Netscape, invalid HTML is the rule rather than the exception on the web. So you probably want to use a third party module for that. I use BeautifulSoup, which handles XML, HTML, has a *lovely* API (going from BeautifulSoup to DOM is always a major dissapointment), and works well with broken X/HTML. That sufficient for my needs, but I haven't been asked to do a lot of automated form filling, so the facilities in the standard library work for me. There are third party tools to help with that. I'm sure someone willsuggest them. > Can you suggest solutions for python? Pros & Cons using Perl vs. Python? > Why Python? Because it's beautiful. Seriously, Python code is very readable, by design. Of course, some of the features that make that happen drive some people crazy. If you're one of them, then Python isn't the language for you. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From g.tagliarettiNO at SPAMparafernalia.org Sun Nov 6 13:12:36 2005 From: g.tagliarettiNO at SPAMparafernalia.org (Gian Mario Tagliaretti) Date: Sun, 06 Nov 2005 19:12:36 +0100 Subject: I need Motivation References: <1h5h37v.1137jn51yis6zmN%aleax@mail.comcast.net> Message-ID: <436e3982$0$22284$4fafbaef@reader1.news.tin.it> Alex Martelli wrote: > Not without knowing more about your motivations for starting Python in > the first place... Alex, maybe trolling in this list? :) > Alex ciao -- Gian Mario Tagliaretti PyGTK GUI programming http://www.parafernalia.org/pygtk/ From fredrik at pythonware.com Fri Nov 18 02:13:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Nov 2005 08:13:28 +0100 Subject: newb ? References: <24aff.11701$cd1.3243@bignews5.bellsouth.net> Message-ID: Chad Everett wrote: > I am back. > No I am not a high school or college student. your subject lines still suck. please read this http://www.catb.org/~esr/faqs/smart-questions.html#bespecific before you post your next question. (the entire article is worth reading, if you haven't done so already) From bokr at oz.net Fri Nov 11 21:42:06 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 12 Nov 2005 02:42:06 GMT Subject: Change directory not successfully done References: Message-ID: <437550cd.254219878@news.oz.net> On Fri, 11 Nov 2005 10:16:02 +0800, Samuel Yin wrote: >Hi, guys, > >This should be a simple problem, but I just can not resolve it. I just >want to use a python script to change my working directory. see my >following code: > ># mycd.py >1) destdir = "xxxxxxxx" >2) command = "cd "+ destdir >3) os.system(command) >4) os.chdir(destdir) > >But neither 3) nor 4) is used, I just can not change the directory after >execute mycd.py. This remind me of bash script. If you change directory I think you are reminded well. It is no use to create a throwaway child process that has the working directory you want, but is just thrown away along with the process ;-) >in your bash script file, it will only impact the sub process of that >script, except that you invoke that bash script by ./script_file_name. >But what should I do in the case of python script? If you do 1) 2) and 4) _within_ your script, the process that is running your script should see the new working directory. E.g., interactively, >>> import os >>> os.getcwd() 'C:\\pywk\\grammar\\ast' >>> os.chdir('..') >>> os.getcwd() 'C:\\pywk\\grammar' But if you execute 1) 2) and 4) by running mycd.py (comment out "3)") in a separate process like os.system('python mycd.py') or such, that's only going to throw it away. If you really want the directory change as a script that will affect your running script, import it or execfile it. E.g., >>> open('mycd.py','w').write("""\ ... import os ... print 'changing cwd %s to parent =>'%(os.getcwd()), ... os.chdir('..') ... print os.getcwd() ... """) Ok see where we are >>> import os >>> os.getcwd() 'C:\\pywk\\grammar' Now see if importing the module we just wrote will do what it's supposed to >>> import mycd changing cwd C:\pywk\grammar to parent => C:\pywk Check effect >>> os.getcwd() 'C:\\pywk' Seems like it worked. But note: (BTW we now have to specify the old subdirectory from current working dir in order to reach mycd.py ;-) >>> os.system('py24 grammar\\mycd.py') changing cwd C:\pywk to parent => C:\ 0 >>> os.getcwd() 'C:\\pywk' I.e., changed but thrown away with subprocess Does this help? Regards, Bengt Richter From pmartin at snakecard.com Tue Nov 8 12:23:04 2005 From: pmartin at snakecard.com (Philippe C. Martin) Date: Tue, 08 Nov 2005 17:23:04 +0000 Subject: user account logon from python References: Message-ID: That helps a lot, thanks. Regards, Philippe jepler at unpythonic.net wrote: > "login APIs" vary widely from system to system. > > Classic Unix systems use calls like getpwent and crypt to check passwords, > and then call setuid, setgid and setgroups to set the identity of the user > who is > logging in. These are all available in stock Python, check the library > reference for more details. Other login-time activities, like writing > utmp entries, may not be directly available in stock Python modules. > > Many modern Linux systems use something called 'pam' for login-related > activities, and there seems to be something called 'python-pam' out there, > but I've never used it. > > Graphical login managers have their own additional requirements, such as > starting and stopping the X server, managing the X authentication > information, etc. > > Jeff From deets at nospam.web.de Thu Nov 17 13:35:14 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Nov 2005 19:35:14 +0100 Subject: Current execution frame of another thread? In-Reply-To: References: Message-ID: <3u40qvFvdc5fU2@uni-berlin.de> skip at pobox.com wrote: > I would like to try a sampling approach to profiling. My thought is to have > a profiling thread that samples the execution frame of all the other > started threads. I don't see any path from the threads returned by > threading.enumerate() to their current frames. Am I missing something? Just another thought: Maybe stackless python can be of use here - as it epxlicits the stack frame, you might be able to inspect it. But I _think_ basically the same limitations apply as in my other post - you'd need to be able to stop a thread, scan its frame, and reschedule it. Diez From bonono at gmail.com Tue Nov 22 23:17:29 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 20:17:29 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <4383e912.513766727@news.oz.net> References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> <1132715742.672265.259740@o13g2000cwo.googlegroups.com> <4383e912.513766727@news.oz.net> Message-ID: <1132719449.516504.268980@z14g2000cwz.googlegroups.com> Bengt Richter wrote: > For me the implication of "sorted" is that there is a sorting algorithm > that can be used to create an ordering from a prior state of order, > whereas "ordered" could be the result of arbitrary permutation, e.g., > manual shuffling, etc. Of course either way, a result can be said > to have a particular defined order, but "sorted" gets ordered > by sorting, and "ordered" _may_ get its order by any means. > But Alex seems to think that based on another external table should be classified as "sorted" whereas I would consider it as "manual shuffling", thus "ordered". I may be wrong it interpreting him though, which is why I want to clarify. From lsumnler at uniqueinsuranceco.com Thu Nov 3 07:35:25 2005 From: lsumnler at uniqueinsuranceco.com (LenS) Date: 3 Nov 2005 04:35:25 -0800 Subject: wxGlade will not run on my machine Message-ID: <1131021325.908977.17230@f14g2000cwb.googlegroups.com> I have installed wxGlade on a MS XP machine. It executed on completion of the install. However, when I try to double click on the wxGlade icon to start nothing happens. I searched the NG and found that this had been report before but no solution was posted. I am running the following versions; Python 2.4.1 wxPython 2.6.1.0 Would like to give wxGlade a try. Len Sumnler From http Tue Nov 29 17:35:51 2005 From: http (Paul Rubin) Date: 29 Nov 2005 14:35:51 -0800 Subject: Which License Should I Use? References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com> <7xu0dvsn5e.fsf@ruckus.brouhaha.com> Message-ID: <7xd5kj9j5k.fsf@ruckus.brouhaha.com> Robert Kern writes: > Is that why the CC Public Domain Dedication has the subtitle > "Copyright-Only Dedication (based on United States law) or Public Domain > Certification"? > > Lessig isn't sure. E.g. http://www.lessig.org/blog/archives/001066.shtml Hmm, interesting, thanks. > > When I wrote Mr. Rosen asking about it, he didn't answer. > He's a lawyer. Getting a legal opinion from him costs money. A legal opinion means something specific. I didn't ask him for one. From noway at sorry.com Thu Nov 24 19:20:43 2005 From: noway at sorry.com (Giovanni Bajo) Date: Fri, 25 Nov 2005 00:20:43 GMT Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org><868xvezb2k.fsf@bhuda.mired.org> <871x15vcdc.fsf@lucien.dreaming> Message-ID: Bj?rn Lindstr?m wrote: >> My feeling is that you're trying to get too much out of my words. I'm >> not trying to handcuff anyone. You seem to concentrate on me trying >> to avoid people adding attributes to my precious objects. It's not >> that. If I write a class and want it to be immutable, it is because >> it has to be so. If I write a queue class and I say that people >> shouldn't call pop() if it's empty, I mean it. If I enforce it with a >> RuntimeError, I'm not thinking I'm handcuffing someone. I don't see a >> ImmutableError to be so different from it. > > But why would you call it that, when the object isn't actually > implemented as immutable? I think you misunderstood my message. I'm saying that an ImmutableError wouldn't be a much different form of self-checking compared to the usual TypeError/ValueError/RuntimeError you get when you pass wrong values/types to methods/functions, or you violate invariants of objects. This has nothing to do with dynamism, duck typing, dynamic binding and whatnot. Some objects have deep invariants which can't be broken. Why do you think we have a frozenset, for instance? By Mike's argument, we shouldn't have it. And we should be able to use a regular mutable set as dictionary key. Unittests will catch errors. Instead, we got two classes instead of one, immutability is *enforced*, and sets can't be used as dictionary keys. This is all good in my opinion, and follows the good rule of "catch errors early". > Throw an exception that describes why it doesn't make sense to change > that particular object instead. *How* can I do? There is no language construct which lets me specifies an exception to throw whenever someone modifies my object. *Even* if I got partial support for immutable types (like __new__ which can be used to initialize immutable objects). > As I said before, I think you're confusing the (in Python pretty > non-existent) concept of encapsulation with Python's immutable types, > which are immutable because the implementation demands it. (A fact I > hope will disappear at some point.) You seriously believe that strings, integers and tuples are immutable because of implementation details? I believe they are part of a language design -- and a good part of it. -- Giovanni Bajo From noahbedford at gmail.com Thu Nov 24 23:53:52 2005 From: noahbedford at gmail.com (noah bedford) Date: Thu, 24 Nov 2005 23:53:52 -0500 Subject: OT: loop help References: Message-ID: <20051124235352.44e927b4@localhost.localdomain> On Thu, 27 Oct 2005 07:00:34 GMT Gorlon the Impossible wrote: >I am using Python 2.3.5 with IDLE 1.0.5 on a Windows98 PC. Just had to say it... MicroSoft makes PCs now? -\n From bokr at oz.net Thu Nov 17 22:47:24 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 18 Nov 2005 03:47:24 GMT Subject: Simulating call-by-reference References: Message-ID: <437d41ce.77730340@news.oz.net> On Thu, 17 Nov 2005 10:03:50 GMT, Rikard Bosnjakovic wrote: >I'm tidying up some code. Basically, the code runs a bunch of >regexp-searches (> 10) on a text and stores the match in a different variable. > >Like this: > > re1 = r' ..(.*).. ' > re2 = r' .... ' > re3 = r' .(.*).. ' > ... > m = re.search(re1, data) > if m: > myclass.bar = m.group(1) > > m = re.search(re2, data) > if m: > myclass.foo = m.group(1) > > m = re.search(re3, data) > if m: > myclass.baz = m.group(1) > > >While this code works, it's not very good looking. > >What I want is to rewrite it to something like this: > > l = [ (re1, myclass.bar), > (re2, myclass.foo), > (re3, myclass.baz), > ] > > for (x,y) in l: > m = re.search(x, y) > if m: > y = m.group(1) > >But since Python doesn't work that way, that idea is doomed. What I'm >looking for are other (better) ways or pointers to accomplish this task of >cleanup. > You could tag your regexs with the foo bar baz names, and pre-compile them. Then you could do something like >>> import re >>> re1 = re.compile(r'(?P\d+)') # find an int >>> re2 = re.compile(r'(?P[A-Z]+)') # find a cap seq >>> re3 = re.compile(r'(?P[a-z]+)') # find a lower case seq >>> >>> data = 'abc12 34CAPS lowercase' >>> >>> class myclass(object): pass # ?? ... >>> class myotherclass(object): pass # ??? ... >>> L = [ (re1, myclass), ... (re2, myclass), ... (re3, myotherclass), ... ] >>> for (rx, cls) in L: ... m = rx.search(data) ... if m: ... setattr(cls, *m.groupdict().items()[0]) ... >>> myclass.bar '12' >>> myclass.foo 'CAPS' >>> myotherclass.baz 'abc' Of course, this is only finding a single group, so this specific code might not work for other searches you might like to do. Also, if you don't need an alternate myotherclass, DRY says don't repeat it in L. I.e., you could write (spelling myclass more conventionally) >>> class MyClass(object): pass # ?? ... >>> L = (re1, re2, re3) >>> for (rx) in L: ... m = rx.search(data) ... if m: setattr(MyClass, *m.groupdict().items()[0]) ... >>> for k,v in MyClass.__dict__.items(): print '%15s: %r'%(k,v) ... __module__: '__main__' bar: '12' baz: 'abc' __dict__: foo: 'CAPS' __weakref__: __doc__: None >>> for it in (it for it in MyClass.__dict__.items() if not it[0].startswith('_')): print '%15s: %r'%it ... bar: '12' baz: 'abc' foo: 'CAPS' The setattr(MyClass, *m.groupdict().items()[0]) just makes an assignment of whatever comes out to be the first of name-tagged matches (of which there has to at least one here also). If you want several name-tagged matches in a single regex, you could do that and do a setattr for each item in m.groubdict().items(). What else you can do is only limited by your imagination ;-) Regards, Bengt Richter From mde at micah.elliott.name Fri Nov 11 15:14:29 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Fri, 11 Nov 2005 12:14:29 -0800 Subject: Python Countdown In-Reply-To: <20051111192208.93680.qmail@web35912.mail.mud.yahoo.com> References: <20051111192208.93680.qmail@web35912.mail.mud.yahoo.com> Message-ID: <20051111201429.GC18475@kitchen.client.attbi.com> On Nov 11, john boy wrote: > I am running the following program from the example in "how to > think like a computer scientist" > ... > When I set "n"= 1000 the program runs in interpreter and stops > counting down at 14 instead of running all the way to "Blastoff". > Why is this program only counting to 986....Anybody have an > answer?? Did you notice the error: ... RuntimeError: maximum recursion depth exceeded You can't recurse forever! >>> import sys >>> sys.getrecursionlimit() 1000 You can set it a little higher (sys.setrecursionlimit) if you want to make this particular example work, but you'll see many disclaimers on doing this. -- _ _ ___ |V|icah |- lliott http://micah.elliott.name mde at micah.elliott.name " " """ From tuvas21 at gmail.com Fri Nov 11 13:54:31 2005 From: tuvas21 at gmail.com (Tuvas) Date: 11 Nov 2005 10:54:31 -0800 Subject: PIL- error message- cannot open libtiff.so.3 In-Reply-To: References: <1131732377.111363.249560@f14g2000cwb.googlegroups.com> Message-ID: <1131735271.881133.282270@g43g2000cwa.googlegroups.com> I got it from the PIL website, version 1.1.5. I guess it's possible that there's another library Image on the computer that it could be confusing? I'm looking for new things. Thanks! From gordonb.96bz4 at burditt.org Mon Nov 7 14:48:47 2005 From: gordonb.96bz4 at burditt.org (Gordon Burditt) Date: Mon, 07 Nov 2005 19:48:47 -0000 Subject: O_DIRECT on stdin? References: Message-ID: <11mvbsv4lbri8d@corp.supernews.com> >Is there a way of setting O_DIRECT on a preexisting file like sys.stdin? > >Does C allow this sort of thing? There is no O_DIRECT or fcntl() in Standard C. fcntl() operates on an open file descriptor, and the file descriptor for stdin is 0. Two calls to fcntl(), one with F_GETFL and one with F_SETFL, would do what you want. I'm not sure why you want to do that, though. It's not going to get you character-at-a-time I/O, if that's what you want. Gordon L. Burditt From nephish at xit.net Mon Nov 7 11:12:19 2005 From: nephish at xit.net (nephish at xit.net) Date: 7 Nov 2005 08:12:19 -0800 Subject: need help extracting data from a text file In-Reply-To: <1131378550.887946.127680@g43g2000cwa.googlegroups.com> References: <1131375863.977379.120620@f14g2000cwb.googlegroups.com> <1131378550.887946.127680@g43g2000cwa.googlegroups.com> Message-ID: <1131379939.695158.298640@g47g2000cwa.googlegroups.com> this is cool, it is only going to run about 10 times a day, the text is not written out like foo(bar) its more like foo blah blah blah (bar) the thing is , every few days the structure of the textfile may change, one of the reasons i wanted to avoid the re. thanks for the tip, From andrea_gavana at tin.it Wed Nov 2 18:20:42 2005 From: andrea_gavana at tin.it (Andrea Gavana) Date: Thu, 3 Nov 2005 00:20:42 +0100 Subject: wxPython: updating style of StaticText from event generated by button References: <1130886746.328723.109570@f14g2000cwb.googlegroups.com> Message-ID: <4367f8fb$0$24643$4fafbaef@reader3.news.tin.it> Hello Kees, > and via the even handler I try to give StaticText a different style: In general you *can not* change in runtime the style of a widget. Only a very limited subset of the wxPython widgets supports style changes in runtime. I would suggest you 2 alternatives: 1) Use wx.lib.stattext ==> GenStaticText (but I am not sure it will work, I don't think so, but you can try it); 2) Every time you call your event binder, Destroy() the StaticText with the old style and create a new one with the style you need. For example (untested code!!!): def VeranderLabel(self, event): if self.text1.GetWindowStyle() == wx.SUNKEN_BORDER: MyStyle = wx.RAISED_BORDER else: MyStyle = wx.SUNKEN_BORDER self.text1.Destroy() self.text1 = wx.StaticText(self.panel, -1, "Dikke Henk en gekke Greetje", size=(100,50), pos=(15,20), style=MyStyle) self.Refresh() HTH. Andrea. -- "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77 "KvS" ha scritto nel messaggio news:1130886746.328723.109570 at f14g2000cwb.googlegroups.com... > Hi all, > > I'm pretty new to (wx)Python so plz. don't shoot me if I've missed > something obvious ;). I have a panel inside a frame, on which a Button > and a StaticText is placed: > > self.panel = wx.Panel(self,-1) > self.button = wx.Button(self.panel,-1,"Klikkerdeklik") > self.button.SetPosition((200,40)) > self.Bind(wx.EVT_BUTTON, self.VeranderLabel, self.button) > self.text1 = wx.StaticText(self.panel, -1, "Dikke Henk en gekke > Greetje", size=(100,50), pos=(15,20), style=wx.RAISED_BORDER) > > and via the even handler I try to give StaticText a different style: > > def VeranderLabel(self, event): > if self.text1.GetWindowStyle() == wx.SUNKEN_BORDER: > self.text1.SetWindowStyle(wx.RAISED_BORDER) > self.text1.Refresh() > self.text1.Update() > else: > self.text1.SetWindowStyle(wx.SUNKEN_BORDER) > self.text1.Refresh() > self.text1.Update() > > Although the style is indeed updated (checked by printing style to > console) the appearance of the StaticText stays the same. What am I > missing here? > > Thanks in advance. > > - Kees > From steve at REMOVETHIScyber.com.au Sun Nov 27 05:19:12 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 27 Nov 2005 21:19:12 +1100 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <1h6lmts.1fr63yddwj4y4N%aleax@mail.comcast.net> <1h6mkzb.meaeo31vesla6N%aleax@mail.comcast.net> Message-ID: On Sat, 26 Nov 2005 09:54:24 -0800, Alex Martelli wrote: >> My understanding is that both Oracle and SAP make most of their money >> through consulting and customization rather than licencing or sales. I > > Have you checked their quarterly statements recently? Obviously not. Thanks for going beyond the call of duty to research the facts in such detail. I'm surprised that Adobe is selling so many licences -- I don't know anyone who has paid for Adobe software in many years -- and you can take that any way you like. (Kids! Pirating software is stealing!!!) I can't argue with anything you've written, except to say that we've obviously got different ideas of what consists of software sales. I know that there is a general sense of "sales" that effectively means "any source of income from services or goods". There is also a more restrictive (there's that word again...) sense of a sale being a transfer of ownership. In that stricter sense, nobody sells software -- they merely licence it. The sense of "software sales" I mean is intermediate between the two. The way I mean "sales", when Joe Public goes to acmesoft.com, pays $99 on his credit card number to download Acmesoft FooMaker, that's a sale. When he discovers that he also needs 37 Client Access Licences at $19 each, that's _not_ a software sale, and neither is the $150 per year for support and upgrades: that's revenue from licencing, not sales. You're usage of sales may differ, and I'm not going to argue that one is better than the other. By my meaning, Red Hat doesn't sell RH Enterprise Linux, but charges for support. By your meaning, Red Hat does sell RHEL. I'm good with that definition too, so long as we can agree on one or the other. -- Steven. From venkatasubramanian at gmail.com Fri Nov 11 03:52:36 2005 From: venkatasubramanian at gmail.com (venk) Date: 11 Nov 2005 00:52:36 -0800 Subject: Diff. between Class types and classic classes In-Reply-To: References: <1131454786.272355.314740@z14g2000cwz.googlegroups.com> <4370ba00$0$7529$626a14ce@news.free.fr> <437146a3$0$19243$626a54ce@news.free.fr> Message-ID: <1131699156.756947.220810@g47g2000cwa.googlegroups.com> Dear Colin, Forgive me for this late reply. Your explanation was of great help to me. Thank you very much. It was crystal clear. From bokr at oz.net Fri Nov 4 14:19:33 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 04 Nov 2005 19:19:33 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> Message-ID: <436ba176.120561988@news.oz.net> On 4 Nov 2005 08:23:05 GMT, Antoon Pardon wrote: >Op 2005-11-03, Magnus Lycka schreef : >> Antoon Pardon wrote: >>> There is no instance variable at that point. How can it add 2, to >>> something that doesn't exist at the moment. >> >> Because 'a += 1' is only a shorthand for 'a = a + 1' if a is an >> immutable object? Anyway, the behaviour is well documented. >> >> http://docs.python.org/ref/augassign.html says: >> >> An augmented assignment expression like x += 1 can be rewritten as x = x >> + 1 to achieve a similar, but not exactly equal effect. In the augmented >> version, x is only evaluated once. > >Then couldn't we expect that the namespace resolution is also done >only once? > >I say that if the introduction on += like operators implied that the >same mentioning of a name would in some circumstances be resolved to >two different namespaces, then such an introduction would better have >not occured. > >Would it be too much to ask that in a line like. > > x = x + 1. > >both x's would resolve to the same namespace? > I think I would rather seek consistency in terms of order of evaluation and action. IOW, the right hand side of an assignment is always evaluated before the left hand side, and operator precedence and syntax defines order of access to names in their expression context on either side. The compilation of function bodies violates the above, even allowing future (execution-wise) statements to influence the interpretation of prior statements. This simplifies defining the local variable set, and allows e.g. yield to change the whole function semantics, but the practicality/purity ratio makes me uncomfortable ;-) If there were bare-name properties, one could control the meaning of x = x + 1 and x += 1, though of course one would need some way to bind/unbind the property objects themselves to make them visible as x or whatever names. It might be interesting to have a means to push and pop objects onto/off-of a name-space-shadowing stack (__nsstack__), such that the first place to look up a bare name would be as an attribute of the top stack object, i.e., name = name + 1 if preceded by __nsstack__.append(my_namespace_object) would effectively mean my_namespace_object.name = my_namespace_object.name + 1 by way of logic like if __nsstack__: setattr(__nsstack__[-1], getattr(__nstack__[-1], name) + 1)) else: x = x + 1 Of course, my_namespace_object could be an instance of a class that defined whatever properties or descriptors you wanted. When you were done with that namespace, you'd just __nsstack__.pop() If __nsstack__ is empty, then of course bare names would be looked up as now. BTW, __nsstack__ is not a literal proposal, just a way to illustrate the concept ;-) OTOH, is suppose a function could have a reseved slot for a name space object stack that wouldn't cost much run time to bypass with a machine language check for NULL. BTW2, this kind of stack might play well with a future "with," to guarantee name space popping. Perhaps "with" syntax could even be extended to make typical usage slick ;-) Regards, Bengt Richter From david.rasmussen at gmx.net Sun Nov 13 14:12:28 2005 From: david.rasmussen at gmx.net (David Rasmussen) Date: Sun, 13 Nov 2005 20:12:28 +0100 Subject: Python Book Message-ID: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> What is the best book for Python newbies (seasoned programmer in other languages)? /David From http Tue Nov 22 16:09:59 2005 From: http (Paul Rubin) Date: 22 Nov 2005 13:09:59 -0800 Subject: matching a string to extract substrings for which some function returns true References: <861x184e7l.fsf@bhuda.mired.org> Message-ID: <7xiruktmmw.fsf@ruckus.brouhaha.com> Mike Meyer writes: > > put in a html page as the value of a hidden variable. And when i get > > the string again, i want to cast it back as list of tuples:... > This is a serious security risk, as you can't trust the data not to do > arbitrary things to your system when eval'ed. > I'd look into pickling the list of tuples to get the string. The whole scheme of putting the stuff on the html page and then getting it back from the client is ill-advised. Keep the info on the server and just have the client send back some token (session ID usually) saying where to find it on the server. If you absolutely have to put this sort of data on the client, append a cryptographic authentication code using the hmac module, and don't believe the data unless the authentication verifies. From steve at REMOVETHIScyber.com.au Sun Nov 13 10:41:53 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 14 Nov 2005 02:41:53 +1100 Subject: Proposal for adding symbols within Python References: <43762d68$0$4335$626a54ce@news.free.fr> <43770305$0$5294$636a15ce@news.free.fr> Message-ID: On Mon, 14 Nov 2005 00:48:46 +1100, Ben Finney wrote: > Steven D'Aprano wrote: >> On Sun, 13 Nov 2005 10:11:04 +0100, Pierre Barbier de Reuille wrote: >> > The problem, IMHO, is that way you need to declare "symbols" >> > beforehands, that's what I was trying to avoid by requiring a new >> > syntax. >> >> If you don't declare your symbols, how will you get the ones that >> you want? >> [...] >> Are you suggesting that the Python language designers should somehow >> predict every possible symbol that anyone in the world might ever >> need, and build them into the language as predefined things? > > I believe Pierre is looking for a syntax that will save him from > assigning values to names; that Python will simply assign arbitrary > unique values for these special names. My understanding of the > intended use is that their only purpose is to compare differently to > other objects of the same type, so the actual values don't matter. Unless I've misunderstood something, it would be easy to modify the recipe given here to do something like that: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 The example code does this: Days = Enum('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su') print Days.Mo, Days.Tu # etc. > What I still don't understand is why this justifies additional syntax > baggage in the language, rather than an explicit assignment earlier in > the code. The only advantage would be if you want to do something like this: MO, TU, WE, TH, FR, SA, SU = Symbols() and have it magically work. I can see the advantage of that, and you don't even need new syntax, just a magic function that somehow knows how many names are on the left hand side of the assignment. This is a poor substitute: MO, TU, WE, TH, FR, SA, SU = range(7) Firstly, if you change the number of symbol names, you have to manually adjust the argument to range. Secondly, your symbols are actually ints, and so will compare the same way ints compare. I don't know enough about the Python internals to tell: is there any feasible way for there to be a magic function like Symbol above that knew how many names were waiting for it to be supplied? If there is no way to do this from Python itself, it is possible to patch the compiler to do so? -- Steven. From apardon at forel.vub.ac.be Fri Nov 25 03:32:45 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Nov 2005 08:32:45 GMT Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132863273.378601.323870@f14g2000cwb.googlegroups.com> <86fyplwwri.fsf@bhuda.mired.org> Message-ID: Op 2005-11-24, Mike Meyer schreef : > rurpy at yahoo.com writes: >> "Mike Meyer" writes: >>> rurpy at yahoo.com writes: >>> > Different programming styles are appropriate for different >>> > tasks, different times and different places, different people. >>> > And like morality, government, or economics, I do not believe >>> > that one style of programming fits all situations. >>> If I read you right, what you're saying is that hammmers aren't good >>> at driving screws. I don't think anyone would argue about that. >> No, the analogy is more like this. Python is hammer that comes >> in green or blue. The hammer's developers say (perhaps with >> some reason) that cool colors like green and blue are the best >> colors because they promote calm when used. Calm hammerers >> are more productive and less violent. My work is >> repairing the inside of dark water tanks. It is hard to see blue >> and green hammers, and to find them if I put them down. >> I suggest that Python have the option of red hammers. > > So you're suggesting a fundamental change to the nature of > Python. It's inherently a blue/green language. Making it available in > Red violates the spirit and philosphy of the language, which is why: Well this is, is one thing I have a problem with. The python people seem to be more concerned with fighting things that could be used counter the python philosophy, than search for things that enable working in the python philosophy. Why did it take so long before a ternary operator was introduced? Because it was thought it could be too easily abused. The fact that there was also good use for a ternary operator within the spirit of Python was regarded as less important. >> The Python people respond with horror, pointing out the problems >> with red hammers. > > In other words, there are reasons that python doesn't come in red, and > they will gladly tell you what they are. > >> Regarding the differences between hammers and screwdrivers... >> When a screwdriver is appropriate I use a screwdriver. If I >> need to write code that does a large amount of CPU intensive >> number crunching, I use C, not Python. > > Yes. And if you need a red hammmer, you should get a red hammer, not > use red spray paint on one that wasn't designed to be red. Just > because *you* don't see how providing a red option violates the > philosophy of python doesn't mean that it doesn't do so. Well this seems to be the main conflict between those who would like Python to go a bit further and those that oppose it. Should the priority be to enable python's philosophy or should it be the priority to limit python to only allow it's philosophy. One groups seems to think that python's spirit is not broken by allowing things that seem counter to it, as long as people can without much trouble, work within that spirit. An other group seems to think that any allowance to disgress from python's spirit is an assault on it. -- Antoon Pardon From et1ssgmiller at gmail.com Fri Nov 18 12:09:24 2005 From: et1ssgmiller at gmail.com (Greg Miller) Date: 18 Nov 2005 09:09:24 -0800 Subject: sqlite utf8 encoding error In-Reply-To: <3b8rn1hkrf4jbt2f4v1mbl3c3ridon7b01@4ax.com> References: <1132228020.486726.26630@g47g2000cwa.googlegroups.com> <3b8rn1hkrf4jbt2f4v1mbl3c3ridon7b01@4ax.com> Message-ID: <1132333764.726662.198180@g43g2000cwa.googlegroups.com> Thank you for all your suggestions. I ended up casting the string to unicode prior to inserting into the database. Greg Miller From d at d.com Mon Nov 7 19:29:15 2005 From: d at d.com (python) Date: Mon, 7 Nov 2005 19:29:15 -0500 Subject: newbiew ?->creating multiuser database project 2 b used via internet Message-ID: hello and thanks for reading this. i am a long time windows/visual_basic user and i have been quite happy using that. i am doing a consulting project for a dry cleaning company. in the past i would use windows and visual basic but i want to create an app using python and linux using something link nomachine's nx server/client. i really did python. seems to me that i can create the app on my windows computer using things like: --- python --- postgre/mqsql --- thinker or something like it. then i could 'deploy'' it on linux. perhaps someone can provide some answers to the following questions to guide me. 1. is there any skeleton apps that supports: --- multi-user database --- forms --- some simple ui --- optmized for use over internet. i do not think i would want to use a browser based app is they seem to have a very primitve interface with too many page reloads. yeah, there is ajax but it is way to new for me. i checked out rekall but it looked to primitve and under development plus it did not seem to do graphing and had only read only kde and i will not be using kde. i have been checking out activatestate's komodo and i like that but i need some code to learn from. python is so different from visualbasic and i want to learn the right way thanks so much, dave From mfranklin1 at gatwick.westerngeco.slb.com Mon Nov 28 04:21:53 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 28 Nov 2005 09:21:53 +0000 Subject: How to make tkFileDialog GUI larger? In-Reply-To: <438A7785.9060205@atomfx.com> References: <438A7785.9060205@atomfx.com> Message-ID: John Wheez wrote: > Hi all, > > I'm using teh tkFileDialog to let teh user select a directory. We have > long names which make > it difficult to view the directories. > > For some reason the GUI windows doesn;t expand on Windows like it does > on OS X or Linux. > Is there a method to make the widths of the tkFileDialog windows larger > when using Windows XP? > > Thanks for any info. > > .JW this is due to Tk using a native Windows file dialog and I guess this is the default behavior on Windows... There may be a special Windows only hack but I'm sorry I don't know what it would be Martin From aleax at mail.comcast.net Sat Nov 12 12:46:05 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 12 Nov 2005 09:46:05 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131639786.958533.45070@z14g2000cwz.googlegroups.com> <1h5tx6n.ayer08s58osaN%aleax@mail.comcast.net> Message-ID: <1h5wov9.tij0dxhyvdn3N%aleax@mail.comcast.net> Yu-Xi Lim wrote: > Alex Martelli wrote: > > There is no effective manner of protecting your code, except running it > > only on well-secured machines you control yourself. If you distribute > > your code, in ANY form, and it's at all interesting to people with no > > interest in respecting the law, then, it WILL be cracked (and if users > > choose to respect the law, then you need no "protecting"). > > Indeed. An this extends to web services too. If you have input which can > be observed (or even better, controlled) and output that can be observed > too, one would be able to infer the workings of the code (reverse > engineering in one of its purest forms). ...unless you have "nonobservable state", of course, in which case the inference is conceptually impossible. For example, say that you have developed a new and revolutionary system to predict weather, much better than anything the competition has. You offer it as a for-pay web service, the customer-supplied inputs being the space-time coordinates at which prediction is required, while the customer-provided outputs are a vector of possible weather conditions each with an attached probability, just as they might be for ANY weather-prediction web service, except that (by hypothesis, or else you won't make much money on this;-) the outputs of your weather predictor match reality much better than the competitors'. "To infer" whatever would essentially mean to reinvent your whole "revolutionary system" from scratch. Much the same would apply if what your system is able to predict better than your competitors' is any other kind of phenomenon of economic interest in a sufficiently complex real-world system -- from interest rates to the probability that two would-be online daters will like each other. And it doesn't have to be prediction -- one famous system where ESR, as a consultant, advised his clients to keep their program a trade secret, was "just" a better heuristic than any of their competitors' for cutting a set of given shapes with automated tools out of a slab of wood, if I recall correctly... a problem that's computationally intractable to solve anything but heuristically, and a better heuristic saves wood, worktime, and/or wear and tear on the tools, therefore is worth money. In practice, you ARE going to be able to operate your system successfully bases on keeping a good innovative algorithm or heuristic secret, for a while -- until somebody else independently reinvents it (or, invents something even better, in which case your secret may become irrelevant). IP protection is a possibility, but copyright per se might be too weak, and whether patents apply in any given case is always controversial (Europe soundly defeated a proposed software patent directive, after a bitter fight, less than a year ago). > If your business strategy relies heavily on a proprietary algorithm or > even something as weak as lock-in via a proprietary "un-interoperable" > data format, then web services is not the final answer. It may work for > certain applications (Microsoft's for example) where the cost of reverse > engineering is equivalent to the cost of building from scratch. ...and the latter is going to be the case for many important "proprietary algorithms", as above exemplified. A cryptographically sound "proprietary data format" may be essentially impossible to break, too -- although, differently from many potential algorithms, it has per se no added value, and may run afoul of sensible legislation (or sensible would-be customers), such as Massachussets', mandating the use of standard data formats. Alex From mclister at zeesource.net Mon Nov 7 17:42:36 2005 From: mclister at zeesource.net (Claire McLister) Date: Mon, 7 Nov 2005 14:42:36 -0800 Subject: [OT] Map of email origins to Python list In-Reply-To: References: <425926b9683e56644bf034dfb9ed65d7@zeesource.net> Message-ID: <6569ef15851fd1fa4ff2d543e6fbf5fd@zeesource.net> On Nov 7, 2005, at 10:55 AM, Steve Holden wrote: > Mostly I wonder what the point is. For example, given my own somewhat > nomadic life I wondered what location has been used to map my own > contributions. Just for fun, really. We try to a best job of mapping the IP location closest to the origins of your email. Again, we are not saying that this is your location. All we are saying is that that particular email seems to have originated from that location. > Nonetheless I'm sure that before long these maps will be used to prove > some spurious facts about newsgroup readership to gullible members of > the business community. Well, we really don't know what the maps tell us. If they say something interesting, then it doesn't hurt to tell more people about it. > If I've got you wrong then please forgive my slight hostility, but I am > particularly suspicious of the "click to change" functionality. You are > clearly expecting people to update their locations, and other > information that might be related to their domains, and I can't help > wondering what purposes that information is intended for. Sorry, I should have made it clear why we are doing this. We have a service that allows people to mark their group of people or places on a Google Map. So, the 'click to change' is for those maps, and really not meant to be used for these email list maps. It's just that as we were building those maps we saw some people offering services of IP to locations, and thought wouldn't it be interesting to find out where emails are coming from to various Open Source projects. > Finally, considering email address from domains like "verizon.net", > "aol.com" and other large ISPs I can't see that you have a chance in > hell of extracting useful demographics. Which all leads me back to > "what's the point?" - just because you can? See my previous response. Sometimes we still can get better origins than just where the bulk server is. Yes, really, it was just an exercise to see what comes out of it. From fumanchu at amor.org Thu Nov 3 18:03:29 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 3 Nov 2005 15:03:29 -0800 Subject: Python Framework that works with IIS/SQL Server? Message-ID: randall_burns at hotmail.com wrote: > I'd like to find a web framework that works with IIS and SQL Server on > Windows(I know-but I didn't make that decision). Anyhow, I've > looked at Turbogears, Django, subway and didn't see any evidence > that anyone had made these work in that configuration. > Any suggestions? Since TurboGears and Subway are built on top of CherryPy, they should be able to use the ASP/IIS WSGI gateway here: http://www.aminus.org/blogs/index.php/fumanchu/2005/05/26/wsgi_gateway_f or_asp_microsoft_iis ...and it seems there is some support for MS SQL Server in SQLObject, which both frameworks also use: http://sqlobject.org/SQLObject.html#ms-sql-server I use bare CherryPy with my own ORM, which handles SQL Server quite well: http://projects.amor.org/dejavu Robert Brewer System Architect Amor Ministries fumanchu at amor.org From graham.abbott at gmail.com Thu Nov 3 04:43:32 2005 From: graham.abbott at gmail.com (Graham) Date: 3 Nov 2005 01:43:32 -0800 Subject: Class Variable Access and Assignment Message-ID: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> This has to do with class variables and instances variables. Given the following: class _class: var = 0 #rest of the class instance_b = _class() _class.var=5 print instance_b.var # -> 5 print _class.var # -> 5 Initially this seems to make sense, note the difference between to last two lines, one is refering to the class variable 'var' via the class while the other refers to it via an instance. However if one attempts the following: instance_b.var = 1000 # -> _class.var = 5 _class.var = 9999 # -> _class.var = 9999 An obvious error occurs. When attempting to assign the class variable via the instance it instead creates a new entry in that instance's __dict__ and gives it the value. While this is allowed because of pythons ability to dynamically add attributes to a instance however it seems incorrect to have different behavior for different operations. There are two possible fixes, either by prohibiting instance variables with the same name as class variables, which would allow any reference to an instance of the class assign/read the value of the variable. Or to only allow class variables to be accessed via the class name itself. Many thanks to elpargo and coke. elpargo assisted in fleshing out the best way to present this. perhaps this was intended, i was just wondering if anyone else had noticed it, and if so what form would you consider to be 'proper' either referring to class variables via the class itself or via instances of that class. Any response would be greatly appreciated. Graham From lsumnler at uniqueinsuranceco.com Sun Nov 6 11:33:27 2005 From: lsumnler at uniqueinsuranceco.com (LenS) Date: 6 Nov 2005 08:33:27 -0800 Subject: ? MDI depreciated Message-ID: <1131294807.907281.58980@g47g2000cwa.googlegroups.com> Hate to ask this dum question (since I've been hiding under a rock). But if the MDI UI model is/was depreciated. What is the new UI model. Would love some links that explain in gerneral and specific terms. Len Sumnler From paul at boddie.org.uk Fri Nov 18 09:13:50 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 18 Nov 2005 06:13:50 -0800 Subject: Ajax for the Developers References: <1132304902.782786.154210@f14g2000cwb.googlegroups.com> Message-ID: <1132323230.673392.313740@z14g2000cwz.googlegroups.com> SABIN wrote: > The trendy XML HTTP Request has really struck the way developers had adopted > with the user interfaces. But the major issuse are yet to be solved.. > > 1. Changing state with links (GET requests) > 2.Asynchronously performing batch operations > 3.Breaking the back button > > Will these get solved. It depends. Issue 3 presumably describes the way the back button doesn't "undo" your last interaction but instead often takes you off the page and back to what you were viewing before. Whether the back button was "broken" before, for things like form-based applications, is also an open issue. I think you need to explain issue 2 in more detail for me (at least) to understand what you're suggesting. As for issue 1, where your objection presumably lies in the need to handle whole page updates in an application as well as what I call "in-page updates" (thus ignoring the Web 2.0 blogging community's tendency to overhype straightforward concepts using catchy but obscure and inaccurate acronyms), strategies certainly do exist to combine the two approaches without necessarily ruining standard Web accessibility. There does appear to be a certain Web 2.0 "scene" which seems hell bent on reinventing "old school client/server" over HTTP; I intend to pay as little attention to such endeavours as my RSS feed reader will allow. Paul From beachbumdon2005 at yahoo.com Wed Nov 16 12:33:36 2005 From: beachbumdon2005 at yahoo.com (Don) Date: 16 Nov 2005 09:33:36 -0800 Subject: Newbie question: string replace In-Reply-To: <3s7620FlqdmnU1@uni-berlin.de> References: <1130258229.662596.228630@g49g2000cwa.googlegroups.com> <3s7620FlqdmnU1@uni-berlin.de> Message-ID: <1132162416.551337.128230@g47g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > usgog at yahoo.com wrote: > > I have a config file with the following contents: > > service A = { > > params { > > dir = "c:\test", > > username = "test", > > password = "test" > > } > > } > > > > I want to find username and replace the value with another value. I > > don't know what the username value in advance though. How to do it in > > python? > > Could be done using regular expressions. Ususally for such tasks one > would prefer pythons string manipulation functions, but if you want to > preserve whitespace, I think a rex is in order here: > > > import re, sys > > > new_name = "foobar" > > rex = re.compile(r'(^.*username *=[^"]*")([^"]*)(".*$)') > for line in sys.stdin: > m = rex.match(line) > if m is not None: > line = "%s%s%s\n" % (m.group(1), new_name, m.group(3)) > sys.stdout.write(line) > > > > use with > > python script.py < config_in > config_out > > Regards, > > Diez From martin at v.loewis.de Tue Nov 22 20:35:57 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Nov 2005 02:35:57 +0100 Subject: Using gettext to provide different language-version of a script In-Reply-To: <1132661256.664435.311520@g14g2000cwa.googlegroups.com> References: <1132661256.664435.311520@g14g2000cwa.googlegroups.com> Message-ID: <4383c77c$0$28830$9b622d9e@news.freenet.de> Thomas W wrote: > Hmmm ... any hints? I think gettext needs environment variables (e.g. LANG) to be set. Regards, Martin From case.nelson at gmail.com Wed Nov 23 12:25:21 2005 From: case.nelson at gmail.com (snoe) Date: 23 Nov 2005 09:25:21 -0800 Subject: strange behaviour when writing a large amount of data on stdout In-Reply-To: References: Message-ID: <1132766721.315132.100990@z14g2000cwz.googlegroups.com> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 No problems on Windows 2000 Pro with 512MB of RAM From aahz at pythoncraft.com Tue Nov 29 20:11:41 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Nov 2005 17:11:41 -0800 Subject: python speed References: Message-ID: In article , Krystian wrote: > >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. Why would we want Python to be as fast as Java when it's already faster? Take a look at PyGame. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Don't listen to schmucks on USENET when making legal decisions. Hire yourself a competent schmuck." --USENET schmuck (aka Robert Kern) From fredrik at pythonware.com Thu Nov 10 18:05:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Nov 2005 00:05:44 +0100 Subject: derived / base class name conflicts References: <1131663184.885322.326530@g44g2000cwa.googlegroups.com> Message-ID: christopherlmarshall at yahoo.com wrote: > Now, 'i' might have already been defined by A or by the call to > A.__init__() so if you define it without knowing that, you could be > changing the behavior of A's methods in unknown ways, which is > obviously a bad thing. http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 From calad.sigilon at gmail.com Tue Nov 1 13:02:36 2005 From: calad.sigilon at gmail.com (calad.sigilon at gmail.com) Date: 1 Nov 2005 10:02:36 -0800 Subject: python.org offline In-Reply-To: References: Message-ID: <1130868156.412172.254110@g43g2000cwa.googlegroups.com> Works fine for me, and I check it pretty frequently. Perhaps it's a problem with your ISP's communication with the Python.org ISP? Sybren Stuvel wrote: > Hi all, > > In the past weeks, I often got this message from the python.org > webserver: > > ------------------------------------------------------------------ > Service Temporarily Unavailable > > The server is temporarily unable to service your request due to > maintenance downtime or capacity problems. Please try again later. > ------------------------------------------------------------------ > > Does anyone know what's going on? > > 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 samrobertsmith at gmail.com Tue Nov 22 06:56:44 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Tue, 22 Nov 2005 03:56:44 -0800 Subject: sort in the list Message-ID: <1d987df30511220356r95126bbvcc09328df4f681e@mail.gmail.com> I use Python 2.3 to run the following code: >>> a=[[1,2],[4,8],[0,3]] >>> a.sort() >>> a [[0, 3], [1, 2], [4, 8]] >>> I wonder whether the sort function automatically consider the first element in the list of list as the sorting criteria or it just happens to be? Thanks! From lycka at carmen.se Thu Nov 24 12:54:01 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 24 Nov 2005 18:54:01 +0100 Subject: about sort and dictionary In-Reply-To: <1h6iwje.127g54a1ltpvmfN%aleax@mail.comcast.net> References: <1132493880.591426.224140@g49g2000cwa.googlegroups.com> <1132651818.348370.117450@g49g2000cwa.googlegroups.com> <1132653873.855348.265740@g47g2000cwa.googlegroups.com> <1132700747.794586.73170@g44g2000cwa.googlegroups.com> <1h6g1t6.qxc6tnag2skbN%aleax@mail.comcast.net> <1132719140.781847.251410@z14g2000cwz.googlegroups.com> <1h6gyxh.1bqns7v1lw2frwN%aleax@mail.comcast.net> <1h6iwje.127g54a1ltpvmfN%aleax@mail.comcast.net> Message-ID: Alex Martelli wrote: > I don't think these headaches and difficulties justify dumping the whole > field of reasoning about programs, nor the subfield of PbC. The concept > of "immutable" is really just a tiny corner of these fields, and it's a > long way from being the hardest or most problematic one in them;-). Agreed. I also think that it's good practice to make methods do *one* thing, so when methods grow into both changing state and returning some substantial value, I usually split them. While the distinction between "functions" and "procedures" to speak Pascalese is a useful guidline at times, it's still a generalization though, and I doubt that it's very useful to have a syntactic marker for this distinction such as e.g. Pascal has. As I understand it, Ruby's "!" isn't quite like "procedure" in Pascal, or "not const" in C/C++, but rather a marker for surprising behaviour, and while it might be wise to acknowledge that not all APIs are perfect, it seems difficult to know where mutating behaviour will surprise users. It seems to me that different programmers have different expectations on such things, and stumble over completely different things... From mwm at mired.org Wed Nov 23 00:02:44 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 00:02:44 -0500 Subject: What a curious assignment. References: <1132721032.455988.259600@o13g2000cwo.googlegroups.com> Message-ID: <86fypoyn0r.fsf@bhuda.mired.org> "Neil.Jin at gmail.com" writes: > [test 1] >>>> class A: > ... i = 1 > ... >>>> a = A() >>>> A.i > 1 >>>> a.i > 1 >>>> A.i = 2 >>>> A.i > 2 >>>> a.i > 2 >>>> > > [test2] >>>> class A: > ... i = 1 > ... >>>> a = A() >>>> A.i > 1 >>>> a.i > 1 >>>> a.i = 2 >>>> A.i > 1 >>>> a.i > 2 >>>> > > Is there somthing wrong???? No. Reading a.i looks up i by checking the instance (a), then the class (A), so a.i and A.i are the same thing. So changing A.i changes the value seen by a.i. Binding a.i binds i to a, not A, so after the binding, a.i and A.i are different things. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From roy at panix.com Wed Nov 9 08:52:30 2005 From: roy at panix.com (Roy Smith) Date: Wed, 09 Nov 2005 08:52:30 -0500 Subject: append to non-existing list References: Message-ID: In article , Yves Glodt wrote: > > You mean you want to type "pkcolumns" only once to keep your code short? > > Would something like this be useful? > > > > pkcolumns = [row.strip() for row in sqlsth] > > I will look into this, maybe it's what I need, thanks! The list comprehension format described above is handy and compact, and there's no reason you shouldn't use it when appropriate. That being said, compactness should not itself be a goal. Writing clear and easy to understand code is much more important than reducing the number of lines. Sometimes you get both at the same time, but not always. From martin at v.loewis.de Sat Nov 26 18:59:09 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 27 Nov 2005 00:59:09 +0100 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <863bljf1o8.fsf@bhuda.mired.org> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> <1132899059.919842.74190@f14g2000cwb.googlegroups.com> <86r795tbph.fsf@bhuda.mired.org> <86oe48inj4.fsf@bhuda.mired.org> <86u0e0h03w.fsf@bhuda.mired.org> <86lkzcgvpq.fsf@bhuda.mired.org> <86br07fv0a.fsf@bhuda.mired.org> <43885b80$0$18644$9b622d9e@news.freenet.de> <863bljf1o8.fsf@bhuda.mired.org> Message-ID: <4388f6ce$0$22897$9b622d9e@news.freenet.de> Mike Meyer wrote: >>This is not true. The second definition of __hash__ does not meet >>the specifications: > > > The specification isn't on the __hash__ method, but on objects. What does it mean for a specification to be "on" something? The specification I quoted is listed "under" the __hash__ heading of the reference manual. > Instances of mylist2 that aren't otherwise tweaked won't meet the > specification. Right, that's what I meant. > That's pretty flaky. The same docs say: > > Should return a 32-bit integer usable as a hash value for dictionary > operations. What is flaky about this? > the dictionary implementation requires that a key's hash value is > immutable Indeed, the question here is: what does "an object is immutable" mean in this context? You appear to read it as "an object whose state does not change", however, what it really means is "an object which will always use the same state in __hash__ and __eq__". > Maybe those are only "recommended" properties, but any class that > doesn't meet them is going to have instances with interesting > behaviors in sets and as dictionary keys. Indeed, you can anything return you want in __hash__, or always raise an exception. What precisely the result of dictionary operations is when you do so is undefined in Python. > That's a problem with mylist2 instances, and may or may not be a > problem in the mylist2 __hash__ method. You can't tell just by > examining the __hash__ method whether or not it meets this > specification. Correct. I would expect that this is the case for any specification of __hash__ you can come up with: __hash__ would typically refer to the state of the object, and whether or not the results meets some specified requirement would also depend on what the state is. (unless either the specification is trivial (e.g. "may or may not return a value") or the implementation is trivial (e.g. "return 0")) Regards, Martin From tuvas21 at gmail.com Fri Nov 4 13:05:10 2005 From: tuvas21 at gmail.com (Tuvas) Date: 4 Nov 2005 10:05:10 -0800 Subject: Tkinter- checkbutton In-Reply-To: <11mn7qgsj29cra2@corp.supernews.com> References: <1131123953.135003.86390@g14g2000cwa.googlegroups.com> <1131124290.860885.105430@g14g2000cwa.googlegroups.com> <11mn7qgsj29cra2@corp.supernews.com> Message-ID: <1131127510.504807.101210@g43g2000cwa.googlegroups.com> That solved the problem. Thanks! From andychambers2002 at yahoo.co.uk Wed Nov 2 16:23:52 2005 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 2 Nov 2005 13:23:52 -0800 Subject: Retain reference to a struct Message-ID: <1130966632.805388.150520@g14g2000cwa.googlegroups.com> Hi All, A C library I'm using has a number of functions that all require a struct as an argument. The example module shows how to make a new Python Object from C code and I've seen other posts that recommend this way of doing it. In this case though, it would seem easier if I could create the object in the Python code. This would require storing a pointer to an instance of the struct until a certain function is called. I can get the pointer into the python code, but whenever I try to use it to call another function, the module segfaults. Can anyone suggest why this is? static PyObject * libpyq_PQconnectdb(PyObject *self, PyObject *args) { PGconn *conn = PyMem_New(PGconn, sizeof(PGconn *)); conn = (PGconn *)PQconnectdb((const char*) PyString_AS_STRING(args)); printf("%p", conn); return PyLong_FromVoidPtr(conn) ; } static PyObject * libpyq_PQfinish(PyObject *self, PyObject *args) { printf("%p", args); return 1; } >>> import libpyq #works fine >>> conn = libpyq.PQconnectdb #conn now a pointer >>> libpyq.PQfinish(conn) #segfaults I'm new to C but relatively experienced with Python. I have a sneaky suspiscion there's a good reason for not doing it this way but I haven't seen a good explanation of why not yet. If you know one, please tell me. Thanks, Andy From sybrenUSE at YOURthirdtower.com.imagination Tue Nov 1 16:48:23 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 1 Nov 2005 22:48:23 +0100 Subject: python.org offline References: <1130862100.694549.276860@f14g2000cwb.googlegroups.com> Message-ID: A.M. Kuchling enlightened us with: > I suspect this is teething problems related to the move to a new > server. I've bumped up the number of Apache processes, so we'll see > if that alleviates the problem. Thanks! I hope it helps! 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 jgardner at jonathangardner.net Sun Nov 27 04:05:48 2005 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 27 Nov 2005 01:05:48 -0800 Subject: How can I do this in Python? In-Reply-To: <1131178398.195075.111300@z14g2000cwz.googlegroups.com> Message-ID: <1133082347.997285.173880@f14g2000cwb.googlegroups.com> I don't know what engine you are using. Basically all you have to do is render the login form at the url of the page that needs the login. You're going to have to hook in the authentication code before you render the page normally. For instance, this is a common way I've been doing it in various engines I use: (1) Check to see if the user is logging in by looking at the parameters. If they login successfully, record that in the session and continue as normal. (2) Normal operation being... check to see if they are logged in according to their session. (The code in (1) will set up their session to be logged in if they just logged in.) If they aren't and they need to be, show the login page. Otherwise, show the regular content. From bonono at gmail.com Thu Nov 10 10:41:51 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 07:41:51 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <1h5subp.1dh6491u1957aN%aleax@mail.comcast.net> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131595096.310029.98740@g43g2000cwa.googlegroups.com> <1131596283.073069.165700@g43g2000cwa.googlegroups.com> <1131620733.240589.296510@g14g2000cwa.googlegroups.com> <1131621952.208466.323880@z14g2000cwz.googlegroups.com> <1h5subp.1dh6491u1957aN%aleax@mail.comcast.net> Message-ID: <1131637311.919062.260500@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > This is the first time on this thread in which I'm glimpsing that you > mean 'when' not as in SQL (where it has just the same meaning as the > 'if' in Python's genexps/listcomps), but rather with the meaning that > any Pythonista would instinctively spell 'while'. Since AFAIK 'when' is > only used in SQL (out of widespread languages), using it with a > drastically different meaning would be an utter disaster, IMHO. The original post was in the context about dropwhile/takewhile. I may choose the wrong word "when". BTW, what does "when" do it SQL ? I only know about "where" which I believe is the closest equvialent of "if" in python generator comprehension/list expression. To me when/while has a "sequence" element there whereas "where/if" don't. I didn't choose "while" because I know it is a key word already in python so I never thought about it being in this kind of construct, but thinking about it, "if" can be used in list expression then may be while can be used to. > > Right now, listcomps and genexps can be explained very simply as > equivalent to just the same nesting of for and if statement as they have > clauses in sequence. Adding a 'while' clause (or 'until', etc) would > unfortunately break this simple rule, and therefore make the whole > construct harder, not easier, to understand. Unless there are very > compelling and frequent use cases for such an addition, I doubt it's > worth even trying to make a patch in order to time it against > itertools.takewhile... I have no idea what it is involved or what about rules. I just raised a simple question because the whole dropping filter/map/reduce discussion I read gave me the impression that python is siding over in-line list/generator expression rather than the more traditional map/reduce/takewhile function call style. From everettcc at hotmail.com Wed Nov 9 21:41:46 2005 From: everettcc at hotmail.com (Chad Everett) Date: Wed, 9 Nov 2005 20:41:46 -0600 Subject: Newb ?? References: Message-ID: Hey guys, Thanks for your help. I am glad to know there is a community out there willing to put the effort out to help us newbies. I will work on it. Some of the suggestions are things that I have not covered yet but I am sure I will figure it out. Thanks again. I am sure I will be back with more questions before too long. Chad "Chad Everett" wrote in message news:mzdcf.470$rN2.320 at bignews2.bellsouth.net... > Hi all, I am new to the group. Trying to learn Python programming on my > own. I am working through Michael Dawson's Book Python Programming for > the absolute beginner. > > I am tring to write a program that is a number guessing game. I want to > be able to give the user 5 tries to guess the number before the program > ends. > > I get the result that I want when the user misses after the 5th try. But > it does not go down to my closing statement to end. Rather is askes for > another guess. > > I appreciate any help you can give. If this is not the correct group for > these types of questions, I apologize and hope that you can direct me to > another NG. > > Thanks, > Chad > > import random > > print "\tWelcome to 'Guess my Number'!" > print "\nI'm Thinking of a Number between 1 and 100." > print "\nTry to Guess it in as few attempts as possible.\n" > > #Set the initial values > the_number = random.randrange(100) + 1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #Guessing Loop > > while (guess != the_number): > if (guess >the_number): > print "Lower..." > else: > print "Higher..." > guess = int(raw_input("Take another Guess:")) > tries +=1 > if tries == 5: > print "Sorry you lose." > print "The Correct Number was ", the_number > > > print "You guess correctly!!" > print "The number was:", the_number > print "You got it correct in", tries, "tries" > > raw_input("Press Enter to exit the program") > From claudio.grondi at freenet.de Wed Nov 16 06:06:28 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 16 Nov 2005 11:06:28 -0000 Subject: newbie - How do I import automatically? References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> Message-ID: <3u0el9Fum367U1@individual.net> Just edit the first lines of %SystemDrive%\Python24\Lib\idlelib\PyShell.py yourself (not tested, but I have customized Idle intitial message using it and it worked ok - after new Python installation I overwrite this file with my own version to keep this customization.) Hope this helps. Claudio schrieb im Newsbeitrag news:1132092221.672995.103230 at z14g2000cwz.googlegroups.com... > I also checked in command prompt, and there it works!, but not in IDLE. > And it's in IDLE that I work all the time. Can anything be done to get > it to work there? > > Bob > From mwm at mired.org Wed Nov 23 23:09:35 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 23:09:35 -0500 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1132800973.008501.34090@g14g2000cwa.googlegroups.com> Message-ID: <867jay1ybk.fsf@bhuda.mired.org> "bonono at gmail.com" writes: >> You're the one that wants to use the hammer to do whatever it is, not >> me. I don't believe in silver bullets. Python is good at what it >> does. If I need a different tool, I use a different tool, rather than >> try and mangle a good tool into something it's not. Such attempts are >> pretty much doomed. They nearly inevitably produce a tool that's not >> as good at what the original did as the original, and not as good at >> whatever new task it's being mangled to do as a tool that was >> designed for that in the first place. > And again. This isn't a Python thing, it's a believe about tools in general - that you should choose the right tool for the job. It isn't applied very often to hardware tools because they aren't as mallable as software tools, and have in general been around and improving for a long time. But it applies to programming languages, data formats, and similar more mallable things. Changes that make them better at what they do are welcome; changes that make the into what they aren't are viewed with great suspicion. Maybe Python attracts people who share that belief. After all, TRTFTJ is implies TSBOOWTDI, and vice versa. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From luismgz at gmail.com Sat Nov 19 17:09:12 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 19 Nov 2005 14:09:12 -0800 Subject: HTML generation vs PSP vs Templating Engines In-Reply-To: <1132435860.231522.29450@g14g2000cwa.googlegroups.com> References: <1132158690.299954.90920@g14g2000cwa.googlegroups.com> <1132225003.654019.309170@z14g2000cwz.googlegroups.com> <1132435860.231522.29450@g14g2000cwa.googlegroups.com> Message-ID: <1132438152.561187.172210@g43g2000cwa.googlegroups.com> I meant that it is not strictly necessary to use templates in Karrigell, although you can use Cheetah if you want. I'm not used to templates mainly because I'm familiar with the way PHP works and, for simple dynamic sites like those I work on, this is the simpliest approach. Another reason is that I'm a little bit lazy for learning yet another language, be it a python-like one or a template one. Also, I feel that Python is easy enough for having to resort to another language. I usually create my pages with Dreamweaver or any other visual tool, and once the design is ready, I add a few python lines to it which, combined with modules that are separated from the html code, work wonders on my sites. From fredrik at pythonware.com Sun Nov 6 14:59:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 6 Nov 2005 20:59:08 +0100 Subject: Validate string as UTF-8? References: <*firstname*nlsnews-835F79.13585206112005@news.verizon.net> Message-ID: Tony Nelson wrote: > I'd like to have a fast way to validate large amounts of string data as > being UTF-8. define "validate". > I don't see a fast way to do it in Python, though: > > unicode(s,'utf-8').encode('utf-8) if "validate" means "make sure the byte stream doesn't use invalid sequences", a plain unicode(s, "utf-8") should be sufficient. From http Thu Nov 24 17:33:19 2005 From: http (Paul Rubin) Date: 24 Nov 2005 14:33:19 -0800 Subject: Why is dictionary.keys() a list and not a set? References: <8664qi3oef.fsf@bhuda.mired.org> <1h6iyik.86v3t3z8icd7N%aleax@mail.comcast.net> <1h6j466.1pwsjsevabcuxN%aleax@mail.comcast.net> <1h6jbmp.vo1aoh1fw1u1mN%aleax@mail.comcast.net> Message-ID: <7xmzjtbrrk.fsf@ruckus.brouhaha.com> aleax at mail.comcast.net (Alex Martelli) writes: > Peano's axioms are perfectly abstract, as far as I recall. Russell and > Whitehead did try to construct naturals from sets (defining, e.g., '5' > as "the set of all sets with five items"), but that was before the > inherent contradictions of set theory were widely known (though Russell > himself had destroyed Frege's attempts at theorization by pointing out > one such contradiction, the one wrt the "set of all sets that don't > include themselves as a member" if I recall correctly). That's only what's called "naive set theory". Axiomatic set theory (the kind they use now) doesn't have these issues. http://en.wikipedia.org/wiki/Naive_set_theory http://en.wikipedia.org/wiki/Axiomatic_set_theory > Later, Goedel showed that any purely formal theory that's powerful > enough to model natural arithmetic cannot be both complete and > consistent... Yes, it's not considered terribly troublesome. Set theory (and arithmetic) are generally accepted as being consistent but incomplete. So there will always be something for mathemeticians to do ;-). From onurb at xiludom.gro Wed Nov 16 14:38:09 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 16 Nov 2005 20:38:09 +0100 Subject: Creating (rather) generic plugin framework? In-Reply-To: <84Ief.9127$fR3.929@reader1.news.jippii.net> References: <84Ief.9127$fR3.929@reader1.news.jippii.net> Message-ID: <437b8aa3$0$16668$626a54ce@news.free.fr> Edvard Majakari wrote: > Hi, > > My idea is to create a system working as follows: each module knows > path to plugin directory, and that directory contains modules which > may add hooks to some points in the code. > > Inspired by http://www.python.org/pycon/2005/papers/7/pyconHooking.html > > I would create a class like this: > > class Printer: > > def printit(self, msg): > stuff = self.beforePrintHook(msg) > if stuff: > msg = stuff > print msg > self.afterPrintHook(msg) > > def beforePrintHook(self, msg): pass > def afterPrintHook(self, msg): pass > > Now, in the spirit of py.test, I'd like API to be practically no API at all :) > moreover, deploying a plugin must consist simply of adding appropriate file to > plugins directory, nothing more, and removing it would uninstall it. The > plugin should be able to somehow result in all future invocations to > Printer.printit() call hooks specified in the plugin. Now, the plugin module > for class above /might/ be along the following lines (I'm thinking of stuff > here, so I don't know yet what would be the most appropriate way): > > ### a very simple plugin which uppercases all data fed to it. > > extensions = {'Printer': 'PrinterHook'} > > class PrinterHook: > > def beforePrintHook(self, msg): > return msg.upper() > def afterPrintHook(self, msg): > print "Called afterPrintHook with msg %s" % msg > > > Now, I have a very rude (I think) implementation which has two methods, first > the one that loads plugin modules: > (snip code) > > But hey, this has many downsides. First off, mechanism doesn't support > arbitrary namespaces. Here, class identifier in the plugin must be as it is > seen from the module which calls the plugin (not a problem for me, but could > be more elegant; probably a mapping between logical class identifiers and > actual class names, hmm?). Second, if one wants to use many hooks (with > priority for conflicts), it is not possible now; set_hooks always overrides > potentially existing hooks. And probably many other problems that are not > obvious to me, but for the simple purpose I have in mind, it seems to work. Just a couple of ideas: - using decorators for plugin hooks ? ie: import hooks class Whatever(anything): @hooks.hook(for='Printer.beforePrintHook',priority=42) def my_function_with_a_long_name(self, *args, **kw): pass The decorator would take care of "registering" the hook where relevant, ie, storing it in a class attribute of the hooked class ? which leads to: - in the hooked class, use a dict class attribute for hooks: from hooks import run_hooks class Printer # will be filled (and could even be created) # by the @hook decorator _hooks = {} def print(self, msg): # run_hooks will take care of selecting appropriate # hooks (by looking up the class attribute _hooks) # and running'em in order msg = run_hooks(self, 'Printer.beforePrintHook', msg) print msg run_hooks(self, 'Printer.afterPrintHook', msg) My 2 cents... I don't even know if this can be implemented (but I don't see why it couldn't). > This is the first plugin system in Python I'm writing, so I can be a way off > the correct path.. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From y.glodt at sitasoftware.lu Wed Nov 9 07:46:52 2005 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 09 Nov 2005 13:46:52 +0100 Subject: append to non-existing list Message-ID: <4371EFBC.1030502@sitasoftware.lu> Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row[0].strip()) ________etc without a prior: pkcolumns = []; I get this error on first iteration: UnboundLocalError: local variable 'pkcolums' referenced before assignment I guess that's normal as it's the way python works...?!? My question is: Is there no way to append to a non existing list? I am lazy for declaring it first, IMHO it bloats the code, and (don't know if it's good to say that here) where I come from (php) I was used to not-needing it... regards, Yves From aum at spam.me.please Sun Nov 6 23:00:58 2005 From: aum at spam.me.please (aum) Date: Mon, 07 Nov 2005 17:00:58 +1300 Subject: how to present Python's OO feature in design? References: <1131332809.044523.169900@o13g2000cwo.googlegroups.com> Message-ID: On Sun, 06 Nov 2005 19:06:49 -0800, pcmanlin wrote: > As I know java has many UML tools to design for its OO feature, is > there any tools or good concept for Python project Modeling? Just code the bloody thing! One of Python's strengths is its rapid design/programming/testing turnaround. And virtually none of Java's mind-gnashing red tape. -- Cheers David From bignose+hates-spam at benfinney.id.au Sun Nov 20 06:33:21 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Nov 2005 22:33:21 +1100 (EST) Subject: about dictionary References: Message-ID: Shi Mu wrote: > I have have the following code: > >>> a=[3,5,8,0] > >>> b={} > >>> > How I can i assign each item in a as the key in the dictionary b > simultaneously? > that is, > b={3:[],5:[],8:[],0:[]} Explicit: a = [3, 5, 8, 0] b = {} for key in a: b[key] = [] Quicker: a = [3, 5, 8, 0] b = dict( [(k, []) for k in a] ) What behaviour do you expect when there are repeated values in the list 'a'? -- \ "Faith may be defined briefly as an illogical belief in the | `\ occurrence of the improbable." -- Henry L. Mencken | _o__) | Ben Finney From mwm at mired.org Fri Nov 18 14:01:08 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 18 Nov 2005 14:01:08 -0500 Subject: Importing a class without knowing the module References: <867jb6n7cw.fsf@bhuda.mired.org> <86veyqlnrn.fsf@bhuda.mired.org> <1h66rw8.wlp7nb19e5629N%aleax@mail.comcast.net> <86k6f6lgvy.fsf@bhuda.mired.org> <1h66w9j.1d82do2qfe2b1N%aleax@mail.comcast.net> <86zmo2jvsw.fsf@bhuda.mired.org> <1h67qx0.1y62ktrcq00pbN%aleax@mail.comcast.net> Message-ID: <86psoxkcgb.fsf@bhuda.mired.org> aleax at mail.comcast.net (Alex Martelli) writes: > Mike Meyer wrote: > ... >> A classes __module__ attribute doesn't always tell you the name of the >> module - or at least, not a name that would be usefull for the the OPs >> use case. That's the case where you don't have the module name. The > How do you arrange a module so that its classes' __module__ attributes > don't tell you the name of the module "that would be useful", yet the > module's __file__ DOES give you information that you can usefully > process, heuristically I assume, to infer a module name that IS useful? So what module name do you import if C.__module__ is __main__? > I just don't see it, which of course doesn't mean it can't be done, with > sufficient evil ingenuity. But since you're the one arguing that this > case is important enough to be worth dwelling on, I'm not dwelling on it, you are. All I did was recommend using the module name if you had one, and if not then the file name was your best bet. You chose to ignore part of my statement to focus on the part you disagreed with, because you thought what I had suggested in the first place was a better idea. I pointed out this oversight on your part, and you've been dwelling on it ever since. Frankly, I thought you were brighter than that, have no idea why you're acting like this, and frankly don't think you need a tutor. I figured this out by fooling around with the interpreter before posting in the first place, you certainly know enough to do the same. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mkonrad at syr.edu Fri Nov 11 16:58:30 2005 From: mkonrad at syr.edu (Michael Konrad) Date: 11 Nov 2005 21:58:30 GMT Subject: directory listing References: Message-ID: <0F5A253A-B10C-419A-AA38-0B259B421FF0%mkonrad@syr.edu> "Fredrik Lundh" wrote: > "SU News Server" wrote: > >> I've struggled with this for quite a while and I'm am just not sure >> what is going on. I have the following code >> import os >> >> def buildList( directory='/Users/mkonrad' ) >> >> dirs = [ ] >> >> listing = os.listdir(directory) >> >> for x in listing: >> if os.path.isdir(x): >> dirs.append(x) >> >> return dirs >> >> This always returns an empty list. >> Now if I change it so that directory='.' or directory=os.getcwd() >> Then it returns a list of directories. > > hint: if you're not sure what's going on in your program, adding > a print statement or two is an easy way to figure it out. like, say: > > for x in listing: > print x > if os.path.isdir(x): > dirs.append(x) > Did that and I was just getting a bunch of [ ]. > (try this before you continue) > > : > : > : > > the problem is that os.listdir returns a list of filenames, without > the preceeding directory name. you can add an os.path.join > > for x in listing: > x = os.path.join(directory, x) > if os.path.isdir(x): > dirs.append(x) OK. This works except each entry in dirs now includes the full path. Is there an unjoin? :) I haven't spent any time trying to work this out. > > or use the glob module instead: > > listing = glob.glob(os.path.join(directory, "*")) > > hope this helps! > > > > > > From fredrik at pythonware.com Wed Nov 9 11:14:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 17:14:10 +0100 Subject: PIL-> Tkinter References: <1131551783.628602.3320@g14g2000cwa.googlegroups.com> Message-ID: "Tuvas" wrote > Is there a way to put an image loaded from PIL into a TKinter GUI? > Without converting the image to a .bmp, and using a canvas? If that's > the only way it'll work, I'll take it, but... It would be nice > otherwise... hmm. is google down today? here's a random cookbook sample: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/227575 also see: http://effbot.org/imagingbook/imagetk.htm http://effbot.org/tkinterbook/photoimage.htm (if the image doesn't appear when it should, see the note at the bottom of the photoimage page) From kevin.bell at slcgov.com Wed Nov 2 10:48:13 2005 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Wed, 2 Nov 2005 08:48:13 -0700 Subject: where to download md5.py? Message-ID: <2387F0EED10A4545A840B231BBAAC722607F98@slcimail1.slcgov.com> I've been looking around, but haven't found a place to download the md5.py module. I need it to run the dupinator.py Anyone know where to find it? Kev From jhefferon at smcvt.edu Tue Nov 15 08:14:49 2005 From: jhefferon at smcvt.edu (Jim) Date: 15 Nov 2005 05:14:49 -0800 Subject: generate HTML In-Reply-To: <1132051974.733119.184010@f14g2000cwb.googlegroups.com> References: <1131962200.216285.307760@g44g2000cwa.googlegroups.com> <4378dc0c$1@nntp0.pdx.net> <1132051974.733119.184010@f14g2000cwb.googlegroups.com> Message-ID: <1132060489.784662.150420@g49g2000cwa.googlegroups.com> Perhaps you are trying to do this: 'text to go here: %s' % ('text',) ? For that you need a double-quoted string: "text to go here: %s" % ('text',) (or triple-doubles: """ .. """ as you noted). Jim From alanmk at hotmail.com Mon Nov 7 08:49:35 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 07 Nov 2005 13:49:35 +0000 Subject: Threading-> Stopping In-Reply-To: <1131117582.259001.224930@g44g2000cwa.googlegroups.com> References: <1131117582.259001.224930@g44g2000cwa.googlegroups.com> Message-ID: [Tuvas] > Is there a way to stop a thread with some command like t.stop()? Or any > other neat way to get around it? Thanks! Good question. And one that gets asked so often, I ask myself why it isn't in the FAQ? http://www.python.org/doc/faq/library.html It really should be in the FAQ. Isn't that what FAQs are for? Maybe the FAQ needs to be turned into a wiki? -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From michele.simionato at gmail.com Fri Nov 4 10:33:23 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 4 Nov 2005 07:33:23 -0800 Subject: Web automation with twill In-Reply-To: <1131117665.999523.176780@g43g2000cwa.googlegroups.com> References: <1130934838.388039.297650@o13g2000cwo.googlegroups.com> <1130945598.627911.264390@g49g2000cwa.googlegroups.com> <1130966536.697459.250700@g49g2000cwa.googlegroups.com> <1131092795.953963.297990@g14g2000cwa.googlegroups.com> <1131117665.999523.176780@g43g2000cwa.googlegroups.com> Message-ID: <1131118403.944127.255730@f14g2000cwb.googlegroups.com> qwwwee: > By the way, are you aware that C. Titus Brown (twill's author) > tells "peste e corna" of Zope? No, but I am not surprised. I also say "peste e corna" of Zope ;) In general I am an anti-frameworks guy (in good company with many Pythonistas including Guido). Michele Simionato From onurb at xiludom.gro Thu Nov 3 11:23:44 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 03 Nov 2005 17:23:44 +0100 Subject: when and how do you use Self? In-Reply-To: References: <4369d4f0$0$18073$626a14ce@news.free.fr> Message-ID: <436a3991$0$15260$636a15ce@news.free.fr> Chris Cioffi wrote: as a point of style, top-posting is a Bad Thing(tm) (fixed) > > On 03/11/05, bruno at modulix wrote: > >>Tieche Bruce A MSgt USMTM/AFD wrote: >> >>>I am new to python, >>> >>>Could someone explain (in English) how and when to use self? >>> >> >>Don't use self. Use other. > As a point of style: the 'other' identifier should only be used in > Zen Metaclass programming as an implicit reference to the calling > object or as a list of references to all other instances of the class. As a point of style, if it refers to a list, it should be 'others' and not 'other'. Also, this was supposed to be a joke. I can well understand that my sens of humour is somewhat disastrous and that this was not a _good_ joke, but "context should have made both clear and obvious" that it was one. > Context will make it both clear and obvious which use case is > desired. import this -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From MrJean1 at gmail.com Tue Nov 15 01:45:26 2005 From: MrJean1 at gmail.com (MrJean1) Date: 14 Nov 2005 22:45:26 -0800 Subject: best way to discover this process's current memory usage, cross-platform? In-Reply-To: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> Message-ID: <1132037126.467573.184300@o13g2000cwo.googlegroups.com> My suggestion would also be to use sbrk() as it provides a high-water mark for the memory usage of the process. Below is the function hiwm() I used on Linux (RedHat). MacOS X and Unix versions are straigthforward. Not sure about Windows. /Jean Brouwers #if _LINUX #include size_t hiwm (void) { /* info.arena - number of bytes allocated * info.hblkhd - size of the mmap'ed space * info.uordblks - number of bytes used (?) */ struct mallinfo info = mallinfo(); size_t s = (size_t) info.arena + (size_t) info.hblkhd; return (s); } #elif _MAXOSX || _UNIX #include size_t hiwm (void) { size_t s = (size_t) sbrk(0); return (s); } #elif _WINDOWS size_t hiwm (void) { size_t s = (size_t) 0; /* ??? */ return (s); } #endif From tdelaney at avaya.com Thu Nov 10 16:53:01 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 11 Nov 2005 08:53:01 +1100 Subject: [ x for x in xrange(10) when p(x) ] Message-ID: <2773CAC687FD5F4689F526998C7E4E5F4DB7BE@au3010avexu1.global.avaya.com> Colin J. Williams wrote: > Are there generally accepted guidelines on what is appropriate for the > builtin namespace? Yes. If Guido can be convinced it should be in builtins, it should be. Tim Delaney From invalidemail at aerojockey.com Sat Nov 5 01:33:05 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 Nov 2005 22:33:05 -0800 Subject: import statement / ElementTree In-Reply-To: <1131158927.097582.91530@g14g2000cwa.googlegroups.com> References: <1131158927.097582.91530@g14g2000cwa.googlegroups.com> Message-ID: <1131172385.009653.112090@g47g2000cwa.googlegroups.com> mirandacascade at yahoo.com wrote: > O/S: Windows 2K > Vsn of Python: 2.4 > > Currently: > > 1) Folder structure: > > \workarea\ <- ElementTree files reside here > \xml\ > \dom\ > \parsers\ > \sax\ First point, XML DOM comes packaged with Python 2.4. (IIRC, Python XML is, or was, a seperate project that made it into the Python distribution--maybe it still makes its own releases. I presume you're using one of those release in lieu of the version supplied with Python. I only point this out in case you didn't realize the xml package is in Python 2.4. My apologies if this comes across as presumptuous of me.) > 2) The folder \workarea\ is in the path. > > 3) A script (which is working) makes calls to the Element(), > SubElement(), tostring() and XML() methods within ElementTree.py; the > script is organized as follows: > > # top of file; not within any function/mehtod > import ElementTree > > > > root = ElementTree.Element('request') > pscifinq = ElementTree.SubElement(root, 'pscifinq') > bank = ElementTree.SubElement(pscifinq, 'bank') > bank.text = '1' > inquiryString = ElementTree.tostring(root) In the most recent version, ElementTree modules are part of the elementtree package. Are you using an older version? If so, perhaps you should get the latest version. > 4) the term 'ElementTree files' referenced above refers to the > following files: > __init__.py (this file contains only comments) > ElementInclude.py > ElementPath.py > ElementTree.py > HTMLTreeBuilder.py > SgmlopXMLTreeBuilder.py > SimpleXMLTreeBuilder.py > SimpleXMLWriter.py > TidyHTMLTreeBuilder.py > TidyTools.py > XMLTreeBuilder.py It looks like your version of ElementTree is a packaged version. The file __init__.py normally appears only in packages; it's a mistake for these files to have been in the workarea directory in the first place. How did you install ElementTree? > Want to change things as follows: > > Folder structure: > > \workarea\ <- ElementTree files no longer here > \xml\ > \dom\ > \elementtree\ <- ElementTree files reside here > \parsers\ > \sax\ Bad idea, I'd say. Generally, you shouldn't inject your own modules into someone else's package system (unless you're working on someone else's packages, to modify or enhance them). The xml package might have been a slight exception to this, seeing how it's just a container for several related packages, but it's in the Python distribution. ElementTree modules are part of the elementtree package. You should arrange your directories like this (and they should have been arranged like this in the first place): \workarea \elementtree \xml \dom \sax ...etc... > I tried changing the > > import ElementTree > > statement to: > > import xml.elementtree.ElementTree > > The result of changing the folder structure and the import statement > was the following error: > > import xml.elementtree.ElementTree > > ImportError: No module named elementtree.ElementTree I'm guessing this exception is not happening with your import statement, but with some other import in one of the ElementTree modules (though in that case I'm not sure why it would have been working before). I'd have to see the traceback to be sure. Generally, when reporting an error, you should include a traceback. > I verified that the file ElementTree.py really does reside in the > \workarea\xml\elementtree\ folder. Assuming that I really want the > ElementTree files to reside in the \workarea\xml\elementtree\ folder, > what changes must I make such that the script can locate the > ElementTree.py file? I have a hunch that there is something obvious > that I am missing in the import statement; is it possible to accomplish > this by changing only the import statement rather than changing each of > the calls to the Element(), SubElement(), XML() and tostring() methods. Well, if you arrange it as I advise, you shouldn't have a problem. However, if you want to change only the import statements, you don't want to do this: import elementtree.ElementTree That will import ElementTree but the you'd have to access it as elementtree.ElementTree. Instead you should do this: from elementtree import ElementTree Carl Banks From bignose+hates-spam at benfinney.id.au Wed Nov 16 16:32:30 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Nov 2005 08:32:30 +1100 (EST) Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <1132154202.424220.54450@g44g2000cwa.googlegroups.com> <1132176350.089366.55090@o13g2000cwo.googlegroups.com> Message-ID: The Eternal Squire wrote: > The teaching of legality and ethics of incorporating other peoples' > works into one's own should begin at 6th grade and be repeated every > year until the message is driven home. I disagree strongly. The legality of copying, modifying and redistributing works should be reformed until it matches a 6th grader's intuitions about sharing. -- \ "I bought some powdered water, but I don't know what to add." | `\ -- Steven Wright | _o__) | Ben Finney From godoy at ieee.org Thu Nov 3 05:37:46 2005 From: godoy at ieee.org (Jorge Godoy) Date: 03 Nov 2005 08:37:46 -0200 Subject: Class Variable Access and Assignment References: <1131011020.845873.282180@g14g2000cwa.googlegroups.com> Message-ID: <87pspiuidh.fsf@jupiter.g2ctech> "Graham" writes: > perhaps this was intended, i was just wondering if anyone else had > noticed it, and if so what form would you consider to be 'proper' > either referring to class variables via the class itself or via > instances of that class. Any response would be greatly appreciated. It was discussed before here and there's something about that at the docs: http://docs.python.org/tut/node11.html -- Jorge Godoy From bokr at oz.net Sat Nov 5 16:26:22 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 05 Nov 2005 21:26:22 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> <436c0527.146082265@news.oz.net> <864q6rkfie.fsf@bhuda.mired.org> Message-ID: <436d0b61.213212052@news.oz.net> On Fri, 04 Nov 2005 21:14:17 -0500, Mike Meyer wrote: >bokr at oz.net (Bengt Richter) writes: >> On Thu, 03 Nov 2005 13:37:08 -0500, Mike Meyer wrote: >> [...] >>>> I think it even less sane, if the same occurce of b.a refers to two >>>> different objects, like in b.a += 2 >>> >>>That's a wart in +=, nothing less. The fix to that is to remove += >>>from the language, but it's a bit late for that. >>> >> Hm, "the" fix? Why wouldn't e.g. treating augassign as shorthand for a source transformation >> (i.e., asstgt = expr becomes by simple text substitution asstgt = asstgt expr) >> be as good a fix? Then we could discuss what >> >> b.a = b.a + 2 >> >> should mean ;-) > >The problem with += is how it behaves, not how you treat it. But you >can't treat it as a simple text substitution, because that would imply >that asstgt gets evaluated twice, which doesn't happen. I meant that it would _make_ that happen, and no one would wonder ;-) BTW, if b.a is evaluated once each for __get__ and __set__, does that not count as getting evaluated twice? >>> class shared(object): ... def __init__(self, v=0): self.v=v ... def __get__(self, *any): print '__get__'; return self.v ... def __set__(self, _, v): print '__set__'; self.v = v ... >>> class B(object): ... a = shared(1) ... >>> b=B() >>> b.a __get__ 1 >>> b.a += 2 __get__ __set__ >>> B.a __get__ 3 Same number of get/sets: >>> b.a = b.a + 10 __get__ __set__ >>> b.a __get__ 13 I posted the disassembly in another part of the thread, but I'll repeat: >>> def foo(): ... a.b += 2 ... a.b = a.b + 2 ... >>> import dis >>> dis.dis(foo) 2 0 LOAD_GLOBAL 0 (a) 3 DUP_TOP 4 LOAD_ATTR 1 (b) 7 LOAD_CONST 1 (2) 10 INPLACE_ADD 11 ROT_TWO 12 STORE_ATTR 1 (b) 3 15 LOAD_GLOBAL 0 (a) 18 LOAD_ATTR 1 (b) 21 LOAD_CONST 1 (2) 24 BINARY_ADD 25 LOAD_GLOBAL 0 (a) 28 STORE_ATTR 1 (b) 31 LOAD_CONST 0 (None) 34 RETURN_VALUE It looks like the thing that's done only once for += is the LOAD_GLOBAL (a) but DUP_TOP provides the two copies of the reference which are used either way with LOAD_ATTR followed by STORE_ATTR, which UIAM lead to the loading of the (descriptor above) attribute twice -- once each for the __GET__ and __SET__ calls respectively logged either way above. > >> OTOH, we could discuss how you can confuse yourself with the results of b.a += 2 >> after defining a class variable "a" as an instance of a class defining __iadd__ ;-) > >You may confuse yourself that way, I don't have any problems with it >per se. I should have said "one can confuse oneself," sorry ;-) Anyway, I wondered about the semantics of defining __iadd__, since it seems to work just like __add__ except for allowing you to know what source got you there. So whatever you return (unless you otherwise intercept instance attribute binding) will get bound to the instance, even though you internally mutated the target and return None by default (which gives me the idea of returning NotImplemented, but (see below) even that gets bound :-( BTW, semantically does/should not __iadd__ really implement a _statement_ and therefore have no business returning any expression value to bind anywhere? >>> class DoIadd(object): ... def __init__(self, v=0, **kw): ... self.v = v ... self.kw = kw ... def __iadd__(self, other): ... print '__iadd__(%r, %r) => '%(self, other), ... self.v += other ... retv = self.kw.get('retv', self.v) ... print repr(retv) ... return retv ... >>> class B(object): ... a = DoIadd(1) ... >>> b=B() >>> b.a <__main__.DoIadd object at 0x02EF374C> >>> b.a.v 1 The normal(?) mutating way: >>> b.a += 2 __iadd__(<__main__.DoIadd object at 0x02EF374C>, 2) => 3 >>> vars(b) {'a': 3} >>> B.a <__main__.DoIadd object at 0x02EF374C> >>> B.a.v 3 Now fake attempt to mutate self without returning anything (=> None) >>> B.a = DoIadd(1, retv=None) # naive default >>> b.a 3 Oops, remove instance attr >>> del b.a >>> b.a <__main__.DoIadd object at 0x02EF3D6C> >>> b.a.v 1 Ok, now try it >>> b.a +=2 __iadd__(<__main__.DoIadd object at 0x02EF3D6C>, 2) => None >>> vars(b) {'a': None} Returned value None still got bound to instance >>> B.a.v 3 Mutation did happen as planned Now let's try NotImplemented as a return >>> B.a = DoIadd(1, retv=NotImplemented) # mutate but probably do __add__ too >>> del b.a >>> b.a <__main__.DoIadd object at 0x02EF374C> >>> b.a.v 1 >>> b.a +=2 __iadd__(<__main__.DoIadd object at 0x02EF374C>, 2) => NotImplemented __iadd__(<__main__.DoIadd object at 0x02EF374C>, 2) => NotImplemented >>> vars(b) {'a': NotImplemented} >>> B.a.v 5 No problem with that? ;-) I'd say it looks like someone got tired of implementing __iadd__ since it's too easy to work around the problem. If _returning_ NotImplemented could have the meaning that return value processing (binding) should not be effected, then mutation could happen without a second evaluation of b.a as a target. ISTM a return value for __iadd__ is kind of strange in any case, since it's a statement implementation, not an expression term implementation. > >> Or point out that you can define descriptors (or use property to make it easy) >> to control what happens, pretty much in as much detail as you can describe requirements ;-) > >I've already pointed that out. Sorry, missed it. Big thread ;-) Regards, Bengt Richter From p at ulmcnett.com Tue Nov 29 14:33:05 2005 From: p at ulmcnett.com (Paul McNett) Date: Tue, 29 Nov 2005 11:33:05 -0800 Subject: wxGrid and Focus Event In-Reply-To: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> References: <1133291436.812397.86930@o13g2000cwo.googlegroups.com> Message-ID: <438CACF1.1020909@ulmcnett.com> lux wrote: > How can I capture the EVT_SET_FOCUS on a wxGrid? If you want to catch when the grid as a whole gets the focus, use: >>> grid.Bind(wx.grid.EVT_SET_FOCUS, self.onGridFocus) If you want to catch when a cell in the grid gets the focus, use: >>> grid.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.onCellSelected) And, your questions will be better on the wxpython-users list at http://wxpython.org/maillist.php -- Paul McNett http://paulmcnett.com http://dabodev.com From luismgz at gmail.com Wed Nov 23 10:13:04 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 23 Nov 2005 07:13:04 -0800 Subject: the PHP ternary operator equivalent on Python In-Reply-To: References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com> <1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132376750.855932.45470@g47g2000cwa.googlegroups.com> Message-ID: <1132758784.301797.268040@z14g2000cwz.googlegroups.com> This could be done easier this way: L = [('odd','even')[n%2] for i in range(8)] From crw at chello.se Mon Nov 28 09:24:09 2005 From: crw at chello.se (Me) Date: Mon, 28 Nov 2005 15:24:09 +0100 Subject: Multiple versions Message-ID: <2qEif.1530$zc1.1481@amstwist00> I need to install both 2.3 and 2.4 on my Win2000 system. Can someone please give me a pointer as to how to do this? Thanks! From sw at wordtech-software.com Mon Nov 14 12:06:25 2005 From: sw at wordtech-software.com (Kevin Walzer) Date: Mon, 14 Nov 2005 12:06:25 -0500 Subject: Not enough arguments for format string Message-ID: I'm getting an error in a Python script I'm writing: "not enough arguments for format string." The error comes at the end of the os.system command, referenced below. Any ideas? --- import EasyDialogs import os import sys password = EasyDialogs.AskPassword("To launch Ethereal, please enter your password:") binpath = os.path.join(os.path.dirname(sys.argv[0]), '/opt/local/bin/ethereal') os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export DISPLAY; echo %s | sudo -S %s; sudo -k' %password %binpath) TypeError: not enough arguments for format string -- Cheers, Kevin Walzer, PhD WordTech Software - "Tame the Terminal" http://www.wordtech-software.com sw at wordtech-software.com From onurb at xiludom.gro Fri Nov 11 10:29:58 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 11 Nov 2005 16:29:58 +0100 Subject: Import statements for timeit module In-Reply-To: <1131715618.580594.68630@z14g2000cwz.googlegroups.com> References: <1131715618.580594.68630@z14g2000cwz.googlegroups.com> Message-ID: <4374b8f8$0$31636$626a14ce@news.free.fr> ChaosKCW wrote: > Hi > > I was wondering if someone could help with the import statements needed > to use the timeit module in the following code. I need to access the > "cur" object. > > Thanks, > > import cx_Oracle > import timeit > > def VerifyTagIntegrity(con, TableOwner): > cur = con.cursor() > sql = 'select (select count(*) from %s.f4111) as F4111_COUNT, > (select count(*) from %s.f4111_tag) as TAG_COUNT from dual;' % > (TableOwner, TableOwner) > print " SQL: %s" % (sql) > timer = timeit.Timer('cur.execute(sql)', 'from __main__ import > cur') > print timer.timeit() > 'cur' is local to the function, so it's not an attribute of your module, so you can't hope to import it anyway. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From cito at online.de Fri Nov 25 03:34:50 2005 From: cito at online.de (Christoph Zwerschke) Date: Fri, 25 Nov 2005 09:34:50 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132884955.735518.213780@g47g2000cwa.googlegroups.com> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383b600.500692667@news.oz.net> <4384DD77.9080303@online.de> <1132884955.735518.213780@g47g2000cwa.googlegroups.com> Message-ID: Le ruego me perdone. replace('haber', random.choice('tener', 'hacer', 'lograr')) Mi espanol es peor que mi python. -- Christoph From skip at pobox.com Tue Nov 29 12:12:41 2005 From: skip at pobox.com (skip at pobox.com) Date: Tue, 29 Nov 2005 11:12:41 -0600 Subject: Death to tuples! In-Reply-To: <1h6r4mi.1dc149q1kxqm03N%aleax@mail.comcast.net> References: <86y839ux1j.fsf@bhuda.mired.org> <8664qcv6i5.fsf@bhuda.mired.org> <7x64qcii9o.fsf@ruckus.brouhaha.com> <1h6r4mi.1dc149q1kxqm03N%aleax@mail.comcast.net> Message-ID: <17292.35849.819150.573732@montanaro.dyndns.org> >> Actually, no, I hadn't. I don't use tuples that way. It's rare when >> I have a tuple whose elements are not all floats, strings or ints, >> and I never put mutable containers in them. Alex> You never have a dict whose values are lists? Sorry, incomplete explanation. I never create tuples which contain mutable containers, so I never have the "can't use 'em as dict keys" and related problems. My approach to use of tuples pretty much matches Guido's intent I think: small, immutable, record-like things. immutable-all-the-way-down-ly, y'rs, Skip From aleax at mail.comcast.net Wed Nov 23 23:44:08 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 20:44:08 -0800 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> Message-ID: <1h6hyr3.p01crx1jz34d5N%aleax@mail.comcast.net> Ben Finney wrote: ... > > Remember that your redefined __setattr__ IS "in place" even when > > you're initializing your istance, so remember to delegate attribute > > setting to the superclass (the other special methods mentioned above > > are less likely to byte you). > > So, for a class that needs to set attributes in __init__ (but after > that, become immutable), how do I get around this? Should I make a As I said, you delegate attribute setting to the superclass. E.g: >>> class Immut(object): ... def __setattr__(*a): raise TypeError, 'immutable' ... def __init__(self, v=23): ... super(Immut,self).__setattr__('v', v) ... >>> x=Immut() >>> x.v 23 >>> x.v=42 Traceback (most recent call last): File "", line 1, in ? File "", line 2, in __setattr__ TypeError: immutable >>> Alex From sjmsoft at hotmail.com Mon Nov 14 10:20:46 2005 From: sjmsoft at hotmail.com (sjmsoft at hotmail.com) Date: 14 Nov 2005 07:20:46 -0800 Subject: Python Book References: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> Message-ID: <1131981646.389036.130170@z14g2000cwz.googlegroups.com> David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? > > /David A couple of years ago I was in the same boat you're in now. I learned from _Python in a Nutshell_ by Alex Martelli and still use it as my main reference. (It only covers up to version 2.2 so a new edition would be most welcome.) I also use the on-line Python docs and I second Larry Bates' comments re. the cookbook and the Windows book, both of which I also use occasionally. -- Steve From lycka at carmen.se Fri Nov 4 04:03:07 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 04 Nov 2005 10:03:07 +0100 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: >>Because b.a += 2 expands to b.a = b.a + 2. Why would you want b.a = >> to correspond to b.__class__.a = ? > > > That is an implemantation detail. The only answer that you are given > means nothing more than: because it is implemented that way. Something that is written in the language reference is not an implementation detail. Every implementation that aims to be Python must follow this. It's a design decision. Whether you like it or not, you will find out that the behaviour of Python is largely based on an idea of an underlying structure. A lot of the syntax is basically just convenient ways to access this structure, and there is a strong tradition to avoid magic. The explicit use of self might be the most obvious example of that, but you can find a lot of other things in Python that shows you this, __dict__ for instance. I agree that the behaviour you are questioning isn't completely unsurprising for someone who stumbles over it the first time, but considering how things work in Python classes, where the class scope is searched if a name isn't found in the instance scope (self.__dict__), any other solution would involve more magic, and be more surprising to someone who actually knows what is going on. It's possible that a oldie like me, who started coding Python in 1996 is just blind to the warts in Python by now, but no language is perfect, and whatever design decisions you make, they will have both positive and negative consequences. I frankly don't understand what you are after Antoon. Just to vent your frustrations? If you want to use Python in an effective way, try to learn how to use the language that actually exists. Asking questions in this forum is clearly a part of that, but your confrontational style, and idea that everything that bothers you is a language bug that needs to be fixed is not the most constructive approach. I'm pretty sure that it doesn't really solve your coding problems, instead it leads the discussion away from the practical solutions. If you really want to improve the Python language, your approach is completely off target. First of all, this isn't really the right forum for that, and secondly, improvements to Python requires a lot of cooperation and substantial contributions of work, not just complaints, even if you might have a point now and then. From bokr at oz.net Tue Nov 29 09:54:44 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 29 Nov 2005 14:54:44 GMT Subject: General question about Python design goals References: <438ba299.175154008@news.oz.net> <86acfo3srq.fsf@bhuda.mired.org> Message-ID: <438c6b30.226504866@news.oz.net> On Tue, 29 Nov 2005 00:52:25 -0500, Mike Meyer wrote: >bokr at oz.net (Bengt Richter) writes: >>>Then feel free to submit patches for the docs. >> This is easy to say, and maybe the docs maintainers are accomodating, >> but I'd be the average reader wouldn't have a concept of how a "patch" >> should be prepared. > >From what's been said here before, the doc committers aren't picky >about getting patches. That requires learning whatever doc format they >use, and they understand that that's a pretty hefty burden for a one >or two-paragraph tweak on the documentation. So submitting docs in >English works. Submitting patches works *better*, but not doing so >doesn't consign your suggestions to oblivion. > Ok, sounds reasonable. BTW, no opinion on iter as a type harboring sequence-applicable methods? ;-) Regards, Bengt Richter From mwm at mired.org Sat Nov 12 12:51:30 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 12 Nov 2005 12:51:30 -0500 Subject: newbie how do I interpret this? References: <1131815443.308190.198850@g14g2000cwa.googlegroups.com> Message-ID: <861x1l3gbh.fsf@bhuda.mired.org> bobueland at yahoo.com writes: > Here's a small session > >>>> import re >>>> p=re.compile('[a-z]+') >>>> m=p.match('abb1a') >>>> dir(m) > ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', > 'groups', 'span', 'start'] >>>> help(m.groups) > Help on built-in function groups: > > groups(...) > >>>> > > My question is. How do I interpret the hiven help info > groups(...) > > alt1. Tough luck. There's no help. People are to busy to write > reference manuals. > alt 2. There are no parameters. The only possibility is m.groups() > alt3. Something else alt 3, specifically: No doc string, time to check the reference manual. says: groups( [default]) Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. (Incompatibility note: in the original Python 1.5 release, if the tuple was one element long, a string would be returned instead. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.) Since you don't have any groups in your re, groups is always going to return (). You probably want group(). http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From could.net at gmail.com Fri Nov 11 02:49:36 2005 From: could.net at gmail.com (could ildg) Date: Fri, 11 Nov 2005 15:49:36 +0800 Subject: Which blog do you use? Message-ID: <311b5ce10511102349t1edae6c9l635aeae9126d20b3@mail.gmail.com> I want to to get a free blog sapce these days, which has category for my posts. What blog do you use? I'll apprecaite your recommendation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.arentz at gmail.com Fri Nov 4 05:02:28 2005 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 04 Nov 2005 11:02:28 +0100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> Message-ID: <8764r8u3wr.fsf@keizer.soze.com> Antoon Pardon writes: ... > Would it be too much to ask that in a line like. > > x = x + 1. > > both x's would resolve to the same namespace? This is starting to look more like a nagging contest than a real discussion imo. Consider changing the semantics of what you are proposing and think about all those Python projects that will break because they depend on the above behaviour and even take advantage of it. So in short: yes, it would be too much to ask :-) But, you can fix it in your own code. Simply make sure that your class variables have different names or a prefix. S. From duncan.booth at invalid.invalid Mon Nov 28 03:44:04 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Nov 2005 08:44:04 GMT Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: Steven D'Aprano wrote: > Since real source code verifiers make no such sweeping claims to > perfection (or at least if they do they are wrong to do so), there is > no such proof that they are impossible. By using more and more > elaborate checking algorithms, your verifier gets better at correctly > verifying source code -- but there is no guarantee that it will be > able to correctly verify every imaginable program. > I'm sure you can make a stronger statement than your last one. Doesn't Godel's incompleteness theorem apply? I would have thought that no matter how elaborate the checking it is guaranteed there exist programs which are correct but your verifier cannot prove that they are. From warpcat at sbcglobal.net Tue Nov 1 13:57:29 2005 From: warpcat at sbcglobal.net (warpcat) Date: 1 Nov 2005 10:57:29 -0800 Subject: Python and DevTrack? Message-ID: <1130871448.959281.105160@f14g2000cwb.googlegroups.com> I'm a python nubie, so be gental. I've been setting up functionality by managing my Perforce clientspec with python (since it seems all of P4's commands are avaliable at the prompt), and I'd love to get access to DevTrack in the same way, but it's looking like it's off limits, UI only. Does anyone have any experience with this? Much appreciated. I have searched the posts, came up with nothing. Thanks! From uomart at ihug.co.nz Wed Nov 9 03:16:00 2005 From: uomart at ihug.co.nz (Jon Monteleone) Date: Wed, 9 Nov 2005 21:16:00 +1300 Subject: Installing Tkinter on knoppix Message-ID: <002b01c5e505$d33ffb30$5200a8c0@rmse> Greetings, Does anybody have a website where I can download a copy of Tkinter to install onto knoppix? Is it a pretty straightforward install? Cheers -Jon From jzgoda at o2.usun.pl Fri Nov 11 11:27:47 2005 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 11 Nov 2005 17:27:47 +0100 Subject: Inserting Records into SQL Server - is there a faster interface than ADO In-Reply-To: <1131724751.606322.162110@g44g2000cwa.googlegroups.com> References: <1131724751.606322.162110@g44g2000cwa.googlegroups.com> Message-ID: geskerrett at hotmail.com napisa?(a): > Is there a "faster" method I can use to connect to the SQL server ? > Or does anyone have any "optimization" tips the can offer ? This has nothing with python, but the fastest way to load large amount of data to MS SQL Server database is DTS import from flat file. To spped up the things a bit, do not commit transaction after each row inserted -- commit whole batch. -- Jarek Zgoda http://jpa.berlios.de/ From mde at micah.elliott.name Wed Nov 9 12:26:35 2005 From: mde at micah.elliott.name (Micah Elliott) Date: Wed, 9 Nov 2005 09:26:35 -0800 Subject: parse data In-Reply-To: <43722126$1@news.uni-ulm.de> References: <1131549682.441233.55330@f14g2000cwb.googlegroups.com> <43722126$1@news.uni-ulm.de> Message-ID: <20051109172635.GB11929@kitchen.client.attbi.com> On Nov 09, Dennis Benzinger wrote: > Use the re module: > > import re > your_data = """person number 1 > > Name: bob > Age: 50 > > > person number 2 > > Name: jim > Age: 39""" > > names = [] > for match in re.finditer("Name:(.*)", your_data): > names.append(match.group(1)) > print names Dennis' solution is correct. If you want to avoid REs, and concision and speed are premiums, then you might refine it to: names = [line[5:].strip() for line in your_data.split('\n') if line.startswith('Name:')] -- _ _ ___ |V|icah |- lliott http://micah.elliott.name mde at micah.elliott.name " " """ From mwm at mired.org Sat Nov 5 22:05:58 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 05 Nov 2005 22:05:58 -0500 Subject: Python doc problem example: gzip module (reprise) References: <1131186286.686748.214280@g47g2000cwa.googlegroups.com> <1131192936.228280.150530@g44g2000cwa.googlegroups.com> <436d232b$0$6017$4fafbaef@reader4.news.tin.it> <86u0eqsigi.fsf@bhuda.mired.org> <7x4q6q7f6b.fsf@ruckus.brouhaha.com> <86hdaqsfjo.fsf@bhuda.mired.org> <7x3bmafrip.fsf@ruckus.brouhaha.com> Message-ID: <86d5lescfd.fsf@bhuda.mired.org> Paul Rubin writes: >> To my knowledge the PSF isn't doing anything about including the >> documentation with their distribution, so they shouldn't care about >> the licenses. Wanting to bundle a good tutorial for everything in >> the library might be on the list, but the licenses on third-party >> tutorials shouldn't matter until you are considering bundling them. > It's only -because- of those licenses that there's any reason not to > bundle. Actually, there are other reasons, just as there are reasons besides licensing for not simply including third party libraries into the standard library. Most important is the issue of maintenance: is someone going to commit to keeping an added document up to date with the distribution? Bundling out of date documentation is a bad thing. Bundling documentation that is going to be left out of the next release because nobody updated it isn't much better. The author of the documentation is the logical person to do this, but if they wanted the documentation bundled with Python, they probably would have submitted it as a PR (I know that's what I do for OSS projects). >> In that light, the only major omission I can think of is Tkinter, as >> the only good docs - tutorial, reference, or otherwise - is the >> Grayson's book. > I found > http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html > to be a pretty good tutorial, though incomplete as a reference. Thanks for the URL, but that's just a short list of links, most of which I've already seen. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jgrahn-nntq at algonet.se Tue Nov 8 12:19:57 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 8 Nov 2005 17:19:57 GMT Subject: Text Auto-fill References: <1131417699.631271.156480@g49g2000cwa.googlegroups.com> Message-ID: On 7 Nov 2005 18:41:39 -0800, ChuckDubya at gmail.com wrote: > It's common in web browsers to have a text auto-fill function for > personal information or passwords or whatnot. The flavor that I'm > referring to is the kind that pops up as you're typing the word, not > the kind that fills text fields before typing has started. > > Well I want to know how to do that in Python. I'm looking to edit IDLE > so that it doesn't take me forever to code four lines. I'm very fond of the Emacs feature called 'dabbrev-expand', which lets you type the start of a word and cycle through all words in all open files that starts with those letters. Not an answer to your question, but if you're going to hack on completion algorithms, you might as well hack on a really great one! > Eventually, I want to create a Visual Basic-type environment for > myself. I'm a moron, and I need all the coding help I can get. I suspected as much ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From max at alcyone.com Sun Nov 13 16:16:43 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Nov 2005 13:16:43 -0800 Subject: Copyright [was Re: Python Obfuscation] In-Reply-To: References: Message-ID: David T wrote: > Individuals, and perhaps groups of individuals are the creators of > works. When someone pays you to create a work, then they own the copyright, not you. It's called work for hire. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis There is no fate that cannot be surmounted by scorn. -- Albert Camus From robert.kern at gmail.com Sun Nov 27 14:19:42 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 27 Nov 2005 11:19:42 -0800 Subject: Which License Should I Use? In-Reply-To: References: <1132947046.639811.14650@g49g2000cwa.googlegroups.com><1133041306.601950.213710@g43g2000cwa.googlegroups.com> Message-ID: Andrew Koenig wrote: > "Robert Kern" wrote in message > news:mailman.1228.1133042840.18701.python-list at python.org... > >>You're in something of a gray area, but one that has seen a lot of >>litigation. Although you are "technically" a consultant, you are >>probably considered an employee with regards to the "work made for hire" >>doctrine. You should probably have a chat with a lawyer soon (I am not >>one! TINLA!). > > I'm pretty sure that there was a change to the copyright laws a few years > ago (perhaps as part of the DMCA), that made it clear that you own > everything you produce, unless you're a W-2 employee or there is a written > agreement to the contrary. The US Copyright Office does not agree with you. http://www.copyright.gov/circs/circ09.pdf But you can read the text of the DMCA itself. http://www.eff.org/IP/DMCA/hr2281_dmca_law_19981020_pl105-304.html -- 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 vagrantbrad at yahoo.com Wed Nov 23 19:23:11 2005 From: vagrantbrad at yahoo.com (vagrantbrad at yahoo.com) Date: 23 Nov 2005 16:23:11 -0800 Subject: Using Cron to run a python program Message-ID: <1132791791.548850.186420@o13g2000cwo.googlegroups.com> I'm using python 2.4 running on Fedora Core 4. I have written a python program called ipscan.py that checks the external ip address of my cable internet connection, and on change, will update the dns records at my dns provider, zoneedit. So basically, I've setup dynamic dns using python. Once the ip compare and/or update is complete, I log the results to a text file called update.log. When I run the program in a bash shell with the command "python ipscan.py", the program runs fine and the results are appended to update.log. When I run this program as a cron job under the root user with the previously mentioned command, the program runs without errors but does not append an entry to the log. The permissions on the update.log file should not be an issue since I'm running the cron job as root, but I've given root write permissions just to be safe. What would cause the logging to work at a command prompt but fail in cron? I'm not getting any errors in the cron logs or /var/spool/mail/root. Thanks for your assitance. From peter at engcorp.com Tue Nov 1 20:26:27 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 01 Nov 2005 20:26:27 -0500 Subject: Flat file, Python accessible database? In-Reply-To: References: <877jbsxnrx.fsf@lucien.dreaming> Message-ID: Karlo Lozovina wrote: > bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) wrote in > news:877jbsxnrx.fsf at lucien.dreaming: > >>If you need it to be SQL-like, SQLite seems to be the right thing. > > Tried that one, but had some problems setting things up. On the other > hand, BerkeleyDB + Pybsddb worked like a charm, with no setting up (under > Cygwin). I'm very curious what problems you had. In my experience SQLite requires *nothing* I'd call "setup". You install Pysqlite or APSW, write your code, and it runs and works. There are no configuration steps required, nothing but creating tables (and that's a standard step with any SQL-like database). What environment were you using, and what kind of issues did you encounter? (I ask because I often recommend SQLite, but would like to temper that advice if in some cases these setup problems would cause someone trouble.) -Peter From nnorwitz at gmail.com Wed Nov 16 01:10:42 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 15 Nov 2005 22:10:42 -0800 Subject: best way to discover this process's current memory usage, cross-platform? In-Reply-To: <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> <1132080864.280909.51540@g44g2000cwa.googlegroups.com> <1h62exx.1oo8bj016pjj2vN%aleax@mail.comcast.net> Message-ID: <1132121442.019702.66620@g47g2000cwa.googlegroups.com> Alex Martelli wrote: > matt wrote: > > > Perhaps you could extend Valgrind (http://www.valgrind.org) so it works > > with python C extensions? (x86 only) > > Alas, if it's x86 only I won't even look into the task (which does sound > quite daunting as the way to solve the apparently-elementary question > "how much virtual memory is this process using right now?"...!), since I > definitely cannot drop support for all PPC-based Macs (nor would I WANT > to, since they're my favourite platform anyway). Valgrind actually runs on PPC (32 only?) and amd64, but I don't think that's the way to go for this problem. Here's a really screwy thought that I think should be portable to all Unixes which have dynamic linking. LD_PRELOAD. You can create your own version of malloc (and friends) and free. You intercept each call to malloc and free (by making use of LD_PRELOAD), keep track of the info (pointers and size) and pass the call along to the real malloc/free. You then have all information you should need. It increases the scope of the problem, but I think it makes it soluble and somewhat cross-platform. Using LD_PRELOAD, requires the app be dynamically linked which shouldn't be too big of a deal. If you are using C++, you can hook into new/delete directly. n From cjw at sympatico.ca Sat Nov 12 16:21:46 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 12 Nov 2005 16:21:46 -0500 Subject: tutorial example In-Reply-To: References: <20051112015026.74881.qmail@web35903.mail.mud.yahoo.com> Message-ID: Max Erickson wrote: > Not in python. > > For example, what would you call the following? > > def rsum(n, m): > print n+m > return n+m > I would call it a python function with a side-effect. Colin W. > > In python a method is callable attached to an object. A function is a > callable object constructed with a def statement. > > max > From JHoover at fbi.gov Fri Nov 18 15:27:56 2005 From: JHoover at fbi.gov (Gordon Airporte) Date: Fri, 18 Nov 2005 15:27:56 -0500 Subject: Type-checking unpickled objects Message-ID: I have this class, and I've been pickling it's objects as a file format for my program, which works great. The problems are a.) how to handle things when the user tries to load a non-pickled file, and b.) when they load a pickled file of the wrong class. a. I can handle with a general exception I guess. I just tried to pickle.load() a .pyc and it failed with a 'KeyError' exception - however that works. It might do that every time, it might not. Regarding b., if I type check I simply get the 'instance' type, which doesn't get me all of the way there because I might have an instance of the wrong class. I can't find any sort of __type__ attribute to set in the objects. Perhaps I should use __str__? From petantik.fool at gmail.com Fri Nov 11 11:11:32 2005 From: petantik.fool at gmail.com (petantik) Date: 11 Nov 2005 08:11:32 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> Message-ID: <1131725491.983050.90210@g47g2000cwa.googlegroups.com> Ben Sizer wrote: > Mike Meyer wrote: > > There are ways to distribute > > Python modules so that the user can't just open them in a text > > editor. There are also ways to get cryptographic security for > > distributed modules. > > I know distributing as bytecode helps, but I was under the impression > that the disassembers worked pretty well. With the dynamic nature of > the language I expect that all the variable names are largely left > intact. You win some, you lose some, I guess. > > As for cryptographic security, could you provide a link or reference > for this? I am quite interested for obvious reasons. I'd be concerned > that there's a weak link in there at the decoding stage, however. > > I have considered distributing my program as open source but with > encrypted data. Unfortunately anyone can just read the source to > determine the decryption method and password. Maybe I could put that > into an extension module, but that just moves the weak link along the > chain. > > > Yes, if you use the same methods you use in C++, > > it's "much harder". But by the same token, if you tried to use the > > methods you'd use in a Python program in C++, you'd find that the C++ > > version was "much harder". > > Well, I'm not sure what you mean here. A compiled C++ program is much > harder to extract information from than a compiled Python program. > That's without applying any special 'methods' on top of the normal > distribution process. > > > Of course, as Alex pointed out, all of these are just keeping honest > > people honest. The crooks have all the advantages in this game, so you > > really can't expect to win. > > No, certainly not. But if you can mitigate your losses easily enough - > without infringing upon anyone else's rights, I must add - then why not > do so. > > -- > Ben Sizer. The economics of software distribution must certainly come into it, doing a cost/benefit analysis of whether it's worth the effort to protect your code from would be crackers. The problem with code protection methodology in general is that once its cracked everyone has access to code for, maybe, all software using the particular protection scheme. the argument that most people buy software rather than get a pirated version depends on the country that they are in e.g. china's piracy problem where shops sell pirated software with no retribution by the state - remember china is about to be the worlds largest economic superpower The above problem illustrate why code needs to be protected in an effective way, by law and code protection schemes With python there is no comfort factor in knowing that your code is being protected, well not than I can see, compared with protection schemes for compiled code which are used by many commercial software companies. Of course, we know that there can never be a 100% way to protect code that some pirate won't overcome but it still stops the casual user or beginner 'crackers' from stealing the code and digging in to your profit margin. btw i'm no expert on copy protection mechanism but the question I raised originally, i believe, is valid and should be discussed http://petantik.blogsome.com - A Lucid Look at Reality From pythonnew at gmail.com Tue Nov 22 12:31:28 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 22 Nov 2005 09:31:28 -0800 Subject: after sorted from the lists In-Reply-To: <8c11e4350511220858q16750dc5v1fdab6d3e88bd83a@mail.gmail.com> References: <8c11e4350511220649h3d3dcb41i1e8fafac5c4b9201@mail.gmail.com> <20051122152949.GC9567@unpythonic.net> <8c11e4350511220858q16750dc5v1fdab6d3e88bd83a@mail.gmail.com> Message-ID: <8c11e4350511220931i3dc2a707nea19c60f56ca930c@mail.gmail.com> On 11/22/05, Ben Bush wrote: > On 11/22/05, jepler at unpythonic.net wrote: > > >>> ll = [[1,2],[2,1],[3,1],[1,4],[3,3],[1,4]] > > >>> ls = [frozenset(i) for i in ll] > > >>> ss = set(ls) > > >>> ss > > set([frozenset([1, 3]), frozenset([1, 2]), frozenset([1, 4]), frozenset([3])]) > > >>> [list(i) for i in ss] > > [[1, 3], [1, 2], [1, 4], [3]] > why this happens? > >>> from sets import * > >>> ll = [[1,2],[2,1],[3,1],[1,4],[3,3],[1,4]] > >>> ls = [frozenset(i) for i in ll] > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'frozenset' is not defined > I know that: Python 2.3 introduced the sets module. C implementations of set data types have now been added to the Python core as two new built-in types, set(iterable) and frozenset(iterable). But why it does not work in my machine? PythonWin 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> from sets import * >>> dir(frozenset) Traceback (most recent call last): File "", line 1, in ? NameError: name 'frozenset' is not defined From deets at nospam.web.de Wed Nov 9 04:07:52 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Nov 2005 10:07:52 +0100 Subject: cx_Oracle callproc output parameters In-Reply-To: <1131486799.092340.72120@g43g2000cwa.googlegroups.com> References: <1131486799.092340.72120@g43g2000cwa.googlegroups.com> Message-ID: <3tdsjaFsdo3aU1@uni-berlin.de> infidel wrote: > I have a stored procedure that has a single output parameter. Why do I > have to pass it a string big enough to hold the value it is to receive? > Why can't I pass an empty string or None? > > >>>>import cx_Oracle as oracle >>>>connection = oracle.connect('usr/pwd at tns') >>>>cursor = connection.cursor() >>>>network_name, = cursor.callproc('my_pkg.get_network_name_sp', ('',)) > > Traceback (most recent call last): > File "", line 1, in ? > DatabaseError: ORA-06502: PL/SQL: numeric or value error: character > string buffer too small > ORA-06512: at "USR.MY_PKG", line 35 > ORA-06512: at line 1 > > The following works fine, but I don't like having to do it: > > >>>>network_name, = cursor.callproc('my_pkg.get_network_name_sp', (' ' * 32,)) > > > Am I missing something obvious here? Yes - where should the oracle store the data if you pass None (null-pointer!) or a too short string? The C-Api of oracle requires an INOUT-Paramter to be properly dimensioned - its like other c-calls, that take a pointer and a size argument. Thus you don't have to deal with freeing malloc'ed memory in the caller. I'm not sure about it, but possibly a _return_-value might help here, possible by using a function inbstead of a procedure. Did you try that? Of course it would require to rewrite your procedure to be a function, or if that is not possible due to others using it too, wrap it in a p/sql function. I'm a bit rusty on p/sql, so I can't wirte it out of my head. Then you could e.g. do select my_pkg.wrapped_get_network_name() from dual and wouldn't have to care about sizes. regards, Diez From hgk at et.uni-magdeburg.de Fri Nov 11 07:40:21 2005 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Fri, 11 Nov 2005 13:40:21 +0100 Subject: Good python reference? In-Reply-To: <1131693916.660356.75310@g44g2000cwa.googlegroups.com> References: <1131693916.660356.75310@g44g2000cwa.googlegroups.com> Message-ID: derek schrieb: > Hello! I'm new to the group and am looking for a decent reference for > information about the history / evolution of the Python language and > its features. Typing, scoping, etc... I'd appreciate any good links. > Thanks! > > - Derek > Looking at the title of your mail I would answer http://rgruet.free.fr/PQR24/PQR2.4.html But history? Sorry.... Hans Georg From benji at benjiyork.com Tue Nov 15 14:41:50 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 15 Nov 2005 14:41:50 -0500 Subject: Default method arguments In-Reply-To: <437a1e7a$0$6131$636a15ce@news.free.fr> References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a1e7a$0$6131$636a15ce@news.free.fr> Message-ID: <437A39FE.1020102@benjiyork.com> bruno at modulix wrote: > Another solution to this is the use of a 'marker' object and identity test: > > _marker = [] > class A(object): > def __init__(self, n): > self.data =n > def f(self, x = _marker): > if x is _marker: > x = self.data > print x I'll add my 2 cents to the mix: default = object() class A(object): def __init__(self, n): self.data = n def f(self, x=default): if x is default: x = self.data print x -- Benji York From siona at chiark.greenend.org.uk Fri Nov 4 12:01:16 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 Nov 2005 17:01:16 +0000 (GMT) Subject: strange sockets References: Message-ID: <8ft*3tU2q@news.chiark.greenend.org.uk> In article , Skink wrote: >% python client.py client.py client.py client.py server.py server.py >init 0.00066089630127 >client.py 0.000954866409302 >client.py 0.0408389568329 >client.py 0.0409188270569 >server.py 0.0409059524536 >server.py 0.0409259796143 > >what's wrong here? That smells of a Nagle/delayed ACK problem to me (see, for instance, http://www.port80software.com/200ok/archive/2005/01/31/317.aspx). 40ms is the default delayed ACK timeout on Linux, IIRC (pretty much everything else uses 200ms). I *think* what's happening from the server's point of view is: receive request 1 send length (first undersized packet is sent immediately by Nagle) (client delays ack #1) send data (larger than 1 packet, send immediately) (client delays acks #2--#n) receive request 2 with ack #1 buffer sending length (undersized packet, not received last ack) -> 40ms passes <- (client timesout delayed acks and sends) send length send data (as before) although why the undersized packet at the end of the first chunk of data isn't buffered, I don't know. Solutions: either change > conn.sendall(struct.pack("!i", len(data))) > conn.sendall(data) to conn.sendall(struct.pack("!i", len(data)) + data) or after creating conn conn.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) to disable Nagle. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From fabioz at esss.com.br Thu Nov 17 11:44:24 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Thu, 17 Nov 2005 13:44:24 -0300 Subject: PyDev 0.9.8.5 released In-Reply-To: <434E801E.3010702@esss.com.br> References: <43382E1F.3000600@esss.com.br> <434E801E.3010702@esss.com.br> Message-ID: <437CB368.2010501@esss.com.br> Hi All, PyDev - Python IDE (Python Development Enviroment for Eclipse) version 0.9.8.5 has been released. Check the homepage (http://pydev.sourceforge.net/) for more details. Details for Release: 0.9.8.5 Major highlights: ------------------- * Removed the dependency on packages 'sun.xxxx.Base64', so that other VMs can be targetted * Some code-completion problems in the 'resolution order' regarding tokens in __init__ were solved * Added option so that the user can choose whether to automatically add 'self' or not in method declarations Cheers, Fabio -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com From skip at pobox.com Sat Nov 12 19:31:40 2005 From: skip at pobox.com (skip at pobox.com) Date: Sat, 12 Nov 2005 18:31:40 -0600 Subject: elementtree.ElemenTree barfs on my Safari Cookies file Message-ID: <17270.35180.907033.431384@montanaro.dyndns.org> Safari stores its cookies in XML format. Looking to try and add support for it to cookielib I started by first trying to parse it with Fredrik Lundh's elementtree package. It complained about an invalid token. Looking at the spot it indicated in the file, I found a non-ASCII, but (as far as I can tell) perfectly valid utf-8 string. I whittled the plist file down to what I've attached. With it I get >>> e = elementtree.ElementTree.parse("Cookies.plist") Traceback (most recent call last): File "", line 1, in ? File "/Users/skip/local/lib/python2.5/site-packages/elementtree/ElementTree.py", line 864, in parse tree.parse(source, parser) File "/Users/skip/local/lib/python2.5/site-packages/elementtree/ElementTree.py", line 588, in parse parser.feed(data) File "/Users/skip/local/lib/python2.5/site-packages/elementtree/ElementTree.py", line 1132, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 17, column 12 I had no trouble decoding that string as unicode. Any ideas what's wrong? Thx, Skip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/octet-stream Size: 511 bytes Desc: not available URL: From Dennis.Benzinger at gmx.net Tue Nov 8 05:52:28 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 08 Nov 2005 11:52:28 +0100 Subject: any python module to calculate sin, cos, arctan? In-Reply-To: References: Message-ID: <43708367$1@news.uni-ulm.de> Shi Mu schrieb: > any python module to calculate sin, cos, arctan? Yes. Use the math module or the cmath module if you need mathematical functions for complex numbers. Bye, Dennis From xray_alpha_charlie at yahoo.com Sun Nov 20 11:09:13 2005 From: xray_alpha_charlie at yahoo.com (john boy) Date: Sun, 20 Nov 2005 08:09:13 -0800 (PST) Subject: email separation Message-ID: <20051120160913.13612.qmail@web35911.mail.mud.yahoo.com> Hey....I have signed up to receive emails from the python forum and the amount of emails I receive on any day is fairly numerous...Does anyone know if I can somehow separate all mails coming from the python forum from all of my other mail, so I can open it from another folder or something like that under the same address...I have a yahoo account... --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lamthierry at gmail.com Mon Nov 21 17:34:35 2005 From: lamthierry at gmail.com (Thierry Lam) Date: 21 Nov 2005 14:34:35 -0800 Subject: Help with modal in Gtk::FileChooserDialog Message-ID: <1132612475.195697.4780@z14g2000cwz.googlegroups.com> Does anyone know how to set modal to True for Gtk::FileChooserDialog? Thanks Thierry From fredrik at pythonware.com Wed Nov 2 15:43:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Nov 2005 21:43:59 +0100 Subject: Hexadecimal Conversion in Python References: <1130963306.183112.3720@g49g2000cwa.googlegroups.com> <1130963890.241985.268920@g14g2000cwa.googlegroups.com> Message-ID: "DaBeef" wrote:/ > it is returning data such as 0x04. I am new to python so this is a > pain for me, learning to do this in a language whose llibrary is > somewhat limited. you make no sense at all. what are you receiving data from? how are you receiving it? what library are you using? what's 0x04? an integer? a string? a byte? what's .... ? a string? a typo? an odd character that's munged by your mail program? From peter at engcorp.com Mon Nov 28 18:33:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 28 Nov 2005 18:33:58 -0500 Subject: General question about Python design goals In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > Ok, these are nice aphorisms with some truth. But I had to think of the > German excuse "Wer Ordnung h?lt ist nur zu Faul zum Suchen - ein Genie > ?berblickt das Chaos." ("Those who try to keep things tidy are just too > lazy to search for searching - a genius surveys the chaos"). Is that really the translation? "too lazy to search for searching"? What does that mean? Google translate doesn't help... here's it's rather comical attempt: "Who order holds is only to putrid for looking for - a genius grasps the chaos" -Peter From jepler at unpythonic.net Tue Nov 15 22:46:40 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 15 Nov 2005 21:46:40 -0600 Subject: Can anyone tell me if pygame and Tkinter can work together? In-Reply-To: References: <20051116012828.GA13790@unpythonic.net> Message-ID: <20051116034640.GA17342@unpythonic.net> On Tue, Nov 15, 2005 at 06:33:40PM -0700, Nathan Pinno wrote: > Thanks. I was going to use TKInter to pop up a message box, then use pygame > to run the game and display the score on the playing surface. Is this still > possible (I'm using Python 2.4.1 and Pygame 1.7.0 on WinXP with Service Pack > 2)? This is more likely to work than the scenario I first considered, where both GUI libraries would be in use at the same time. With my understanding of how X works, and my knowledge of Tk, you'd probably be successful if what you want to do is first use GUI Library A, and then GUI Library B. This resolves the issue with XSetErrorHandler, for instance, because you'll be completely done with Library A at the time you call the initialization routines of Library B. It also resolves the event loop problem, because you never need to allow Libraries A and B to receive events during the same phase of the program. I don't know anything about Windows, and I haven't actually given this scenario a try on Linux either, so it's still all idle speculation on my part. Actual experimentation on your part wouldn't be that hard, though. Just write the simplest possible Tk program as a callable function 't()' and the simplest possible pygame program as a callable function 'p()', and then see what happens when you run them back to back: def t(): import Tkinter t = Tkinter.Tk() Tkinter.Button(t, command = t.destroy).pack() t.mainloop() def p(): likewise t() p() Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From vida00 at gmail.com Wed Nov 23 17:06:29 2005 From: vida00 at gmail.com (vida00 at gmail.com) Date: 23 Nov 2005 14:06:29 -0800 Subject: newbie class question Message-ID: <1132783589.533488.51460@g44g2000cwa.googlegroups.com> Hi, I scouted the ng for someone w/ a similar problem and couldn't find one, so I might be thinking about this probable non-issue in a wrong way. What I am trying to accomplish should be pretty self explanatory when looking at the following: >>> class heh(object): ... def __init__(self): ... self.foo='hello' ... def change(self): ... self.foo+=' world' ... def show(self): ... return self.foo ... ... class hih(object): ... def __init(self): ... self.foo=heh.foo() ... def show(self): ... return self.foo ... >>> x=heh() >>> x.show() 'hello' >>> x.change() >>> x.show() 'hello world' >>> y=x.hih() >>> y.show() Traceback (most recent call last): File "", line 1, in ? File "", line 13, in show AttributeError: 'hih' object has no attribute 'foo' so, how do I reference heh.foo in its current state (i.e. 'hello world', not 'hello') from hih? Thanks, -Josh. From mwm at mired.org Sun Nov 27 00:08:36 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 27 Nov 2005 00:08:36 -0500 Subject: wxPython Licence vs GPL References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <86zmnuvsv0.fsf@bhuda.mired.org> <43861352$0$11076$e4fe514c@news.xs4all.nl> <86oe49wyky.fsf@bhuda.mired.org> <86acfsgols.fsf@bhuda.mired.org> <86sltjg2s8.fsf@bhuda.mired.org> <86y83bdmln.fsf@bhuda.mired.org> Message-ID: <86sltid6ej.fsf@bhuda.mired.org> Steven D'Aprano writes: > On Sat, 26 Nov 2005 18:18:44 -0500, Mike Meyer wrote: >> So that's the basis of the disagreement. I'm using "restriction" with >> the intent of communicating it's normal english meaning, > Your meaning is about as far from the plain English sense of "restrictive" restiction != restrictive. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From yahoo at nospam.leszczynscy Tue Nov 29 18:52:56 2005 From: yahoo at nospam.leszczynscy (Andy Leszczynski) Date: Tue, 29 Nov 2005 18:52:56 -0500 Subject: [OT] Oracle 9i client for Linux In-Reply-To: <438ced15$0$447$6c56d894@reader0.news.be.easynet.net> References: <438ced15$0$447$6c56d894@reader0.news.be.easynet.net> Message-ID: Bernard Delm?e wrote: > Look into the Oracle Instant Client: > > (might require a -free- OTN registration) It is version 10, would it be compatible with 9i servers? > Be sure to download the smallish "sdk" if you want to compile client code > (e.g. cx_oracle - highly recommended Indeed I use cx_oracle but on M$ yet. Want to move to Linux. A. From martin.witte at gmail.com Tue Nov 15 11:02:45 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 15 Nov 2005 08:02:45 -0800 Subject: Need advice on subclassing code In-Reply-To: References: Message-ID: <1132070565.544686.241390@g49g2000cwa.googlegroups.com> Would the approach of using a switch to decide to instatite which class good for you, like: py> class C: py. name = 'C' py. py> class D: py. name = 'D' py. py> switch = { (1, 1): C, (1,2): D } py> x = 1 py> y = 2 py> c = switch[(x,y)]() py> print c.name D py> From bdesth.quelquechose at free.quelquepart.fr Sun Nov 20 18:51:09 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 Nov 2005 00:51:09 +0100 Subject: Underscores in Python numbers In-Reply-To: <1132460920.666321.264290@f14g2000cwb.googlegroups.com> References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132460920.666321.264290@f14g2000cwb.googlegroups.com> Message-ID: <4381016f$0$4205$626a14ce@news.free.fr> Raymond Hettinger a ?crit : > Gustav H?llberg wrote: > >>I tried finding a discussion around adding the possibility to have >>optional underscores inside numbers in Python. This is a popular option >>available in several "competing" scripting langauges, that I would love >>to see in Python. >> >>Examples: >> 1_234_567 >> 0xdead_beef >> 3.141_592 > > > I suppose it could be done. OTOH, one could argue that most production > code has no business hardwiring-in numerical constants greater than 999 > ;-) > That's what I thought at first, but Steven D'Aprano made some good points here IMHO, ie : """ Not all numeric constants used have simple formulae, or *any* formulae, or can be calculated on the fly in any reasonable time. Numeric programming often uses magic constants which truly are "magic" (in the sense that where they come from requires deep, difficult, and sometimes hidden knowledge). Nobody sensible wants to be typing in long strings of digits, but sometimes it is unavoidable. """ and """ Another sensible usage case is in the interactive interpreter. If you are using Python interactively, you may wish to use numeric literals with large numbers of digits. It is not feasible to read them from a data file, and using a special converter function is impractical and unnecessary. """ So even if it's far from a common use case for *most* Python users, it may be a common use case for *some* Python users. Also, someone mentionned the use of Python as a configuration langage - which is probably a much more common use case. So FWIW, I'd be +1 on adding it *if and only if*: - it's trivial to implement [1] - it doesn't break older code and +1 on the space as group delimiter BTW. [1]: I never wrote a language by myself, but I've played a bit with parsers and lexers, and I _guess_ (which implies I may be wrong !-) it wouldn't require much work to add support for a "literal numeric grouping" syntax in Python. From dr.addn at gmail.com Tue Nov 15 01:35:51 2005 From: dr.addn at gmail.com (adDoc's networker Phil) Date: Mon, 14 Nov 2005 22:35:51 -0800 Subject: about invalid syntax In-Reply-To: <8c11e4350511142148m64e4eda8t2cf33467a0e2fa40@mail.gmail.com> References: <8c11e4350511142148m64e4eda8t2cf33467a0e2fa40@mail.gmail.com> Message-ID: <8fd4a2fe0511142235lb22aa96ta915fba44868ad5d@mail.gmail.com> . maybe you could separate your code into parts { python std, pythonwin-specific}, and then use a debugger to know most of the problem sources? (I'm not familiar with pythonwin, I assume it's a superset of python std) . On 11/14/05, Ben Bush wrote: > > When I run scripts in PythonWin, > sometimes will get the message of invalid syntax error. > How can I check which error I made? > For example, in VB, you might got the wrong place highlighted and help > message too. > > -- > Thanks! > Ben Bush > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- American Dream Documents http://www.geocities.com/amerdreamdocs/home/ "(real opportunity starts with real documentation) -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Fri Nov 18 17:42:23 2005 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 18 Nov 2005 16:42:23 -0600 Subject: examining python objects In-Reply-To: <1132351505.628598.325420@o13g2000cwo.googlegroups.com> References: <1132339687.048155.252160@g47g2000cwa.googlegroups.com> <1132351505.628598.325420@o13g2000cwo.googlegroups.com> Message-ID: <4866bea60511181442y5688c0a4w644fc51296afa678@mail.gmail.com> On 18 Nov 2005 14:05:05 -0800, rurpy at yahoo.com wrote: > __repr__ almost always only prints a summary of it's > object, not the detailed internal structure that I want to > see. When it prints values, that are not pretty-printed, > nor are the objects that constitute the value printed > recursively. > > Writing my own __repr__() is emphatically what I don't > want to do! That is no better than debugging by inserting > print statements, a technique from the 1980's. > It's still a good idea, though > I am surprised (err, astounded actually) that a basic > tool like this isn't available. Besides debugging, I would > think it would be very helpful to people leaning python. > All of this functionality is intrinsically available within Python - it's a dynamic language and you can easily inspect an object directly to see what it looks like. Try (pretty) printing the objects __dict__ or __slots__. > Perhaps one of the Python IDEs contains something > like this I could extract from it but I was hoping to shortcut > what will be a time consuming search. > wxPython includes a graphical shell & namespace browser which you may find useful. > Ben Finney wrote: > > rurpy at yahoo.com wrote: > > > Is there a function/class/module/whatever I can use to look at > > > objects? > > > > The repr() function is what you want. > > > > > I want something that will print the object's value (if any) in > > > pretty-printed form, and list all it's attributes and their values. > > > And do all that recursively. > > > > The repr() function returns what the object's __repr__ method returns. > > You'll notice that the builtin container types (string, set, list, > > dict, ...) will show the values of their referred objects also. > > > > Define the __repr__ method on your classes so that they show whatever > > information you think is useful for debugging. > > > > -- > > \ "If you go flying back through time and you see somebody else | > > `\ flying forward into the future, it's probably best to avoid eye | > > _o__) contact." -- Jack Handey | > > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list > From nyamatongwe+thunder at gmail.com Tue Nov 22 16:00:02 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 22 Nov 2005 21:00:02 GMT Subject: sort the list In-Reply-To: References: Message-ID: Nick Craig-Wood: > Since no-one mentioned it and its a favourite of mine, you can use the > decorate-sort-undecorate method, or "Schwartzian Transform" That is what the aforementioned key argument to sort is: a built-in decorate-sort-undecorate. >>> lst = [[1,4],[3,9],[2,5],[3,2]] >>> print lst [[1, 4], [3, 9], [2, 5], [3, 2]] >>> lst.sort(key=lambda x: x[1]) >>> print lst [[3, 2], [1, 4], [2, 5], [3, 9]] Neil From pwatson at redlinepy.com Sun Nov 27 15:51:28 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 27 Nov 2005 14:51:28 -0600 Subject: nesting for statements? In-Reply-To: <1133114314.033077.104970@g14g2000cwa.googlegroups.com> References: <1133114314.033077.104970@g14g2000cwa.googlegroups.com> Message-ID: <3uukiiF135t04U1@individual.net> tpcolson at gmail.com wrote: > I'm not what you'd call a "programmer" of any sort, so perhaps this > question may seem arcane and result in a plethora of "you idiot" > threads, but here goes: > > ArcGIS 9.1 has a neat interface with python (2.1-2.4), allowing me to > do all sorts of spatial operations within python, namely, repetitive > functions. > > > In the below code, I'm trying to iterate thru multiple values of the > variable "Discretisation error factor" using a for statement that > temporarily populates "Disc", which is used as input in "Discretisation > error factor" in the gp.TopoToRaster._sa function. > > > For each iteration of "Discretisation error factor", I'm trying to name > the output file "outa", "outb", "out...." > > Not quite sure how to implement that. There are lots of examples on > nested for loops out there, but nothing on combing that with a output > file naming sheme. > > The gp.TopoToRaster_sa function by itself without all the for > statements works fine. > > Appreciate any help on this, other wise I have to manually interpolate > hundreds of LiDAR point clouds, each, 10 times for diff. values of DEF. > > > > # TopoToRaster_sample.py > # Description: Interpolate a series of point features onto a > rectangular raster using TopoToRaster > # Requirements: None > # Author: ESRI > # Date: 12\\01\\03 > > # Import system modules > import sys, string, os, win32com.client > > # Create the Geoprocessor object > from win32com.client import Dispatch > gp = Dispatch("esriGeoprocessing.GpDispatch.1") > > # Check out any necessary licenses > gp.CheckOutExtension("spatial") > > # Iterate 2 thru 4 in increments of 2 for DEF > # Name the "2" dem "outa" and the "4" dem "outb" > for x in range(2,4): > Disc = int(x) > names = ["a","b"] > for y in names: > Out_Dem = "out"+y > > > try: > > # Process: Topo to Raster... > gp.TopoToRaster_sa("C:\\temp\\falls_lidar.shp Z PointElevation", > Out_Dem, # Variable for name of output raster. > This should increment name of output based on the for statement > "5", # Output raster cell size: each pixel is 5 > feet by 5 feet > "2103763.27 813746.12 2111850.32 822518.65", > #extent of raster borders, SPF, NC, NAD83 > "20", # #Grid Margin > "", #Smallest z value to be used in > interpolation (optional) > "", #Largest z value to be used in interpolation > (optional) > "NO_ENFORCE", #Drainage option > "SPOT", #Spot data option > "40", #Maximum number of iterations (optional) > "", #Roughness penalty (optional) > Disc, #Discretisation error factor: This should > increment DEF based on the for statement > "0", #Vertical standard error (optional) > "", #Tolerance 1 (optional) > "" #Tolerance 2 (optional) > ) > except: > print "ERROR OCCURED" > print gp.GetMessages() I think you want a filename generated for each pass through the loop. I would suggest generating the filenames before you ever start the loop in a list. Then, reference the filename list while you are in the loop. You could also construct the filename while you are in the loop. sor = 2 # start of range eor = 4 # end of range filenames = ['file' + chr((x-sor) + ord('a')) for x in range(sor, eor)] for x in range(sor, eor): print filenames[x - sor] If you do not want to create all of the filenames in memory at one time, you could generated them during the loop. However, this will not work well when you code is run on a system not using ASCII character encoding. for x in range(sor, eor): print 'file' + chr((x - sor) + ord('a')) Something using string.ascii_lowercase would work better. My guess is that on the mainframe using EBCDIC character encoding that string.ascii_lowercase still contains the LATIN SMALL LETTER characters, just as it does on ASCII-based systems. From fphsml at gmail.com Wed Nov 2 20:35:55 2005 From: fphsml at gmail.com (James) Date: 2 Nov 2005 17:35:55 -0800 Subject: Python for .NET and IronPython In-Reply-To: References: Message-ID: <1130981755.173817.91010@g47g2000cwa.googlegroups.com> IronPython is good if you want to bring in Python into a .NET world. Python for .NET is good if you want to bring in .NET into a Python world. As for your learning concerns, there need be none. There is really nothing to learn extra for the integration. They just work. Once you learn the .NET framework and Python, there isn't much to know additionally. While you are on topic, check out Boo. It is not the same as the ones you mentioned but you might find it interesting and useful while working with .NET if you have Python tastes. From irmen.NOSPAM at xs4all.nl Tue Nov 8 02:34:59 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 08 Nov 2005 08:34:59 +0100 Subject: socket receive file does not match sent file In-Reply-To: <1131332435.722801.96810@z14g2000cwz.googlegroups.com> References: <1131297183.385236.146170@g14g2000cwa.googlegroups.com> <1131332435.722801.96810@z14g2000cwz.googlegroups.com> Message-ID: <43705648$0$11067$e4fe514c@news.xs4all.nl> zelzel.zsu at gmail.com wrote: > when I test the two program in the same OS, > i mean from a redhat 9 OS to a redhat 9 OS, > It's ok. receivefile match sent file. > > > But when I run receiver on a Redhat 9, > and send file from a windows XP, > the received file's size is randomized. > > May be that's where the problem is. > No. Read Jean-Paul's reply. --Irmen From roy at panix.com Wed Nov 23 17:01:33 2005 From: roy at panix.com (Roy Smith) Date: Wed, 23 Nov 2005 17:01:33 -0500 Subject: Backwards compatibility [was Re: is parameter an iterable?] References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com> <437C36EA.8010600@REMOVEMEcyber.com.au> <438287DF.8030506@REMOVEMEcyber.com.au> Message-ID: "Fredrik Lundh" wrote: > I've said it many times, and I'll say it again: the only fundamentally > new concept that has been added since Python 1.5.2 is generators. > [...] > All the rest is just coloured frosting In my mind, the biggest thing since 1.5.2 is string methods. They are perhaps, as you say, just frosting, but they're very good tasting frosting :-) From auch-ich-m at g-kein-spam.com Tue Nov 15 07:22:50 2005 From: auch-ich-m at g-kein-spam.com (=?ISO-8859-1?Q?Andr=E9?= Malo) Date: Tue, 15 Nov 2005 13:22:50 +0100 Subject: codecs References: <4379d05d$0$10556$9b622d9e@news.freenet.de> Message-ID: * TK wrote: > sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout) > What does this line mean? "Wrap stdout with an UTF-8 stream writer". See the codecs module documentation for details. nd From steve at holdenweb.com Thu Nov 24 01:23:48 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 06:23:48 +0000 Subject: Python as Guido Intended In-Reply-To: <1132807138.648558.234880@g47g2000cwa.googlegroups.com> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1132800973.008501.34090@g14g2000cwa.googlegroups.com> <867jay1ybk.fsf@bhuda.mired.org> <1132805759.799632.265850@f14g2000cwb.googlegroups.com> <86u0e2zmwb.fsf@bhuda.mired.org> <1132807138.648558.234880@g47g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Mike Meyer wrote: > >>"bonono at gmail.com" writes: >> >>>>Maybe Python attracts people who share that belief. After all, TRTFTJ >>>>is implies TSBOOWTDI, and vice versa. >>> >>>I was not talking about the believe, I was talking about the way you >>>presented it. You are setting up an "imaginary" me, which is not me. >>>And that is the kind of arguments I saw, I believe this many times are >>>done unconciously. >> >>You're doing that yourself. But we don't have a real other person to >>work with - the best we can do is work with our model of that other >>person. That's life. >> > > In what way am I doing it myself ? It could be unconciously too but I > always welcome if it could be pointed out. > I think Mike (the Mike I imagine, anyway) merely intended to point out that since we can't live in each others' heads all communication is with an imaginary person, whose actual thoughts and feelings are unavailable to us. 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 kylotan at gmail.com Thu Nov 24 10:36:31 2005 From: kylotan at gmail.com (Ben Sizer) Date: 24 Nov 2005 07:36:31 -0800 Subject: Writing big XML files where beginning depends on end. In-Reply-To: References: Message-ID: <1132846591.731735.75120@g44g2000cwa.googlegroups.com> output = [] def write_tree(node): output.append("") sum = 0 for child in reversed(node.children): if child.type = leaf: output.extend(["", "%d" % node.value, ""]) sum += node.value else: sum += write_tree(node) output.append("" % sum) return sum write_tree(rootNode) output.reverse() print output :) (There is probably a cleaner way to do this than the quick hack above.) -- Ben Sizer From bonono at gmail.com Thu Nov 10 10:51:38 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 10 Nov 2005 07:51:38 -0800 Subject: [ x for x in xrange(10) when p(x) ] In-Reply-To: <1h5sutg.lo9536i8e9fN%aleax@mail.comcast.net> References: <1131593043.986202.273280@g44g2000cwa.googlegroups.com> <1h5rxys.nwlodz1syadnvN%aleax@mail.comcast.net> <1131594467.709976.320520@o13g2000cwo.googlegroups.com> <1131627394.890394.200070@g44g2000cwa.googlegroups.com> <1h5sutg.lo9536i8e9fN%aleax@mail.comcast.net> Message-ID: <1131637898.612217.258140@z14g2000cwz.googlegroups.com> Alex Martelli wrote: > So use takewhile(condition, some_generator) > > which is LESS to type. When your predicate is a function, there's no > need to wrap a lambda around it, just like there's no need to wrap an > '[x for x in' or '(x for x in' around a list/iterator. No. my predicate sometimes is not function but inline expression that needs scoping within nested for. > Complicated expressions often become hard to read; so, break the > expression up into more readable pieces, assigning names to the > intermediate steps. There's negligible price to pay for that, since in > Python assignment is NOT a copy, just a 'naming' of an intermediate > object. For example, instead of: > > for x in takefile(foo, takewhile(bar, zlupp)): ... > > you may choose to code, e.g., > > zlupps_bars = takewhile(bar, zlupp) > zb_foos = takewhile(foo, zlupps_bars) > for x in zb_foos: ... > > Flat is better than nested. > Sparse is better than dense. > Readability counts. > That is one opinion and I think I can decide when to break or not to break. Sometimes, breaking them in mutiple level for with interim name assignment is not desirable. In fact, because python allows me to write in both style, I practiced to write the same thing in both style and found that the nested list expression way is less error prone(at least for me ). From bonono at gmail.com Thu Nov 24 03:20:26 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 00:20:26 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: References: <1132815683.602078.216760@g14g2000cwa.googlegroups.com> Message-ID: <1132820426.374743.51410@g49g2000cwa.googlegroups.com> Fredrik Lundh wrote: > bonono at gmail.com wrote: > > > Fredrik Lundh wrote: > > > performance is of course another aspect; if you *need* two parallel > > > lists, creating a list full of tuples just to pull them apart and throw > > > them all away isn't exactly the most efficient way to do things. > > > > > > (if performance didn't matter at all, we could get rid most dictionary > > > methods; "iterkeys", "in", and locking should be enough, right?) > > > If I need two parallel list(one key, one value), I can still use the > > same [(k,v)] tuple, just access it as x[0], x[1]. > > that's a single list containing tuples, not two parallel lists. > > this is two parallel lists: > > k = d.keys() > v = d.values() > assert isinstance(k, list) > assert isinstance(v, list) > use(k, v) I know that is a single list of tuples, I mean that can be used as well. for k, _ in d.items(): print k for _, v in d.items(): print v for k in d.keys(): print k for v in d.values(): print v Would there be a noticeable performance difference ? From johnwalczak at comcast-dot-net.no-spam.invalid Fri Nov 4 19:14:38 2005 From: johnwalczak at comcast-dot-net.no-spam.invalid (john_walczak) Date: Fri, 04 Nov 2005 18:14:38 -0600 Subject: help with sending data out the parallel port References: Message-ID: I may have a solution to your problem that involves a small piece of hardware plugged into the serial port. contact me if interested in details. johnwalczak at comcast.net Sent via Archivaty.com From bokr at oz.net Tue Nov 29 19:31:44 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 30 Nov 2005 00:31:44 GMT Subject: Why are there no ordered dictionaries? References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <1132735254.039468.106660@g44g2000cwa.googlegroups.com> <4385b7b6.632202659@news.oz.net> <4389193a.8914908@news.oz.net> <438ca42e.241094455@news.oz.net> Message-ID: <438cea30.259016475@news.oz.net> On Tue, 29 Nov 2005 23:30:45 +0100, Christoph Zwerschke wrote: >I had the same idea to create a py.test to verify and compare various >implementations. The doctests in odict.py are nice, but you can't use >them for this purpose and they may not test enough. It would be also >good to have something for testing and comparing performance. > Well, the previous post test file just grew to make a simple check for various aspects, so it's not super clean. I just grepped for defs in the implementation and bulk appended "test_" to make an empty starting point. Then I just filled in tests after a preliminary sanity check test. But there are some things that could still accidentally be inherited from the base class when builtin utility functions are called on the dict object. Also there's a lot of cut-paste duplication an no full explorations of corner cases. There's neat generator-based test driving with different parameters that I didn't take advantage of, etc. etc. I should really read the py test docs and learn to use it better if I am going to use it. But anyway, it's a q&d hack to show and sanity-check different usages. The semantics of assigning slices to d.keys[i:j] and d.values[i:j] are kind of tricky when the size changes and/or key names match or don't match in various ways, or the incoming data represents collapsing redundant keys that are legal sequential assignment overrides but change the size, etc. One could add keyword args to the constructor to vary key eq and cmp used on keys to determine "key collisions" between e.g. tuple keys and also for sort. You could even allow partially non-hashable keys that way if you got tricky. But maybe this is getting too tricky ;-) I'll make some simple mods to the test to allow applying it to arbitrary candidate implementations with different names and directory locations, so I can try it on odict.py and other versions. But are the semantics right? Doctest is handy, and in some ways I like examples showing up in the help docs, but maybe help should take a keyword arg to select showing them (and some other things too perhaps. A brief version excluding a lot of inheritance for classes might be nice. Or a pattern for method and class var inclusion. But I like the separation of the py.test tests with no need to mod the original. Where next? This ordered dict thing is kind of a side-track from a side-track for me ;-) Regards, Bengt Richter From jim.eggleston at gmail.com Tue Nov 1 14:25:32 2005 From: jim.eggleston at gmail.com (jim.eggleston at gmail.com) Date: 1 Nov 2005 11:25:32 -0800 Subject: Automatically creating a HOME environ variable on Windows? In-Reply-To: <1130843258.600599.180750@g47g2000cwa.googlegroups.com> References: <1130549236.679806.297670@g43g2000cwa.googlegroups.com> <1130843258.600599.180750@g47g2000cwa.googlegroups.com> Message-ID: <1130873132.775072.303440@g44g2000cwa.googlegroups.com> Does Windows 98 have a %USERPROFILE% environment variable? From dave at dbmdata.com Sun Nov 6 09:47:04 2005 From: dave at dbmdata.com (David Mitchell) Date: Sun, 06 Nov 2005 09:47:04 -0500 Subject: Can't instantiate class In-Reply-To: References: <436E124B.7000003@dbmdata.com> Message-ID: <436E1768.90901@dbmdata.com> Thanks for your prompt reply. Ok, so If use your first suggestion (db = DataUtil.DataUtil() ), I get this error: AttributeError: 'module' object has no attribute 'DataUtil' If I try importing the class directly (from DataUtil import DataUtil), I get this error: ImportError: cannot import name DataUtil Could these errors have something to do with the fact that I am doing this through mod_python? Thanks again, Dave Michael P. Soulier wrote: > On 11/6/05, David Mitchell wrote: > >>import DataUtil >> >> File "C:\Apache2\htdocs\Intranet\addLink.py", line 42, in getCategories >> db = DataUtil() >> >>TypeError: 'module' object is not callable > > > You've imported module DataUtil, and by calling DataUtil(), you're > trying to call the module, hence the error. I think you want > > db = DataUtil.DataUtil() > > Or, > > from DataUtil import DataUtil > > And then your code will work. > > Mike > > -- > Michael P. Soulier > From cito at online.de Tue Nov 22 15:08:32 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 21:08:32 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <4383635b.479535916@news.oz.net> References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <438258f2.411334718@news.oz.net> <4383635b.479535916@news.oz.net> Message-ID: >>I still believe that the concept of an "ordered dictionary" ("behave >>like dict, only keep the order of the keys") is intuitive and doesn't >>give you so much scope for ambiguity. But probably I need to work on an >>implementation to become more clear about possible hidden subtleties. Bengt Richter schrieb: > Does that mean that the Larosa/Foord odict.py implementation in PyPI > does not do what you want? Basically, it is what I had in mind. But I'm now seeing some things that could be improved/supplemented, e.g. - performance improvements - the internal keys list should be hidden - list methods should be mixed in instead -- Christoph From waldbie at yahoo.com Sat Nov 26 16:14:39 2005 From: waldbie at yahoo.com (Carl Waldbieser) Date: Sat, 26 Nov 2005 16:14:39 -0500 Subject: FTP over TLS References: Message-ID: David Isaac wrote: > > "Carl Waldbieser" wrote in message > news:dm2sc0$4i2$1 at domitilla.aioe.org... >> Does anyone know of any good examples for writing client side code to > upload >> files over a secure FTP connection? > > http://trevp.net/tlslite/ > > Alan Isaac Thanks. I have actually looked at this library before. It looks like it might be able to do what I want, but my problem is that I don't really understand how the protocol itself works very well. I mean, from a high level view, I thing something like this happens: 1) FTP client contacts server, sends command requesting secure connection. 2) Server responds by sending some sort of public key 3) Client uses key to encrypt the rest of the communication. I don't really understand the nitty-gritty of what's going on, though. I can read the API for the library, but I am really lost as to how to use it. I didn't see any docs on the site that clarify how it's supposed to be used. Did I miss something? Is there somewhere else I should be looking? Thanks From wangminghua at gmail.com Wed Nov 16 08:40:17 2005 From: wangminghua at gmail.com (wangminghua at gmail.com) Date: 16 Nov 2005 05:40:17 -0800 Subject: Shutdown hook In-Reply-To: References: <1132094726.985460.97110@g14g2000cwa.googlegroups.com> Message-ID: <1132148417.488916.61840@g49g2000cwa.googlegroups.com> great. It's a good idea. From onurb at xiludom.gro Wed Nov 23 04:26:12 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 23 Nov 2005 10:26:12 +0100 Subject: What a curious assignment. In-Reply-To: <1132721032.455988.259600@o13g2000cwo.googlegroups.com> References: <1132721032.455988.259600@o13g2000cwo.googlegroups.com> Message-ID: <438435b5$0$21223$626a54ce@news.free.fr> Neil.Jin at gmail.com wrote: > [test 1] > >>>>class A: > > ... i = 1 > ... > >>>>a = A() >>>>A.i > > 1 > >>>>a.i > > 1 > >>>>A.i = 2 >>>>A.i > > 2 > >>>>a.i > > 2 > > > [test2] > >>>>class A: > > ... i = 1 > ... > >>>>a = A() >>>>A.i > > 1 > >>>>a.i > > 1 > >>>>a.i = 2 >>>>A.i > > 1 > >>>>a.i > > 2 > > > Is there somthing wrong???? No. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From keesvanschaik at gmail.com Thu Nov 24 20:18:53 2005 From: keesvanschaik at gmail.com (KvS) Date: 24 Nov 2005 17:18:53 -0800 Subject: sending all key events to wx.panel? Message-ID: <1132881533.749292.137160@g44g2000cwa.googlegroups.com> Hi all, I have a wxPython GUI consisting of a wxWindow -> wxPanel -> set of widgets. I need to catch pressed keys no matter which widget has focus, so I've attached an event handler to the panel but I can't seem to find a way to do some kind of collective "sending through" of the key event from all the widgets on the panel to that handler in case the panel doesn't have focus. Is there some way to do this? Thanks in advance! - Kees From PPNTWIMBXFFC at spammotel.com Thu Nov 17 11:11:04 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Thu, 17 Nov 2005 17:11:04 +0100 Subject: PyExcelerator - mishandling of formulas? References: <1132216046.704767.59200@g44g2000cwa.googlegroups.com> Message-ID: On Thu, 17 Nov 2005 09:27:26 +0100, Serge Orlov wrote: >> ws_summary.write(0,0, pyExcelerator.Formula('Data:A1')) >> ws_data.write(0, 0, '4000') > I think you're doing it wrong. ":" character means range, to refer to a > sheet use "!" charater: Data!A1 > Right you are. It "changed" somehow... anyhow, even if you change it, it will choke on the same line. I received an answer... a workaround which doesn't make me happy, but it is, as it is! [...] This is not a bug. This is by design. pyExcelerator does not unerstand such syntax. Try Formula("HYPERLINK(address; name)") [...] Which means: ws_summary.write(0,0, pyExcelerator.Formula('HYPERLINK("Data!A1")) does the trick, but the text shown is a hyperlink now! Thanks for your help, Regards, Marco From mwm at mired.org Wed Nov 16 15:32:47 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 16 Nov 2005 15:32:47 -0500 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <1131969669.048494.55680@o13g2000cwo.googlegroups.com> <867jbbrowx.fsf@bhuda.mired.org> <1132052791.374452.206310@g49g2000cwa.googlegroups.com> <86fypxr82g.fsf@bhuda.mired.org> <1132133826.129889.97630@g47g2000cwa.googlegroups.com> Message-ID: <86u0ecnxjk.fsf@bhuda.mired.org> "Ben Sizer" writes: > Mike Meyer wrote: >> "Ben Sizer" writes: >> > In my >> > case, providing a free download of any lost executables or data upon >> > presentation of a legitimate license key should be adequate. >> My special handling for such >> things - and *especially* for entertainment software, where the media >> gets handled by children - is "Return that POS." > That's funny, I could have sworn that a few messages above you > suggested I "Try Alex's solution, and put the data on a network server > that goes through whatever authentication you want it to." > Are you claiming therefore that it's more acceptable to you to have to > access the data remotely every time you use the software than once per > install? Alex's solution doesn't require special treatment for disaster recovery and/or planning, and as such is a valid answer to the question. It may be unacceptable for *other* reasons, but it beats dictating a disaster recovery plan for your software to the end user hands down on that basis. >> Worse yet, you play >> semantic games so you can claim not to be violating fair use rights in >> the process. > No, I am just pointing out that you are mixing up the concept of an > actual 'right' such as one embodied in a state's constitution, with an > implied 'right' that is just an exemption from committing an offence. > The term 'right' does not even appear in the relevant part of US > copyright law, except to state that it is a limitation on the copyright > holder's rights. You're still just playing semantic games. The common usage is "fair use rights." If you mean "... without infringing on the end users rights, except for fair use rights", then you should say that. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From sybrenUSE at YOURthirdtower.com.imagination Mon Nov 28 04:02:19 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 28 Nov 2005 10:02:19 +0100 Subject: return in loop for ? References: <4384F705.31CEC951@valid.org> <86acfu3ony.fsf@bhuda.mired.org> <43850362.95E1D6A1@valid.org> <86wtiy28z5.fsf@bhuda.mired.org> <1132812397.369787.214140@g47g2000cwa.googlegroups.com> <5kghf.2723$ea6.2055@news-server.bigpond.net.au> Message-ID: Duncan Booth enlightened us with: > I would have thought that no matter how elaborate the checking it is > guaranteed there exist programs which are correct but your verifier > cannot prove that they are. Yep, that's correct. I thought the argument was similar to the proof that no program (read: Turing machine) can determine whether a program will terminate or not. 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 baudelaire_2c at yahoo.fr Fri Nov 4 11:40:05 2005 From: baudelaire_2c at yahoo.fr (N. Pourcelot) Date: Fri, 04 Nov 2005 17:40:05 +0100 Subject: exec behaviour Message-ID: <436b8ed9$0$7577$626a54ce@news.free.fr> Hello, I can't understand some specific behaviour of the exec statment. For example, say that I create such a class A : class A: def __init__(self): self.n = 3 self.m = None def h(self, ini): n = self.n m = self.m if ini: exec("def m(x): return n+x"); self.m=m else: m(7) Now : obj = A() obj.h(1) obj.h(0) I get : Traceback (most recent call last): File "", line 1, in ? File "", line 9, in h File "", line 1, in m NameError: global name 'n' is not defined Now, suppose I would like to make exactly the same without exec : class A: def __init__(self): self.n = 3 self.m = None def h(self, ini): n = self.n m = self.m if ini: def m(x): return n+x self.m=m else: return m(7) je lance : obj = A() obj.h(1) obj.h(0) This time, it works fine !!! If I knew why the first doesn't work, and the second does, it would be a great help for me for my program... Thank you very much ! From steve at holdenweb.com Tue Nov 1 12:55:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Nov 2005 17:55:40 +0000 Subject: python.org offline In-Reply-To: References: <1130862100.694549.276860@f14g2000cwb.googlegroups.com> Message-ID: Sybren Stuvel wrote: > dcrespo enlightened us with: > >>"The server is temporarily unable to service your request due to >>maintenance downtime or capacity problems." > > > Yes, I can read. My question is: does anyone know why this happens so > often lately? > Possibly real maintenance occasioned by a recent move to a new server, in preparation for the new-look web site. 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 steve at holdenweb.com Thu Nov 24 01:21:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Nov 2005 06:21:56 +0000 Subject: Python as Guido Intended In-Reply-To: <1132800973.008501.34090@g14g2000cwa.googlegroups.com> References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> <86k6ey25y2.fsf@bhuda.mired.org> <1132798362.260195.175680@f14g2000cwb.googlegroups.com> <86fypm22kv.fsf@bhuda.mired.org> <1132800973.008501.34090@g14g2000cwa.googlegroups.com> Message-ID: bonono at gmail.com wrote: > Mike Meyer wrote: [...] > >>By the results of the vote, most people wanted ternary. The use >>cases for it are well know. From what I recall, the debate was over >>which of the many proposals should be adopted. > > That is not the impression I get on here. The impression I get lately > is "ternary" is bad, is hard to read, can always be done "better" with > if then else statement. > Well I personally believe the main reason Guido resisted the introduction of the ternary operator for so long is precisely because he knows it will be "abused" (by which I mean "used when its use will make a program's meaning less clear") to the detriment of program readability. Python's unusual virtue is its ability to make a programmer's intent clear from a reading of the code, and Guido tends to be fiercely protective of that characteristic. You should also bear in mind that many (though admittedly not all) suggestions for change are ill-thought-out at best and lamebrained at worst. One recent example (though I won't accord it a specific position on the scale) was the suggestion that user-defined operators could be introduced using a "]+[" syntax. The fact that this made y = [1,2,3]+[4,5,6] syntactically ambiguous had not been considered by the proposer. I agree that sometimes those who shoot such proposals down in flames might be more considerate of the feelings of the proposers, but life is short and we are all imperfect. The fact that naive expressions of opinion about such matters are traditionally accorded respect and answered politely is one of the reasons why so many people find this list a helpful place to discuss Python. 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 gsakkis at rutgers.edu Mon Nov 7 14:26:31 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 7 Nov 2005 11:26:31 -0800 Subject: A Tcl/Tk programmer learns Python--any advice? References: Message-ID: <1131391591.426798.175920@z14g2000cwz.googlegroups.com> "Kevin Walzer" wrote: > I've gotten all the approropriate resources for learning Python (docs, > books, tutorials), so my question is this: are there any "gotchas" that > Tcl programmers often encounter in learning Python? I'm thinking > specifically about habits that may require "unlearning," for instance, > such as grokking object orientation (Tcl procedures are now embedded > deep in my brain). I don't know Tcl, but python doesn't force you to be OO; you can write 100% procedural code if you want to. OTOH, you'll probably need other people's code that is OO, so at the very least you'll have to be able to read and use it. Fortunately, using an existing OO module/library is much easier than designing and writing it, so you can get away with it with little effort. George From mwm at mired.org Thu Nov 24 21:36:24 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 24 Nov 2005 21:36:24 -0500 Subject: Making immutable instances References: <861x163nl3.fsf@bhuda.mired.org> <868xvezb2k.fsf@bhuda.mired.org> <86y83dvacs.fsf@bhuda.mired.org> Message-ID: <86psopv4gn.fsf@bhuda.mired.org> "Giovanni Bajo" writes: > Mike Meyer wrote: >> And I have no problems with that. If you believe your class should >> throw an error if someone calls an instances pop() method when it's >> empty, do so. >> Likewise, if you want to make it so a client can't change your >> attributes, feel free to do so. >> However, when you prevent a client from adding an attribute, you're >> not merely making your objects immutable, you're making them >> static. Python isn't a static language, it's a dynamic language. I >> consider parts of it that are static to be warts. > I always thought that adding an attribute was just as bad as changing the > attributes, for an immutable object. But I now see your point (eventually!), > they are pretty different issues. > > But, whatever attribute you add to the instance, it should *also* be immutable > (so that, in other words, wouldn't be so different than carrying around a tuple > with the original instance and the added attribute). This said, I think I > devise that a language support for enforcing immutability could allow adding > attributes to instance -- as long as those attributes then become immutable as > well. That's cool, but only because immutability is such a slippery concept in Python. We both agree that tuplee are immutable, right? So consider this: >>> x = f() >>> type(x) >>> id(x) 136810980 >>> y = copy.deepcopy(x) >>> y is x False >>> y == x True >>> f2(x) >>> id(x) 136810980 >>> y == x False >>> So I'm perfectly willing to let your class declare that my attributes be immutable, just so long as you mean the same thing by that as you mean when you refer to tuples as immutable. >>>> I'm not sure it's more important than >>>> things like interned strings and the sharing of small integers. >>>> Most >>>> of the discussion of immutables here seems to be caused by newcomers >>>> wanting to copy an idiom from another language which doesn't have >>>> immutable variables. Their real problem is usually with binding, not >>>> immutability. >>> I'm not such a newcomer, but (how funny) Python is *the* language >>> that introduced me to the concept of immutable objects and their >>> importance in design :) >> Well, that would explain why you think it's so important - it's where >> you first encountered it. > Yes. But I'm familiar with different object semantics, and I found the > immutable objects to be a pretty good replacement of value semantics, and to > implement a kind-of pass-by-value convention in a language which only has > references. Like I said, I don't have a problem with immutable objects per se. It's taking away my ability to extend the objects in all the ways that Python allows that bothers me. Personally, I haven't found much use for immutable *objects*, as for immutable *attributes*. Python allows the latter. In Python, you create an immutable object by creating an object with no mutable attributes. >> I'd argue that it's no more important than >> identity - which is what I was searching for when I talked about >> interned strings sharing small integers. There are builtin types that >> preserve identity for equal instances, at least under some >> conditions. There are no constructs for helping you do that with >> user-defined objects. Should we add them for the sake of >> orthogonality? I don't think so - not without a good use case. > > I don't think identity is important for immutable objects (as I wrote > elsewhere), so I don't think adding language constucts for this would prove > useful. Instead, immutable objects *are* common, and we still miss a way to > mark them as such. I think identity is important from an implementation point of view. Implementation is important - so having constructs that let you deal with this is useful. Python has those constructs. What Python doesn't have in general is the ability to "mark" objects. You have the ability to create attributes that are immutable. You can create immutable objects by creating objects which have no mutable attributes. What more do you need? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From apardon at forel.vub.ac.be Tue Nov 29 03:27:43 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Nov 2005 08:27:43 GMT Subject: General question about Python design goals References: Message-ID: On 2005-11-28, Duncan Booth wrote: > Antoon Pardon wrote: > >> >> No I gave an example, you would implement differently. But even >> if you think my example is bad, that would make it a bad argument >> for tuples having list methods. That is not the same as being >> a good argument against tuples having list methods. > > Tuples don't have list methods, therefore any code which seems to require a > tuple with list methods should make you stop and consider whether your > design is wrong. IMO that is a non-sequitur, because that makes what is good or bad design dependand on the language used. If I have a design that seems to require tuples with a count method, then wether that is a good or bad design doesn't depend on whether or not python allows that or not. -- Antoon Pardon From mardy at users.sourceforge.net Thu Nov 24 11:46:14 2005 From: mardy at users.sourceforge.net (Mardy) Date: Thu, 24 Nov 2005 16:46:14 GMT Subject: Help me to catch this exception :-) References: <1132844966.571253.186270@g49g2000cwa.googlegroups.com> Message-ID: Le die Thu, 24 Nov 2005 07:09:26 -0800, Fuzzyman ha scribite: > I don't know the answer, but I like the problem. :-) > > What happens with the standard CGIHttpServer ? The standard CGIHttpServer uses fork() on Unix and popen() on Windows; since both these functions run the module in a separate process, the problem doesn't show up. But on Mac, it uses execfile(), so I guess the problem is the same. For the moment, I've come up with a hybrid solution: in CGIHTTPServer, doing "import cgitb; cgitb.enable()" before the try block which calls execfile(), and add an empty except clause which prints the exception: except: cgitb.handler() There's still something not working perfectly, but I think this is close to the solution. -- Saluti, Mardy http://interlingua.altervista.org From dyoo at hkn.eecs.berkeley.edu Mon Nov 14 19:20:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Nov 2005 16:20:13 -0800 (PST) Subject: [Tutor] how to convert between type string and token In-Reply-To: <20051114230923.42243.qmail@web30505.mail.mud.yahoo.com> Message-ID: On Mon, 14 Nov 2005, enas khalil wrote: > hello all [program cut] Hi Enas, You may want to try talking with NTLK folks about this, as what you're dealing with is a specialized subject. Also, have you gone through the tokenization tutorial in: http://nltk.sourceforge.net/tutorial/tokenization/nochunks.html#AEN276 and have you tried to compare your program to the ones in the tutorial's examples? Let's look at the error message. > File "F:\MSC first Chapters\unigramgtag1.py", line 14, in -toplevel- > for tok in train_tokens: mytagger.train(tok) > File "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py", line 324, in train > assert chktype(1, tagged_token, Token) > File "C:\Python24\Lib\site-packages\nltk\chktype.py", line 316, in chktype > raise TypeError(errstr) > TypeError: > Argument 1 to train() must have type: Token > (got a str) This error message implies that each element in your train_tokens list is a string and not a token. The 'train_tokens' variable gets its values in the block of code: ########################################### train_tokens = [] xx=Token(TEXT=open('fataha2.txt').read()) WhitespaceTokenizer().tokenize(xx) for l in xx: train_tokens.append(l) ########################################### Ok. I see something suspicious here. The for loop: ###### for l in xx: train_tokens.append(l) ###### assumes that we get tokens from the 'xx' token. Is this true? Are you sure you don't have to specifically say: ###### for l in xx['SUBTOKENS']: ... ###### The example in the tutorial explicitely does something like this to iterate across the subtokens of a token. But what you're doing instead is to iterate across all the property names of a token, which is almost certainly not what you want. From pythonnew at gmail.com Mon Nov 14 05:29:34 2005 From: pythonnew at gmail.com (Ben Bush) Date: Mon, 14 Nov 2005 02:29:34 -0800 Subject: circle and point In-Reply-To: References: <8c11e4350511122051hc4ae8b9tc4ef54818ba44318@mail.gmail.com> Message-ID: <8c11e4350511140229u51dcb5fdg76aab41411cc97aa@mail.gmail.com> is there any python code doing this: there are two line segments (2x+y-1=0 with the coordinates of two ending points are (1,-1) and (-1,3); x+y+6=0 with the coordinates of two ending points are (-3,-3) and (-4,-2);). They extend and when they meet each other, stop extending. how can i use python to implement this in Tkinter? -- Thanks! Ben Bush -------------- next part -------------- An HTML attachment was scrubbed... URL: From grahn+nntp at snipabacken.dyndns.org Wed Nov 16 14:38:06 2005 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 16 Nov 2005 19:38:06 GMT Subject: Python, Linux, Desktop Environment References: <1132159865.965080.150530@z14g2000cwz.googlegroups.com> <437b80f4$0$625$626a14ce@news.free.fr> Message-ID: On Wed, 16 Nov 2005 19:56:51 +0100, bruno at modulix wrote: > jeremyvoros at gmail.com wrote: >> So, I've written my first GUI app in python. I've turned it into a >> binary .exe and .app that runs on Windows and Mac respectively, but on >> my Linux box, where I wrote the thing, I still have to drop to the >> command line and ./myscript.py. What can I do to make it a "click and >> run" sort of application in KDE or Gnome on Linux? > > There are *no* "click and run" on linux, since the GUI is an option, > not a part of the OS. > > What you're looking for is WM/DesktopManager specific. You'll find the > answers in the Gnome and KDE manuals. Yeah, and please don't accidentally remove the option to type 'myscript.py' on the command line -- that's how I almost always start GUI programs. If I like them enough, I edit my window manager's config so that it appears in a suitable place in the menus. Nine applications have made that list during the past fifteen years ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From cs at totallybogus.com.invalid Wed Nov 16 17:47:53 2005 From: cs at totallybogus.com.invalid (Cousin Stanley) Date: Wed, 16 Nov 2005 16:47:53 -0600 Subject: python-mysqldb__debian_to_freebsd Message-ID: <1132181273_661@spool6-east.superfeed.net> Greetings .... I'm using a commercial web host running FreeBSD that fortunately has Python and MySQL, but no python-mysqldb module .... Before begging the host to install it I thought I would try the Debian version that I have on the outside chance that it might fly directly under FreeBSD on the server .... import MySQLdb .... leads to the ImportError message .... Shared object "libpthread.so.0" not found, required by "_mysql.so" On my local Debian installation the reference to that particular library file is actually a symbolic link .... libpthread.so.0 -> libpthread-0.10.so I copied libpthread-0.10.so over to the server in a directory that is in the Python search path and renamed it to libpthread.so.0 .... I tried to make the symbolic link as above from Python since I don't have a shell account, but it failed for some reason that I don't recall at the moment .... After a bit of google-izing and a quick scan of the MySQL install docs, I also set the LD_LIBRARY_PATH enviroment variable to point to the dir where the supposed missing file lives .... Is there any at all chance that this will work with the proper configs or should I go ahead and beg the host for an installation ? Any clues would be greatly appreciated .... -- 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 cnxt200 at yahoo.com Tue Nov 29 16:10:46 2005 From: cnxt200 at yahoo.com (YongYong Li) Date: Tue, 29 Nov 2005 13:10:46 -0800 (PST) Subject: problem with Message-ID: <20051129211046.27764.qmail@web32111.mail.mud.yahoo.com> Recently I got problem on final distributed software in python. In my program, I have C code which import module in python. But when I install my software on another computer which is not installed whole python23 but part of it, I have problem in running the program. The module is simple as I import os import win32com.client import win32api import pythoncom def f1(): ..... def f2(): ... I used another main() if __name__=="__main__": print "test" to use py2exe and get all DLL as well as related library. I moved them to a dir and run the C program on another computer, it does not work at all. It works on the development computer where python23 installed. 1. What extral lib or interpretor or environment I need to have in order to run it on another computer? If it is pure python code, it works. But when C code call function inside python modue, it does not find them. Sure I Py_Initialize() them. 2. does py2exe get all neceaasry dll, libs for this type of execution? Does anyone has experience with this type of problems? Thanks in advance. __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From bonono at gmail.com Thu Nov 17 21:45:51 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 17 Nov 2005 18:45:51 -0800 Subject: Zope vs Php In-Reply-To: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> Message-ID: <1132281951.154913.13960@z14g2000cwz.googlegroups.com> I believe Cheetah can do this kind of thing, Kid too. Personally, I like Kid more. And you can take a look at TurboGears which is a bag of tools (web server - cherrypy, template - Kid, ORM - SQLObject) glued together in a pretty nice way. Steve wrote: > We are building a web app and the our backend is currently using python > with php front end. We would like to do everything in python but php > for our front end is so easy to use. We would like to use zope on our > front end(no experience with it) can anyone provide any experience with > this? > > >From what I can tell you can't just do > <% > #python code > %> > some title > > this is what we would like to do with session support and things that > php provides? > > > Steve From franck.perez at gmail.com Thu Nov 17 19:45:18 2005 From: franck.perez at gmail.com (Franck PEREZ) Date: Fri, 18 Nov 2005 01:45:18 +0100 Subject: Importing a class without knowing the module In-Reply-To: <867jb6n7cw.fsf@bhuda.mired.org> References: <867jb6n7cw.fsf@bhuda.mired.org> Message-ID: I thought about it, but it would make the XML file depend on the machine... no more portability... On 11/18/05, Mike Meyer wrote: > Franck PEREZ writes: > > ########### My test application ############ > > class Foo(object): > > #The class I'd like to serialize > > pass > > > > import myMarshaller > > foo = Foo() > > s = myMarshaller.dumps(foo) #works fine, spits something like > class = "Foo"...> > > another_foo = loads(s) #fails, see below > > > > ########### My marshaller (in its own module) ############ > > def loads(s): > > #First, get class name (here "Foo") > > klass = eval(className) #fails because "Foo" is not in the > > marshaller's namespace ! > > > > How could I tell the marshaller to locate the Foo class and any other > > class I try to deserialize ? > > How about adding Foo.__file__ to the serialized data? > > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. > -- > http://mail.python.org/mailman/listinfo/python-list > From aleax at mail.comcast.net Wed Nov 23 22:11:53 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Wed, 23 Nov 2005 19:11:53 -0800 Subject: Making immutable instances References: Message-ID: <1h6huee.f74jx2krwvj2N%aleax@mail.comcast.net> Ben Finney wrote: > How can a (user-defined) class ensure that its instances are > immutable, like an int or a tuple, without inheriting from those > types? You can make a good start by defining __setattr__, __delattr__ (and __setitem__ and __delitem__ if your class is a container) to raise exceptions. Of course, these restrictions can be easily worked around by a sufficiently determined attacker... but if you have to think of the user of your code as an attacker, you've got worse problems than this trifling one. Do not define any of the in-place operator special methods, such as __iadd__ and friends (or, if you're inheriting from a class that does define them, override them to raise exceptions). > What caveats should be observed in making immutable instances? Remember that your redefined __setattr__ IS "in place" even when you're initializing your istance, so remember to delegate attribute setting to the superclass (the other special methods mentioned above are less likely to byte you). You will probably want to define __hash__ and __eq__ if you're going to the trouble of making instances immutable. Alex From steve at holdenweb.com Wed Nov 2 10:46:14 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Nov 2005 15:46:14 +0000 Subject: python CGI,sybase and environ variables In-Reply-To: <1130896485.220506.103570@g43g2000cwa.googlegroups.com> References: <1130896485.220506.103570@g43g2000cwa.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > hi > i am writing a CGI to process some database transactions using the > Sybase module. > so in my CGI script, i have: > > ... > import Sybase > import cgitb; cgitb.enable(display=1 , logdir="/tmp/weblog.txt") > ... > ... > > the problem is , everytime i have ImportError: No module named Sybase > flagged out. > > at first i think it's library path misconfiguration, so i put > os.environ["SYBASE"] = '/path/to/sybase' > os.environ["LD_LIBRARY_PATH"] = '/path/to/sybase/lib' > > before i import Sybase. but its still the same error > > Ok.so now, is it necesary to configure the web server's "nobody" user's > profile to point to the Sybase libraries? or worse, configure root's > profile to point to Sybase libraries? what's could be wrong? > thanks for any help rendered. > You should try adding "/path/to/sybase" to sys.path as well as/rather than putting it in an environment variable. sys.path is what the interpreter uses to find importable modules. 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 bonono at gmail.com Thu Nov 17 23:22:17 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 17 Nov 2005 20:22:17 -0800 Subject: Zope vs Php In-Reply-To: <878xvm39mt.fsf@jupiter.g2ctech> References: <1132262483.602298.263680@g49g2000cwa.googlegroups.com> <437d0b7a$0$7585$636a15ce@news.free.fr> <1132270188.226770.309980@g14g2000cwa.googlegroups.com> <86br0in877.fsf@bhuda.mired.org> <87hdaa3brc.fsf@jupiter.g2ctech> <86oe4iljz4.fsf@bhuda.mired.org> <878xvm39mt.fsf@jupiter.g2ctech> Message-ID: <1132287737.339479.205630@f14g2000cwb.googlegroups.com> Jorge Godoy wrote: > Kid is for XML output. It won't work with non-HTML output... > I believe someone patches it to output plain text, thus it is possible to do "makefile" like things. I don't have such a need so don't know the detail. It can output XML as well as HTML which I believe you already know. From cfbolz at gmx.de Sun Nov 27 18:07:04 2005 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Mon, 28 Nov 2005 00:07:04 +0100 Subject: Profiling with hotshot and wall clock time In-Reply-To: <4386237F.2090103@boskant.nl> References: <4386237F.2090103@boskant.nl> Message-ID: Hi! Geert Jansen wrote: > I'm trying to profile an application that I believe is blocking on I/O > for a significant amount of time. In trying to dig down where this > happens, I profiled the application with hotshot. The results are not > really usable however as it seems to display the amount of CPU time > which for my application is much lower than the total run time. > > Is possible to use hotshot with wall clock time, i.e. is it possible to > have the code fragment below show one second as opposed to zero? The old > profiler seems to have functionality choosing a timer function but it > crashed on my code. There is a nice profiling module that PyPy has used profitably recently: it is called lsprof and can be found at (svn repository): http://codespeak.net/svn/user/arigo/hack/misc/lsprof/ It was written by Brett Rosen and Ted Czotter, with further changes from Michael Hudson and Armin Rigo. I did not really check what timer function it uses, although it seems to provide more exact results than hotshot while maintaining the speed of same. It seems to handle your example just fine: >>> import lsprof >>> import time >>> def f(): ... time.sleep(1) ... >>> lsprof.profile(f).pprint() CallCount Recursive Total(ms) Inline(ms) module:lineno(function) 1 0 999.0380 999.0380 <>:1(f) (profiling time.sleep directly does not work, but I guess that this is also not so useful). Cheers, Carl Friedrich Bolz From enleverlesO.OmcO at OmclaveauO.com Mon Nov 21 15:50:44 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Mon, 21 Nov 2005 21:50:44 +0100 Subject: Reading a subprocesses stdout on Windows References: <1132603718.835058.146620@z14g2000cwz.googlegroups.com> Message-ID: <438239a2$1$11127$626a14ce@news.free.fr> Hi! Let down subprocess, and remember popen4. Here, an example (with CMD, under w-XP) : import os def lcmd(lst=None): a = os.popen4(lst[0]) for i in lst[1:]: if i!='': a[0].write(i+'\r\n') a[0].flush() return a[1].readlines() l=[ 'CMD /K', 'DIR *.c /B', 'DATE /T', 'TIME /T', 'EXIT' ] lret = lcmd(l) for n in lret: print n[:-1] Attention : don't read data inside the loop (for)... @-salutations Michel Claveau From piet at cs.uu.nl Sun Nov 27 17:14:13 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 27 Nov 2005 23:14:13 +0100 Subject: How to enable bash mode at the interative mode? References: Message-ID: >>>>> Anthony Liu (AL) escribi?: >AL> That is, at the Python interactive mode, if I hit the >AL> upper arrow key, it'll bring up the last line of code. >AL> At >AL> http://groups.google.com/group/comp.lang.python/browse_thread/thread/fb8c2fd9eed0d/736fac8c33e84d0c?lnk=st&q=python+%22upper+arrow%22&rnum=2&hl=en#736fac8c33e84d0c >AL> , it seems that Michael Spalinski suggests of >AL> reinstalling Python. >AL> Any easier way to achieve this feature? Just installing the readline module was sufficient in MacOSX (Apple's python). Maybe it is the same for other implementations? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From igouy at yahoo.com Tue Nov 29 17:08:12 2005 From: igouy at yahoo.com (igouy at yahoo.com) Date: 29 Nov 2005 14:08:12 -0800 Subject: Computer Language Shootout In-Reply-To: <1133299669.010298.283100@g14g2000cwa.googlegroups.com> References: <1133298307.938958.186070@f14g2000cwb.googlegroups.com> <1133299669.010298.283100@g14g2000cwa.googlegroups.com> Message-ID: <1133302092.368063.235410@o13g2000cwo.googlegroups.com> We don't scrape programs from news-groups, if you'd like the program to be shown on the shootout then please attach the source code to a tracker item. Please follow the FAQ instructions http://shootout.alioth.debian.org/faq.php#contribute bearophileHUGS at lycos.com wrote: > This is a direct translation of the D code, maybe it's not the faster > Python implementation, and surely it's not the shorter one. But Psyco > makes it much faster (Psyco likes "low level" style code). > ShedSkink is (almost) able to compile it too, producing a really fast > executable (with some "smart attentions" this SS version becomes only > 17% slower than the D version for a given n=11 (26.66 sec instead of > 22.70 sec of total running time on a PIII 500 MHz)). > > > ! import sys > ! > ! def fannkuch(n): > ! perm = [0] * n > ! perm1 = range(n) > ! count = [0] * n > ! m = n - 1 > ! r = n > ! maxFlipsCount = 0 > ! > ! while True: > ! while r != 1: > ! count[r-1] = r > ! r -= 1 > ! > ! # SS v.0.0.5 has a problem with this line: > ! if not (perm1[0]==0 or perm1[m]==m): > ! #perm = list(perm1) > ! # to not produce memory garbage > ! for i in xrange(n): > ! perm[i] = perm1[i] > ! > ! i = perm[0] > ! flips = 0 > ! while i: > ! temp = perm[i] > ! perm[i] = i > ! i = temp > ! j = 1 > ! k = i - 1 > ! while j < k: > ! temp = perm[j] > ! perm[j] = perm[k] > ! perm[k] = temp > ! j += 1 > ! k -= 1 > ! flips += 1 > ! > ! if flips > maxFlipsCount: > ! maxFlipsCount = flips > ! > ! while True: > ! if r == n: > ! return maxFlipsCount > ! temp = perm1[0] > ! i = 0 > ! while i < r: > ! j = i + 1 > ! perm1[i] = perm1[j] > ! i = j > ! perm1[r] = temp > ! > ! count[r] -= 1 > ! if count[r] > 0: > ! break > ! r += 1 > ! > ! > ! #import psyco > ! #psyco.bind(fannkuch) > ! > ! if len(sys.argv) > 1: > ! n = int(sys.argv[1]) > ! else: > ! n = 1 > ! print "Pfannkuchen(%d) = %ld" % (n, fannkuch(n)) > > > Bye, > bearophile From o0O0o at o0O0o.invalid Wed Nov 9 00:17:32 2005 From: o0O0o at o0O0o.invalid (o0O0o) Date: Tue, 08 Nov 2005 19:17:32 -1000 Subject: Hawaii Python Users Group? Message-ID: <11n31jasi3p8d5e@corp.supernews.com> Are there any users groups or other resources for Python near Honolulu? I just started learning Python recently and would like to meet other people who use Python. (Python, Zope, Plone, etc.) From lycka at carmen.se Mon Nov 14 11:41:58 2005 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 14 Nov 2005 17:41:58 +0100 Subject: Python Book In-Reply-To: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> References: <43779016$0$2111$edfadb0f@dtext02.news.tele.dk> Message-ID: David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? I think most of the best books have been mentioned, but I thought that I'd add some comments. After all, different people have different ways of learning, and like different book styles. Both Martelli's "Python in a Nutshell" and Beazley's "Python Essential Reference" are mainly reference books. In a way, the standard library manual contains the same information, but Martelli's and Beazley's books explain things much better, and at least Martelli goes into a number of things outside the standard library. They have brief Python tutorials, but don't go into things like writing any larger programs involving things from several libraries etc. They are excellent if you want a high information density. The Python Cookbook mainly contains stuff from the Python Cookbook web site, but it's carefully selected, well edited (although a redundant line of code in my recipe remains) and in each chapter there is an initial discussion which is interesting. It's a great source of good Python code examples with explanations. If you prefer books that are more in Tutorial style, you might want to look at Dive Into Python (try it out in the web version first) or Magnus Hetland's new book (which is basically an update of his previous book with a different title.) I think the Python 2.1 Bible was good too, but it's a bit old by now. Then there are a lot of other books that are more narrow in scope, like Holden's Web Programming book, Ascher & Robinson's Windows book etc, but most of them are a few years old, and things change rapidly when it comes to libraries and tools in various niches. Many of these books are still very good and useful, but it takes some familarity with the Python world to know what to use in these books, and what to find more current information for. I hope you'll have a great time with Python! From mwm at mired.org Wed Nov 23 20:24:53 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 23 Nov 2005 20:24:53 -0500 Subject: Python as Guido Intended References: <43830213$0$84151$892e7fe2@authen.yellow.readfreenews.net> <1132678387.884058.107900@z14g2000cwz.googlegroups.com> <1132701667.183254.166910@g47g2000cwa.googlegroups.com> <86y83g1bww.fsf@bhuda.mired.org> <1132704024.711460.194310@f14g2000cwb.googlegroups.com> <1132768993.161352.260810@g49g2000cwa.googlegroups.com> <1132791525.595643.4710@g49g2000cwa.googlegroups.com> Message-ID: <86k6ey25y2.fsf@bhuda.mired.org> rurpy at yahoo.com writes: > Different programming styles are appropriate for different > tasks, different times and different places, different people. > And like morality, government, or economics, I do not believe > that one style of programming fits all situations. If I read you right, what you're saying is that hammmers aren't good at driving screws. I don't think anyone would argue about that. > But I do not think (and reading c.l.p convinces me) that GvR and > Python's developers know a coding style that works best in all > situations. I don't think that GvR believes he knows such a coding style, either. I certainly don't believe it. > I do think that the Python development community believes they do, > or more accurately, that if someone wants to use a different style, > they can go use something else. In other words, they believe that you should use a screwdriver to drive screws, and not a hammer. You apparently disagree with them. > I think that it is possible to include in Python, things that are > non-Pythonic (such as a return value from sort()) that allow users > more stylistic freedom, without degrading the ability of those who > don't want to use such features, to write in a pure Pythonic manner. So you think we can turn a hammer into a screwdriver without degrading the ability to use the hammer to drive nails. The problem is, doing this means you have a bigger, heavier hammer - which almost certainly degrades the ability to use it as a hammer. Adding features makes the language processor bigger. With Pythons strong commitment to backwards compatibility, these are hard to get rid of. Further, while those of us who like the Pythonic style may not have to use them, that won't prevent us from having to maintain code that uses them. Now, I'm not against changing the language per se. But most language changes have deeper implications than are obvious at first glance. Even when they don't, I'd prefer that you get cases that make for significantly cleaner code without having major negative connotations. The first is why people ask for "use cases": they want to see a real-world example where the proposed change would make things cleaner or more readable, or otherwise better in some way. At the same time, the new feature should provide an abuse that's hard to read, or lead to code that is easily misinterpreted. > This has the benefit of attracting more people to Python. And why is this a benefit? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bonono at gmail.com Thu Nov 24 03:26:36 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 00:26:36 -0800 Subject: wxPython Licence vs GPL In-Reply-To: <86hda2zcli.fsf@bhuda.mired.org> References: <1132817527.714232.319910@g14g2000cwa.googlegroups.com> <86hda2zcli.fsf@bhuda.mired.org> Message-ID: <1132820796.119386.309160@o13g2000cwo.googlegroups.com> Mike Meyer wrote: > "bonono at gmail.com" writes: > > Steve Holden wrote: > >> Whether or not some fragments of code remain unchanged at the end of > >> your project, if you start out with a piece of source code lifted from > >> wxPython then what you have created is definitely a "derivative work" > >> and, as such, you must take into account the wxPython license in your > >> licensing of the derivative work. > > Is that true ? What if I remove/replace the copyright doubtful portion > > with another implementation ? I believe this happens all the time in > > commerical software sue too. > > In general, if you can show you removed all the licensed code that was > in your code, and replaced it with software from another source, > you're cool. That's how the BSD distributions came about - Berkeley's > Computer Systems Research Group rewrote pretty much all of Unix. > > However, you're still liable to be sued. CSRG was, which is part of > why BSD languished while Linux was taking off. It's also why the > previous paragraph is a gross oversimplification. The court case > didn't establish a real precedent, as it turned out AT&T was > distributing code that belonged to CSRG in violation of the BSD > license. So they reached a settlement in which CSRG was allowed to > distribute a tape that had most of a Unix sytem on it, a few key files > that AT&T claimed as their own being withheld. This is the "BSD Lite" > distribution that the *BSD systems and parts of OS X are based on. All > this backstory made the SCO barratry much more entertaining. > Thanks, I was just trying to clarify it. As my initially understanding of Steve's post is that your work would be perpetual derivative work which doesn't sound too convincing for me. As for the liability, that is for sure, withness what is happening for the linux kernel. From james at colannino.org Tue Nov 8 18:16:35 2005 From: james at colannino.org (James Colannino) Date: Tue, 08 Nov 2005 15:16:35 -0800 Subject: Regular Expressions and Dividing Strings In-Reply-To: <200511090005.48137.email@christoph-haas.de> References: <43712DD7.6090603@colannino.org> <200511090005.48137.email@christoph-haas.de> Message-ID: <437131D3.8040104@colannino.org> Christoph Haas wrote: >You probably mean: > >a="root:root" >b,c = a.split(":") > >b and c contain both sides of the colon. > > Thanks. That's exactly what I was looking for. james -- My blog: http://www.crazydrclaw.com/ My homepage: http://james.colannino.org/ "A well regulated militia being necessary to the security of a free state, THE RIGHT of the people to keep and bear arms SHALL NOT BE INFRINGED." --United States Constitution, Second Ammendment From fredrik at pythonware.com Wed Nov 23 11:27:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 17:27:57 +0100 Subject: the PHP ternary operator equivalent on Python References: <1132339984.180573.303920@z14g2000cwz.googlegroups.com><1132341437.448693.248670@f14g2000cwb.googlegroups.com> <1132756197.635519.114180@g47g2000cwa.googlegroups.com> Message-ID: Daniel Crespo wrote: > Let me tell you something: I'm not a one-liner coder, but sometimes It > is necesary. > For example: > I need to translate data from a DataField to Another. > > def Evaluate(condition,truepart,falsepart): > if condition: > return truepart > else: > return falsepart > > dOldDataFields = {} > dNewDataFields = {} > > dNewDataFields = { > 'CODE': dOldDataFields['CODEDATA'], > 'DATE': dOldDataFields['DATE'], > 'CONTACT': Evaluate(dOldDataFields['CONTACTTYPE']==2, > dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT']) > } > > With this, I created a new dic very easy, saving in > dNewDataFields['CONTACT'] the value of dOldDataFields['FIRSTCONTACT'] > or the value of dOldDataFields['SECONDCONTACT'] depending on > dOldDataFields['CONTACTTYPE']. How you do this in a practic way without > the use of one-line code? It is needed! You can't avoid it! if you use less verbose names, you can do the same thing in less than half the number of characters, without a single oneliner: def convert(old): new = dict( CODE=old['CODEDATA'], DATE=old['DATE'] ) if old['CONTACTTYPE'] == 2: new['CONTACT'] = old['FIRSTCONTACT'] else: new['CONTACT'] = old['SECONDCONTACT'] return new From tdelaney at avaya.com Sun Nov 27 17:58:25 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 28 Nov 2005 09:58:25 +1100 Subject: Python as Guido Intended Message-ID: <2773CAC687FD5F4689F526998C7E4E5F4DB814@au3010avexu1.global.avaya.com> Bryan wrote: > i agree with you... pyrex should be part of the python distribution :) And this has been discussed on python-dev. Greg has stated though that he doesn't feel it's ready (there are other factors, but this one is overriding). There were also discussions about the fact that to get maximum performance out of pyrex, it's necessary to produce very non-pythonic code. FWIW, I'm strongly in favour of Pyrex eventually becoming part of the Python distribution. Tim Delaney From apardon at forel.vub.ac.be Mon Nov 7 03:47:44 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Nov 2005 08:47:44 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> <87d5lhltt8.fsf@keizer.soze.com> <878xw5lry1.fsf@keizer.soze.com> <87sludsq8r.fsf@keizer.soze.com> Message-ID: Op 2005-11-04, Christopher Subich schreef : > Antoon Pardon wrote: >> Well maybe because as far as I understand the same kind of logic >> can be applied to something like >> >> lst[f()] += foo >> >> In order to decide that this should be equivallent to >> >> lst[f()] = lst[f()] + foo. >> >> But that isn't the case. > > Because, surprisingly enough, Python tends to evaluate expressions only > once each time they're invoked. Well but once can consider b.a as an expression too. An expression that gets evaluated twice in case of b.a += 2 > In this case, [] is being used to get an item and set an item -- > therefore, it /has/ to be invoked twice -- once for __getitem__, and > once for __setitem__. But we are here questioning language design. One could question a design where it is necessary to invoke the [] operator twice, even when it is only mentioned once in the code. > Likewises, lst appears once, and it is used once -- the name gets looked > up once (which leads to a += 1 problems if a is in an outer scope). > > f() also appears once -- so to evaluate it more than one time is odd, > at best. No more or less than "[]" or "." is to be invoked twice. -- Antoon Pardon From desparn at wtf.com Sun Nov 20 10:44:36 2005 From: desparn at wtf.com (Rick Wotnaz) Date: Sun, 20 Nov 2005 10:44:36 -0500 Subject: about lambda References: <1132494099.642274.220720@g14g2000cwa.googlegroups.com> Message-ID: "bonono at gmail.com" wrote in news:1132494099.642274.220720 at g14g2000cwa.googlegroups.com: > > Shi Mu wrote: >> what does the following code mean? It is said to be used in the >> calculation of the overlaid area size between two polygons. >> map(lambda x:b.setdefault(x,[]),a) > > The equivalent of : > > def oh_my_yet_another_function_name_why_not_use_lambda(x): > b.setdefault(x,[]) > > map(oh_my_yet_another_function_name_why_not_use_lambda, a) > > Or > > for x in a: > b.setdefault(x,[]) > > Or even: [b.setdefault(x,[]) for x in a] The effect of the code is this: if you have b, a dictionary of values, and a, a list or tuple of indexes to the dictionary, you can generate a list that will contain just the values associated with the indices in the list. If the index is not found in the dictionary, the default value will be used; in this case, that is an empty list. So, for example, if you have b = {'x':1,1:(1,2,3),'arthur':'A string',99:{'j':45,'k':111}} and a looks like this: you produce this: a = (0,1,'x') [[], (1, 2, 3), 1] a = (0,2,3,22) [[], [], [], []] a = ['x','arthur'] [1, 'A string'] ... and so on. -- rzed From igouy at yahoo.com Wed Nov 30 17:37:37 2005 From: igouy at yahoo.com (Isaac Gouy) Date: 30 Nov 2005 14:37:37 -0800 Subject: python speed In-Reply-To: References: <438d9409$0$67256$157c6196@dreader2.cybercity.dk> <1133383306.218266.123210@f14g2000cwb.googlegroups.com> Message-ID: <1133390257.578054.218620@g47g2000cwa.googlegroups.com> Peter Hansen wrote: > Isaac Gouy wrote: > > Peter Hansen wrote: > >>Judging by the other posts in this thread, the gauntlet is down: Python > >>is faster than Java. Let those who believe otherwise prove their point > >>with facts, and without artificially handcuffing their opponents with > >>non-real-world "purity" requirements. > > > That form of argument is listed as one of the principal forms of > > illogical thinking in "Being Logical" D.Q.McInerny - "An Inability to > > Disprove Does Not Prove" > > Good thing this is the form of argument *against* which I was arguing, > rather than that which I choose to use myself. (Read very carefully, if > you really think I was saying otherwise, and point out exactly where I > made any such claims for my own part. In fact, I was referencing the > arguments of others -- who *were* supporting their arguments with facts, > as near as I can tell -- and I was calling on the opposition to do the > same, and without changing the rules mid-discussion.) > > > "The fact that there is no concrete proof against a position does not > > constitute an argument in favour of the position. I cannot claim to be > > right simply because you can't prove me to be wrong." > > Isn't that what I was saying? That those who claim Python isn't faster > were not supporting their arguments with actual facts? > > -Peter *Python is faster than Java. Let those who believe otherwise prove their point with facts* We must be looking at different threads :-) afaict the only posting that provided something like "facts" was http://groups.google.com/group/comp.lang.python/msg/309e439697279060 Which stated "Python is doing the heavy lifting with GMPY which is a compiled C program with a Python wrapper" - but didn't seem to compare that to GMPY with a Java wrapper? From bokr at oz.net Fri Nov 18 00:27:10 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 18 Nov 2005 05:27:10 GMT Subject: Hot to split string literals that will across two or more lines ? References: Message-ID: <437d636b.86335784@news.oz.net> On Fri, 18 Nov 2005 11:33:57 +0800, Xiao Jianfeng wrote: >Lars Kellogg-Stedman wrote: > >>>print "a string whcih is very very looooooooooooooooooooooooooooooooooo\ >>>oooooooooooooooooooong." >>> >>> >> >>print "a string which is very loooooo" \ >> + "ooooong." >> Personally, I prefer to use a parenthesized expression format instead of "\" and (as has been mentioned) to remove the '+' between adjacent string literals, since the tokenizer will join adjacent string literals into one to generate a single constant. This is more efficient at run time also, since there are no byte codes generated for the adding. E.g., the above becomes print ("a string which is very loooooo" "ooooong.") or formatted however you please. Sometimes if the substring source code is machine generated, it is handy to bracket the substrings between a header line and a trailer line, e.g., print ( "a string which is very loooooo" "ooooong." ) Regards, Bengt Richter From rganesan at myrealbox.com Wed Nov 9 11:24:42 2005 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Wed, 09 Nov 2005 21:54:42 +0530 Subject: Hi, from my login i want to login as a other user , References: <1131533184.096101.49940@g49g2000cwa.googlegroups.com> <4371e131$0$19929$626a54ce@news.free.fr> <1131537660.853452.124790@z14g2000cwz.googlegroups.com> Message-ID: >>>>> sumi writes: > Hi, i am very new to python , it is just 2 days i started reading abt > it. I did not understand the above statement. Just read the document at the URL given to you. > what i want to do is , i want to login as a super user eg : $su xyz , and > then i need to enter the passwd, i want to do these steps using python , > how can i do it?????????? This is a slightly better description of the problem. However it's still not clear what exactly you want to achieve. Do you need to continue running your python script as the new user? Or do you want to run other commands as teh new user? In any case, take a look at pexpect (http://pexpect.sourceforge.net) and see if it fits your purpose. Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan | http://rganesan.blogspot.com From twic at urchin.earth.li Thu Nov 3 14:56:48 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 3 Nov 2005 19:56:48 +0000 Subject: Running autogenerated code in another python instance In-Reply-To: References: <43685941.1593033671@news.oz.net> Message-ID: On Thu, 3 Nov 2005, Paul Cochrane wrote: > On Wed, 02 Nov 2005 06:33:28 +0000, Bengt Richter wrote: > >> On Wed, 2 Nov 2005 06:08:22 +0000 (UTC), Paul Cochrane wrote: >> >>> I've got an application that I'm writing that autogenerates python >>> code which I then execute with exec(). I know that this is not the >>> best way to run things, and I'm not 100% sure as to what I really >>> should do. I've had a look through Programming Python and the Python >>> Cookbook, which have given me ideas, but nothing has gelled yet, so I >>> thought I'd put the question to the community. But first, let me be a >>> little more detailed in what I want to do: Paul, this is a rather interesting problem. There are two aspects to it, which i believe are probably separable: getting instructions from the client to the server, and getting data back from the server to the client. The former is more complex, i think, and what's attracted the attention so far. The first thing i'd say is that, while eval/exec is definitely a code smell, that doesn't mean it's never the right solution. If you need to be able to express complex things, python code might well be the best way to do it, and the best way to evaluate python code is eval/exec. >> It's a little hard to tell without knowing more about your user input >> (command language?) syntax that is translated to or feeds the process >> that "autogenerates python code". > > It's basically just a command language I guess. Hang on - the stuff that the user writes is what you're calling "pyvisi code", is that right? That doesn't look like 'just a command language', that looks like python, using a library you've written. Or is there another language, the "just a command language", on top of that? And what you call "vtk-python code" - this is python again, but using the renderer's native library, right? And you generate the vtk-python from the pyvisi-python by executing the pyvisi-python, there being (pluggable renderer-specific) logic in the guts of your pyvisi classes to emit the vtk-python code, right? You're not parsing anything? >> There are lots of easy things you could do without generating and exec-ing >> python code per se. > > I'd love to know of other options. I like the idea of generating the > code one would have to write for a particular renderer so that if the > user wanted to, they could use the autogenerated code to form the basis > of a specific visualisation script they could then hack themselves. If you want vtk-python code as an intermediate, i think you're stuck with eval/exec [1]. > One of the main ideas of the module is to distill the common visualisation > tasks down to a simple set of commands, and then let the interface work out > how to actually implement that. Okay. There's a classic design pattern called Interpreter that applies here. This is one of the more complex patterns, and one that's rather poorly explained in the Gang of Four book, so it's not well-known. Basically, the idea is that you provide classes which make it possible for a program to build structures encoding a series of instructions - essentially, you define a language whose concrete syntax is objects, not text - then you write code which takes such structures and carries out the instructions encoded in them - an interpreter, in other words. For example, here's a very simple example for doing basic arithmetic: # the language class expression(object): pass class constant(expression): def __init__(self, value): self.value = value class unary(expression): def __init__(self, op, arg): self.op = op self.arg = arg class binary(expression): def __init__(self, op, arg_l, arg_r): self.op = op self.arg_l = arg_l self.arg_r = arg_r # the interpreter UNARY_OPS = { "-": lambda x: -x, "|": lambda x: abs(x) # apologies for abnormal syntax } BINARY_OPS = { "+": lambda l, r: l + r, "-": lambda l, r: l - r, "*": lambda l, r: l * r, "/": lambda l, r: l / r, } def evaluate(expr): if isinstance(expr, constant): return expr.value elif isinstance(expr, unary): op = UNARY_OPS[expr.op] arg = evaluate(expr.arg) return op(arg) elif isinstance(expr, binary): op = BINARY_OPS[expr.op] arg_l = evaluate(expr.arg_l) arg_r = evaluate(expr.arg_r) return op(arg_l, arg_r) else: raise Exception, "unknown expression type: " + str(type(expr)) # a quick demo expr = binary("-", binary("*", constant(2.0), constant(3.0)), unary("-", binary("/", constant(4.0), constant(5.0)))) print evaluate(expr) This is by no means a useful or well-designed bit of code, and there are several things that could have been done differently (bare vs wrapped constants, operations defined by a symbol vs expression subtypes for each operation, etc), but i hope it gets the idea across - representing a language using an object graph, which lets you write programs that can speak that language. Your code is already doing something a bit like this - you build scene graphs, then call render on them to get them to do something. Instead of that, you'd pass the whole scene to a renderer object, which would do the rendering (directly, rather than by generating code). The point is that the renderer could be in another process, provided you have a way to move the scene graph from one process to another - the pickle module, for example, or a custom serialisation format if you feel like reinventing the wheel. An approach like this has a natural solution to your second problem, too - the evaluator function can return objects, which again can just be pickled and sent over the network. tom [1] Okay, so there is a way to do this without ever actually creating python code. You're not going to like this. You need to apply the interpreter pattern to python itself. Well, a simplified subset of it. Looking at your generated vtk-python code, you basically do the following things: - call methods with variables and literals as arguments - throwing away the result - or keeping it in a variable - do for loops over ranges of integers To make things a bit simpler, i'm going to add: - getting attributes - subscripting arrays - return a value You also need to do some arithmetic, i think; i leave that as an exercise for the reader. So we need a language like: class statement(object): pass class invoke(statement): def __init__(self, var, target, method, args): self.var = var # name of variable for result; None to throw away self.target = target self.method = method self.args = args class get(statement): def __init__(self, var, target, field): self.var = var self.target = target self.field = field class subscript(statement): def __init__(self, var, target, index): self.var = var self.target = target self.index = index class forloop(statement): def __init__(self, var, limit, body): self.var = var self.limit = limit self.body = body # tuple of statements def return_(statement): def __init__(self, value): self.value = value With which we can write a script like: vtk_script = [ invoke("_plot", "vtk", "vtkXYPlotActor", ()), invoke("_renderer", "vtk", "vtkRenderer", ()), invoke("_renderWindow", "vtk", "vtkRenderWindow", ()), invoke(None, "_renderWindow", "AddRenderer", ("_renderer")), invoke(None, "_renderWindow", "SetSize", (640, 480)), invoke(None, "_renderer", "SetBackground", (1, 1, 1)), invoke("_x", None, "array", ([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],)), get("vtk_vtkDataArray", "vtk", "vtkDataArray"), get("vtk_VTK_FLOAT", "vtk", "VTK_FLOAT"), invoke("_xData", "vtk_vtkDataArray", "CreateDataArray", ("vtk_VTK_FLOAT",)), invoke("_x_len", None, "len", ("_x",)), invoke(None, "_xData", "SetNumberOfTuples", ("_x_len",)), invoke("_y0", None, "array", ([0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0],)), invoke("_y0Data", "vtk_vtkDataArray", "CreateDataArray", ("vtk_VTK_FLOAT",)), invoke("_y0_len", None, "len", ("_y0",)), invoke(None, "_y0Data", "SetNumberOfTuples", ("_y0_len",)), forloop("i", "_x_len", ( subscript("_x_i", "_x", "i"), invoke(None, "_xData", "SetTuple1", ("i", "_x_i")),)), # etc ] Or rather, your pyvisi classes can generate structures like this, exactly as they currently generate code. Code to convert this into python source is trivial, so i'll gloss over that. The interpreter looks like this: def isiterable(x): return hasattr(x, "__iter__") def execute(script, vars=None): if (vars == None): vars = {} # initialise variables with 'vtk' and anything else you need def decode_arg(arg): if (isinstance(arg, str)): return vars[arg] elif (isiterable(arg)): return map(decode_arg, arg) else: return arg for stmt in script: if (isinstance(stmt, invoke)): target = vars[stmt.target] method = getattr(target, stmt.method) args = decode_arg(stmt.args) result = method(*args) if (stmt.var != None): vars[stmt.var] = result elif (isinstance(stmt, get)): target = vars[stmt.target] vars[stmt.var] = getattr(target, stmt.field) elif (isinstance(stmt, subscript)): target = vars[stmt.target] vars[stmt.var] = getattr(target, decode_arg(stmt.index)) elif (isinstance(stmt, forloop)): var = stmt.var limit = decode_arg(stmt.limit) body = stmt.body for i in range(limit): vars[var] = i execute(body, vars) elif (isinstance(stmt, return_)): return vars[stmt.value] # nb won't work from inside a for loop! # you can use an exception to handle returns properly Note that i haven't tested this, i've just written it off the top of my head, so it probably won't work, but maybe you get the idea. To be honest, i'd go with exec. -- Fitter, Happier, More Productive. From james at colannino.org Fri Nov 11 18:08:52 2005 From: james at colannino.org (James Colannino) Date: Fri, 11 Nov 2005 15:08:52 -0800 Subject: os.chown() Message-ID: <43752484.20706@colannino.org> Hey everyone. I tried to use os.chown() in the following manner: os.chown('filename', 'username', 'groupname') I got an error, and when I googled for this function I realized that I must pass the numerical uid and gid. My question is, is there a way for me to change ownership based on the name instead of the number? Perhaps there's a function that will let me lookup the uid from the username, and the gid from the groupname? Thanks :) James -- My blog: http://www.crazydrclaw.com/ My homepage: http://james.colannino.org/ "A well regulated militia being necessary to the security of a free state, THE RIGHT of the people to keep and bear arms SHALL NOT BE INFRINGED." --United States Constitution, Second Ammendment From thakadu at gmail.com Fri Nov 4 14:33:39 2005 From: thakadu at gmail.com (thakadu) Date: 4 Nov 2005 11:33:39 -0800 Subject: fcntl.flock() not working when called from a function Message-ID: <1131132819.081353.213180@z14g2000cwz.googlegroups.com> The following code works as expected when run in the main body of a python script (ver 2.3.5) on OpenBSD v3.8. but when it is in the body of a function definition it does not work. It does not raise any errors but it simply does not block as expected. I have repeated this in both a cgi envirnoment and a non-cgi environment. I also have repeated it under OpenBSD 3.6 Python Version 2.3.4. To test this you need to run the code from two shells or if testing the cgi version from two browsers. The first call to flock() should pass without blocking while the second call should block. I have tried varying the file open mode by using 'r', 'r+', 'w', 'rw', 'w+', and always I get the same results. Does anyone have an idea why this would work in the main body of the script but not in a function? This code works if in the main body of a script: import fcntl f=open('/tmp/lockfile') fcntl.flock(f,fcntl.LOCK_EX) but this does not work: import fcntl def lock(): f=open('/tmp/lockfile') fcntl.flock(f,fcntl.LOCK_EX) lock() From csubich.spam.block at spam.subich.block.com Fri Nov 4 10:31:42 2005 From: csubich.spam.block at spam.subich.block.com (Christopher Subich) Date: Fri, 04 Nov 2005 10:31:42 -0500 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131026455.722847.153180@g14g2000cwa.googlegroups.com> Message-ID: Antoon Pardon wrote: > Well I wonder. Would the following code be considered a name binding > operation: > > b.a = 5 Try it, it's not. Python 2.2.3 (#1, Nov 12 2004, 13:02:04) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-42)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a Traceback (most recent call last): File "", line 1, in ? NameError: name 'a' is not defined >>> b = object() >>> b.a Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'a' Once it's attached to an object, it's an attribute, not a base name. The distinction is subtle and possibly something that could (should?) be unified for Py3k, but in cases like this the distinction is important. From james.hague at gmail.com Tue Nov 8 14:33:28 2005 From: james.hague at gmail.com (James) Date: 8 Nov 2005 11:33:28 -0800 Subject: which feature of python do you like most? References: <1131452512.084857.10350@g43g2000cwa.googlegroups.com> Message-ID: <1131478407.991699.231860@g43g2000cwa.googlegroups.com> Most of the responses are of the "Why Python is more pleasant than C++" variety, but the original poster specifically said he had experience with Perl. As such, arguments like "automatic memory management" don't carry any weight. >From my experience as both a Perl and Python user--and I do prefer Perl for many tasks--the big win for Python is when you have complex data structures: dictionaries containing arrays, arrays of arrays, array of dictionaries, and so on. This kind of thing is awkward in Perl (you need to use references), but perfectly natural and obvious in Python. From exarkun at divmod.com Tue Nov 15 14:34:36 2005 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 15 Nov 2005 14:34:36 -0500 Subject: is parameter an iterable? In-Reply-To: <1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: <20051115193436.10365.1849735283.divmod.quotient.8156@ohm> On 15 Nov 2005 11:26:23 -0800, py wrote: >Dan Sommers wrote: >> Just do it. If one of foo's callers passes in a non-iterable, foo will >> raise an exception, and you'll catch it during testing > >That's exactly what I don't want. I don't want an exception, instead I >want to check to see if it's an iterable....if it is continue, if not >return an error code. Error codes are not the common way to do things in Python. Exceptions are. There's generally no reason to avoid exceptions. Error codes allow errors to pass silently, which leads to bugs that nobody notices for long periods of time. You should let the exception be raised. You shouldn't try to return an error code. >I can't catch it during testing since this is going to be used by >other people. Then they'll catch it during their testing >:) If you return an error code instead, they are just as likely to pass in bad data, and even *more* likely to not see that an error has occurred, causing their programs to be incorrect. Jean-Paul From mwm at mired.org Tue Nov 8 20:06:15 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Nov 2005 20:06:15 -0500 Subject: user account logon from python References: Message-ID: <86ek5qaauw.fsf@bhuda.mired.org> "Philippe C. Martin" writes: > Jeff, > > 1- I cannot find getpwent in the documentation getpwent is a Unix library call. For python, you want the pwd module. The docs are . > 2- crypt will not work if the system does not have shadow pw Rubbish. crypt doesn't know anything about passord files. It just knows how to encrypt a password. It's up to you to get the password attempt from the user, and the encrypted password from the password file (or the shadow password file). The pwd module doesn't deal with shadow passwords. Maybe you meant "system does have shadow pw". But it's pwd that doesn't work, not crypt - and that depends on the system. For instance: bhuda% cat tp.py #!/usr/bin/env python import pwd, os p = pwd.getpwnam(os.environ['USER']) print p[1] bhuda% ./tp.py * But: bhuda# ./tp.py $1$cKJbUtaY$y.e7GRjo8ePxgiBzskyRX0 I.e. - as me, the pwd routines won't return passwords. As root, it returns the encrypted password. > 3- Even as root I get "Operation not permitted" using setuid and setgid ... > but I assume it is because I cannot get 1 and/or 2 to work. They shouldn't have anything to do with it. Are you sure the process is running as root? For instance, most modern Unices won't honor the the setuid bit on script executables. You have to write a setuidj wrapper that runs the interpreter with the appropriate privileges. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fred at adventistcare.org Tue Nov 15 08:12:17 2005 From: fred at adventistcare.org (Sells, Fred) Date: Tue, 15 Nov 2005 08:12:17 -0500 Subject: Is Python worth it?? Message-ID: <777056A4A8F1D21180EF0008C7DF75EE033176C4@sunbelt.org> I second what others have said about the tutorials. I have not read "how to think like a ..." but from other posting here I have reservations about it as a starting point. -----Original Message----- From: Simon Brunning [mailto:simon.brunning at gmail.com] Sent: Tuesday, November 15, 2005 4:42 AM To: john boy Cc: python-list at python.org Subject: Re: Is Python worth it?? On 14/11/05, john boy wrote: > I have started out trying to learn Python for my first programming language. > I am starting off with the book "how to think like a computer scientist." > I spend about 4-5 hrs a day trying to learn this stuff. It is certainly no > easy task. I've been at it for about 1-2 weeks now and have a very > elementary picture of how Python works. I am teaching myself from home and > only recieve help from this forum. Can anybody give me a timeframe as to > how long it usually takes to pick something like this up, so I can maybe > figure out a way to pace myself? I can dedicate a good amount of time to it > everyday. Any advice on what is the best way to learn Python? I am a > fairly educated individual with a natural sciences degree (forestry), so I > also have a decent math background. Are there any constraints > mathematically or logic "wise" that would prevent me from building a firm > grasp of this language? Keep at it. Everyone is different, so don't worry about how long it takes you vs. how long others might take. If you have no programming background, there's a lot to learn. Using Python is a good choice, I think, 'cos it gets a lot of extranious crud that many other languages insist on out of your way, but there's still a lot to learn. The best way to learn? Go through the tutorials - but if you get an idea for a mini-project of your own, don't be afraid to dive off and give it a go. Try to solve you own problems for a while, 'cos that's a valuable skill, but don't get to the point of frustration. Ask for help here or on the tutor mailing list[1]. And have fun. [1] http://mail.python.org/mailman/listinfo/tutor -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------------- 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 not at valid.org Wed Nov 23 18:11:01 2005 From: not at valid.org (yomgui) Date: Wed, 23 Nov 2005 15:11:01 -0800 Subject: return in loop for ? Message-ID: <4384F705.31CEC951@valid.org> hello, is it legal to return inside a for loop or am I obliged to break out of the loop before returning ? thanks yomgui From rudy.schockaert at gmail.com Tue Nov 15 14:13:01 2005 From: rudy.schockaert at gmail.com (Rudy Schockaert) Date: Tue, 15 Nov 2005 20:13:01 +0100 Subject: AJAX => APAX? Or: is there support for python in browsers? In-Reply-To: <4379EB06.1050508@websafe.com> References: <4379EB06.1050508@websafe.com> Message-ID: <60987dac0511151113wdf0cad0u909b239af5db1120@mail.gmail.com> Indeed, and a huge success in the TurboGears project. Check it out. On 11/15/05, Larry Bates wrote: > > Roger Erens wrote: > > Hello, > > > > I remember that the first time I read about Python as a programming > > language was when reading the W3C's HTML 4.01 specification a few years > > ago. In the section on objects, images and applets > > (http://www.w3.org/TR/html401/struct/objects.html) an example was given > > like > > > >

> > > > > > This user agent cannot render Python applications. > > > > > > It's also in the XHTML2.0 specification. Now, is this just a theoretical > > example? Or is there a browser that _does_ support python scripts? Or do > > we have to place our bets on the Mozilla 1.9 milestone with hard work > > being done by Mark Hammond? > > > > I'm asking because of all the AJAX hype going on. I'd like rather not > > delve too deep into JavaScript and use Python instead. > > > > Any insights to be shared? > > > > Cheers, > > Roger > > Take a look at this kit: > > http://www.mochikit.com/ > > It seems that this is a python programmer that has created JavaScript > functions that "feel" a lot like Python. May just be a transitional > way to go, but I thought it was interesting anyway. > > -Larry Bates > -- > http://mail.python.org/mailman/listinfo/python-list > -- "You don't stop laughing because you grow old. You grow old because you stop laughing." -- Michael Pritchard -------------- next part -------------- An HTML attachment was scrubbed... URL: From joshuacronemeyer at sunflower.com Thu Nov 24 10:05:59 2005 From: joshuacronemeyer at sunflower.com (Josh Cronemeyer) Date: Thu, 24 Nov 2005 09:05:59 -0600 Subject: Understanding Python Documentation Message-ID: <200511240906.00008.joshuacronemeyer@sunflower.com> Hi, I have very little experience programming in python but considerable experience with java. One thing that is frustrating me is the differences in the documentation style. Javadocs, at the top level are just a list of packages. Drilling down on a package reveals a list of classes in that package, and drilling down on a class reveals a list of methods for that class. Is there something similar for python? The closest thing I have found to this for python is http://www.python.org/doc/2.4.2/modindex.html which really isn't the same thing at all. wxpython has their documentation like this http://www.wxpython.org/docs/api/ is there something like this for the rest of python? From r.roelofsen at tuxed.de Wed Nov 9 18:52:00 2005 From: r.roelofsen at tuxed.de (Roman Roelofsen) Date: Thu, 10 Nov 2005 00:52:00 +0100 Subject: Pythonising the vim (e.g. syntax popups) -> vimpst In-Reply-To: <200511091609.09613.email@christoph-haas.de> References: <200511091609.09613.email@christoph-haas.de> Message-ID: <200511100052.01043.r.roelofsen@tuxed.de> > Evening, > > Is there a decent way to get that help into vim? Or like showing docstrings > or help that I get through pydoc on request? I've been working myself > through a pile of vim macros/plugins but couldn't find even one which > simplifies programming in Python. Further issues would be handling the Hi Christoph, Hi Vim users, The last 5 days I?ve been working on a code-completion/calltips plugin for vim. It?s working pretty good but not finished yet. I will anounce the first beta version on this mailling list. I hope during the next week. I recorded a swf-video so that you can take a look at the current status. Link: http://www.tuxed.de/vimpst/video.tar.gz Note that it is not necessary to generate symboltable files, etc. Everything is done "on demand". It is even possible to change the python implementation e.g. CPython, Jython, IronPython. It is also possible to add some "special feature" interceptor. Currently this is working for SQLObject: Lets say you have the class User and the attribute username is a alternate ID. Then, the method User.byUsername("...") will always return a User object. vimpst checks this and provides a suitable help. Regards, Roman From jgardner at jonathangardner.net Fri Nov 4 10:33:21 2005 From: jgardner at jonathangardner.net (jgardner at jonathangardner.net) Date: 4 Nov 2005 07:33:21 -0800 Subject: help converting some perl code to python In-Reply-To: References: <1131094909.984993.32330@z14g2000cwz.googlegroups.com> Message-ID: <1131118401.338995.219810@g43g2000cwa.googlegroups.com> The '..' operator is the flip-flop operator in perl. (It is rarely used.) It is exactly the same as the 'range' type operator. It returns false until the first condition is met, then it returns true until the last condition met, then it returns false. You could create a flip-flop with a python closure (t_cond and f_cond are functions that take a value and return True of False) def make_flip_flop(t_cond, f_cond): state = [False] def flip_flop(val): if state[0] and f_cond(val): state[0] = False elif not state[0] and t_cond(val): state[0] = True return state[0] return flip_flop From snail at objmedia.demon.co.uk Fri Nov 18 15:42:07 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 18 Nov 2005 20:42:07 +0000 Subject: Web-based client code execution References: <3u6ngeFvh3v1U1@individual.net> <1132342910.799932.58720@g44g2000cwa.googlegroups.com> Message-ID: In message <1132342910.799932.58720 at g44g2000cwa.googlegroups.com>, Steve writes >AJAX works because browsers can execute javascript. I don't know of a >browser that can execute python. Basically your stuck with java or >javascript because everything else really isn't cross platform. ActiveState do a version of Python that can run in a script tag like JavaScript and VBScript. This requires Windows Scripting Host. They also do a similar thing for Perl, not sure about TCL. The syntax is along the lines of I remember reading this about PerlScript and I'm pretty sure I'm correct in remembering there is a PythonScript. Anyway you are limited to ActiveState and Windows Scripting Host. For pragmatic reasons I think you would be better concentrating on JavaScript for the Client and your language of choice Python/Ruby/Lua/whatever for the server part of AJAX. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From carsten at uniqsys.com Fri Nov 18 11:10:06 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 18 Nov 2005 11:10:06 -0500 Subject: How to convert a "long in a string" to a "long"? In-Reply-To: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> References: <1132329856.693360.288480@g44g2000cwa.googlegroups.com> Message-ID: <1132330206.30323.30.camel@dot.uniqsys.com> On Fri, 2005-11-18 at 11:04, ondekoza at gmail.com wrote: > Hello, > > I need to convert the string "FFFFFFFF" to a long. To convert this > string I tried the following: > >>> 0xffffffff > -1 > >>> 0xffffffffL > 4294967295L > > OK, this is what I want, so I tried > > s = long("0xffffffffL") > ValueError: invalid literal for long(): 0xffffffffL > > s = long("0xffffffff") > ValueError: invalid literal for long(): 0xffffffffL > > What can I do? > > Thank you in advance. > Stefan Leave out the "0x" prefix and tell long() that you're using base 16: >>> long("ffffffff", 16) 4294967295L HTH, Carsten. From onurb at xiludom.gro Tue Nov 8 09:38:09 2005 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 08 Nov 2005 15:38:09 +0100 Subject: recursive function call In-Reply-To: References: Message-ID: <4370b852$0$14083$626a14ce@news.free.fr> Nicolas Vigier wrote: > Hello, > > I have in my python script a function that look like this : > > def my_function(arg1, arg2, opt1=0, opt2=1, opt3=42): > if type(arg1) is ListType: How should it behave with tuples or subclasses of List ? Or if it's any other iterable ? Testing against the *exact* type of an object is usually not a good idea in Python. You should at least replace this test with something like: if isinstance(arg1, list): #code here or even better: if hasattr(arg1, '__iter__'): # code here or still even better (for maintenance at least): def my_function(arg1, ...): def kind_of_list(arg): return hasattr(arg1, '__iter__') if kind_of_list(arg1): # code here > for a in arg1: > my_function(a, arg2, opt1=opt1, opt2=opt2, opt3=opt3) > return > if type(arg2) is ListType: > for a in arg2: > my_function(arg1, a, opt1=opt1, opt2=opt2, opt3=opt3) > return > ... then here the real function code > > I'm new to python, so I was wondering if there is a better way to do that. > The reason for a recursive function here is to be able to give lists for > the first 2 args If possible, you'd better decide for a simplest API. Either always pass a kind_of_list, or let the user take care of the loop. You can also use two functions, one that actually do the job and the other that do the test and wrap the call to the first (note that the first function doesn't need to be part of the public API). This makes code more readable, and cleany decouple effective task from the test_type_and_dispatch mechanism. ie: def doTheJob(arg, opt1=None, opt2=None, opt3=None): # effective code here pass def callDoTheJob(arg1, arg2, opt1=0, opt2=1, opt3=42): if is_kind_of_list(arg1): for a in arg1: callDoTheJob(a, arg2, ....) elif is_kind_of_list(arg2): for a in arg2: callDoTheJob(arg1, a, ....) else: doTheJob(arg1, arg2, ...) > (I could as well use only a simple 'for' without a > recursive call). This can be better when it comes to perfs. I find the recursive solution to be more readable (but this is a matter of taste), and it has the advantage/drawback (depends on the real usage) that nested lists are handled for (almost) any depth of nesting. > The problem I have here, is that as I'm working on this > script, I often change the prototype of the function, and each time I > have to think about changing the recursive call too. Is there a way that > I can do a recursive call and say something like "keep all the same > arguments except this one" ? If this only concern the 'opts' args: def callDoTheJob(arg1, arg2, **kw): if is_kind_of_list(arg1): for a in arg1: callDoTheJob(a, arg2, **kw) elif is_kind_of_list(arg2): for a in arg2: callDoTheJob(arg1, a, **kw) else: doTheJob(arg1, arg2, **kw) hth -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mhellwig at xs4all.nl Sat Nov 26 15:39:13 2005 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 26 Nov 2005 21:39:13 +0100 Subject: wxPython Licence vs GPL In-Reply-To: References: <43837289$0$27610$4fafbaef@reader1.news.tin.it> <1132755285.097073.61200@g49g2000cwa.googlegroups.com> <11o930pojo086fd@corp.supernews.com> <1132766124.891749.162010@o13g2000cwo.googlegroups.com> <11o9v2l5qqa7765@corp.supernews.com> <43856594.40300@REMOVEMEcyber.com.au> <43857f2c$0$11076$e4fe514c@news.xs4all.nl> <864q62yrkg.fsf@bhuda.mired.org> <4385edad$0$11067$e4fe514c@news.xs4all.nl> <4388385e$0$11063$e4fe514c@news.xs4all.nl> Message-ID: <4388c7f9$0$11080$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > > > I think you are over-estimating both the numbers and profitability of such > niche software distributors, and misunderstanding the business models of > them. Coincidently, I worked at a software company making a "standard" administration software for primary schools. Which concentrate on the national market. Because this in the Netherlands, not such a big country, the customer base is not that big. So on a population of 17 million people there are about 7.500 thousands primary schools, our market share was quit big we had 4.500 thousands customers, there where "only" about 7 other competitive products/companies in that market. The software was sold in 3 separates modules requiring a yearly renewal, the base module was required for all customers the other modules where add on packages, the base module cost about 500 EUR, then there where 2000 clients for 350 EUR module and about 500 clients for the third 250 module. They also sold administration software for the academic market with about the same annual income as that of the primary schools. So for a niche market on a small user base using non-consulting software, they had a quite profitable steady income. Perhaps not the billions of dollars you expect from a software company but for me and the 40 other employees it was enough to say that we didn't over-estimated both the numbers and profitability of such a niche software distributor and we sure didn't misunderstood the business model of that. Unfortunately the profitable company was merged by the VC's with 8 non-profitables companies because they had that this would make them all profitable. -- mph From crw at chello.se Wed Nov 30 09:50:27 2005 From: crw at chello.se (Me) Date: Wed, 30 Nov 2005 15:50:27 +0100 Subject: Multiple versions References: Message-ID: This will work fine for me Tim, thank you for your time! "Tim Golden" wrote in message news:mailman.1317.1133252254.18701.python-list at python.org... (Just to keep things readable, I've reordered the posts top-to-bottom chronologically. And "Me" is the cognomen of the original poster, not simply a redundant personal pronoun!) [Me] > I need to install both 2.3 and 2.4 on my Win2000 system. > Can someone please > give me a pointer as to how to do this? Thanks! [Tim Golden] > ... The simple answer is: just install > them (in different directories, eg c:\python23, > c:\python24), installing last the one which > you want your .py/.pyw files to be associated with. [Me] > Thank you for your reply! Is there a simple way to > change the .py/.pyw associations? Like a registry > setting I can "toggle"? Or are there lots of other > things involved, system directory libraries etcetera? Assuming that you're not doing anything fancy with system or Python paths -- and I guess from the tenor of your questions that you're not -- then it's just the same as changing any other file association on Windows. There was a thread on this subject fairly recently, but in essence you can either use the File Associations tab on Explorer (on XP it's under Tools > Folder Options > File Types) or you can use the command line equivalent: FTYPE Python.File="C:\Python24\python.exe" "%1" %* replacing c:\python24 by whatever is appropriate. If you really wanted to do things which involved testing your programs against different versions of Python, which I imagine might be your aim, then you probably want either to write some sort of batch file wrapper (search c.l.py for some examples of this in the past) or to use a MoveablePython installation: http://www.voidspace.org.uk/python/movpy/ which is designed for this kind of things (according to their introduction). TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ajartaknev at gmail.com Mon Nov 7 05:11:58 2005 From: ajartaknev at gmail.com (Ajar) Date: 7 Nov 2005 02:11:58 -0800 Subject: web interface Message-ID: <1131358318.437052.107220@f14g2000cwb.googlegroups.com> Hi, I have a stand alone application which does some scientific computations. I want to provide a web interface for this app. The app is computationally intensive and may take long time for running. Can someone suggest me a starting point for me? (like pointers to the issues involved in this, or even better any of the existing tools for doing this...) Ajar From mwm at mired.org Wed Nov 9 16:06:24 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 09 Nov 2005 16:06:24 -0500 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1131562381.449032.299630@g14g2000cwa.googlegroups.com> Message-ID: <8664r18ran.fsf@bhuda.mired.org> "bonono at gmail.com" writes: > How effective can it be when python is designed to make writing this > kind of code hard(hopefully impossible) ? The most effective would be > renaming function and may be variables but if the functions are kept > short, they would at most looks like haskell ;-) I haven't looked at obfuscator, so I have *no idea* how it works. The following is how I'd do it. Step one: globally replace all names in all python module withb names that are composed of long strings of l, 1, 0 and 0. Fixing cross-module references should be fun. Don't just make them random - make them all start with the same sequence, and end with the same sequence, having differences only in the middle. Step two: repeat this process for the contents of binary modules, not neglecting __builtins__. In this case, you probably can't remove the old names, but you can add new things to the module, and make sure you only reference those. I'm not sure how to go about fixing things that are referenced by name in binary modules. Maybe you'll have to leave those names in the modules. But you an make sure that all references in Python source use the new, binary-like names. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bonono at gmail.com Wed Nov 23 11:46:12 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 23 Nov 2005 08:46:12 -0800 Subject: best cumulative sum In-Reply-To: <4W0hf.11$id.3@trnddc04> References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> <4W0hf.11$id.3@trnddc04> Message-ID: <1132764372.123353.46410@o13g2000cwo.googlegroups.com> David Isaac wrote: > OK, this might do it. But is a generator "better"? > (I assume accuracy is the same, so what about speed?) > I have the slightest idea. So long it works for me and is not too hard to understand and has no obvious speed problem, I don't care too much. I believe in line is in general faster, especially you don't call other function too much. I like to use generator/list because I find it easier to understand and it is more BD(bondage and discipline) which save me a few occasions of subtle errors. From bonono at gmail.com Tue Nov 22 20:11:05 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 22 Nov 2005 17:11:05 -0800 Subject: best cumulative sum In-Reply-To: References: <9Qbgf.8204$BC2.5713@trnddc04> <1132553397.042444.147660@g44g2000cwa.googlegroups.com> <_zlgf.13457$a62.3638@trnddc07> Message-ID: <1132708265.941224.186550@g44g2000cwa.googlegroups.com> Michael Spencer wrote: > David Isaac wrote: > for a solution when these are available. > > Something like: > > def cumreduce(func, seq, init = None): > > """Return list of cumulative reductions. > > > > > This can be written more concisely as a generator: > > >>> import operator > >>> def ireduce(func, iterable, init): > ... for i in iterable: > ... init = func(init, i) > ... yield init > ... > >>> list(ireduce(operator.mul, range(1,5),init=1)) > [1, 2, 6, 24] > >>> If iterable has no elements, I believe the behaviour should be [init], there is also the case of init=None that needs to be handled. But otherwise, that is more or less what I wrote for my scanl/scanl1. > Michael From dudufigueiredo at gmail.com Tue Nov 1 21:26:08 2005 From: dudufigueiredo at gmail.com (Dudu Figueiredo) Date: 1 Nov 2005 18:26:08 -0800 Subject: Rename files with numbers In-Reply-To: References: <1130776390.085587.116270@g43g2000cwa.googlegroups.com> <1130784747.373637.108040@g14g2000cwa.googlegroups.com> <1130789205.862429.10090@g43g2000cwa.googlegroups.com> <20051031220841.GF2575@kitchen.client.attbi.com> <34bb7f5b0511010855u60848244p@mail.gmail.com> Message-ID: <1130898368.043850.20070@g14g2000cwa.googlegroups.com> I wrote a simpler script based in Micah Elliott's help, it's to add the band name to mp3 files imported with iTunes: import glob, os def renamer_itunes(songdir, band): """ Rename mp3 files imported from itunes, transformation: Song Name.mp3 --> Artists - Song Name.mp3 """ os.chdir(songdir) archives = glob.glob("*.mp3") pretties = [] for ugly in archives: song, ext = os.path.splitext(ugly) song = song.title() song = band + " - " + song songext = song + ext pretties.append(songext) for ugly, pretty in zip(archives, pretties): os.rename(ugly, pretty) Just an exercise, I'm begining in Python now... Thanks to every one that helped me, i'll bring more questions for you. Sorry for my bad english, i'm Brazilian... ! _________________ Eduardo Figueireredo http://dudufigueiredo.com From paschott at no.yahoo.spamm.com Fri Nov 11 16:25:44 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Fri, 11 Nov 2005 21:25:44 GMT Subject: Command-line tool able to take multiple commands at one time? References: <86acgc54ej.fsf@bhuda.mired.org> Message-ID: OK - I justed tested and may be doing something wrong, but it didn't work when I just tried it. I have something like this: X = "Value1" Y = "Value2" Z = "Value3" etc at the top of my script. When I copy/paste those three lines all at once into IDLE's interactive window, X is defined, Y and Z are not. That's more the behaviour I was hoping for - the ability to run parts of my code at a time in order to work through issues without too much trouble in mostly-working code. TIA, -Pete Schott Mike Meyer wrote: > Peter A. Schott writes: > > Per subject - I realize I can copy/paste a line at a time into an interactive > > session when I'm trying to debug, but was wondering if there is any tool out > > there that allows me to copy sections of working Python scripts to paste into my > > interactive console and let those run so I don't have to copy line-by-line. > > Um, just curious - doesn't copying multiple lines at a time work now? > That works fine for me on both OS X and Unix. > > References: <1130252059.474472.102670@g14g2000cwa.googlegroups.com> <1130252427.220729.312180@o13g2000cwo.googlegroups.com> <1130252913.385217.64250@g49g2000cwa.googlegroups.com> <1130945463.512471.172560@g14g2000cwa.googlegroups.com> Message-ID: <1131707736.259462.143610@f14g2000cwb.googlegroups.com> In case anyone else finds this thread, the solution is that for Moin >= 1.3.5, the 404 handling in IIS has to be changed for the Wiki Virtual Directory. See my blog at http://www.bloglines.com/blog/Kolossi?id=13 for details. From bignose+hates-spam at benfinney.id.au Mon Nov 14 00:01:57 2005 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 14 Nov 2005 16:01:57 +1100 (EST) Subject: Abstract Base Classes References: Message-ID: Ben Finney wrote: > I want my modules to (sometimes) define an abstract base exception > class, that all other exceptions in that module inherit from. Not a whole lot of feedback on this, so here's the implementation I decided upon. class FooException(Exception): """ Base class for all exceptions in this module """ def __init__(self): if self.__class__ is EnumException: raise NotImplementedError, \ "%s is an abstract class for subclassing" % self.__class__ class FooBarTypeError(TypeError, FooException): """ Raised when the foo gets a bad bar """ class FooDontDoThatError(AssertionError, FooException): """ Raised when the foo is asked to do the wrong thing """ This allows the exceptions for the module to behave similarly to their leftmost base exception; but because they all inherit from the abstract base class exception for the module, it also allows for this idiom: import foo try: foo.do_stuff(bar) except FooException, e: special_error_handler(e) Any more comment on this technique? Any other significant use cases for abstract base classes? -- \ "For man, as for flower and beast and bird, the supreme triumph | `\ is to be most vividly, most perfectly alive" -- D.H. Lawrence. | _o__) | Ben Finney From deets at nospam.web.de Thu Nov 3 17:29:11 2005 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Nov 2005 23:29:11 +0100 Subject: python, mssql and unicode In-Reply-To: <1131034411.281189.17770@g43g2000cwa.googlegroups.com> References: <1131034411.281189.17770@g43g2000cwa.googlegroups.com> Message-ID: <3svh9oFqfulaU1@uni-berlin.de> riek at zem.uni-bonn.de wrote: > Hello, > > I am using pymssql (http://pymssql.sourceforge.net/) to insert data > from a web-frontend (encoded in utf-8) into fields of type nvarchar of > an MS-SQL Server 2000. > > The problem is, ms-sql server uses ucs-2 and not utf-8. I have looked > around a bit but found no suitable solution to this problem so far > except converting the utf-8 into latin-1 which will restrict the > characters to western europe languages. > > Does any one have some suggestions? > > Thank you for your help! Hey Simnon, cool dich hier zu lesen :) AFAIK you should be able to use utf-16 as encoding for most practical pusrposes. http://www.python.org/peps/pep-0100.html Alternatively, it might be possible to have the mysql connection deliver and expect the string values in a different encoding from the one the data is stored in - at least with oracle that's possible. Regards, Diez B. Roggisch From fuzzyman at gmail.com Fri Nov 25 04:13:42 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Nov 2005 01:13:42 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <1h6h08u.5v642xndgfj2N%aleax@mail.comcast.net> References: <1132493596.945667.259650@g43g2000cwa.googlegroups.com> <1132531775.399671.93120@o13g2000cwo.googlegroups.com> <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383d564.508728452@news.oz.net> <1132735428.485669.153090@g43g2000cwa.googlegroups.com> <1h6h08u.5v642xndgfj2N%aleax@mail.comcast.net> Message-ID: <1132910022.308232.251080@o13g2000cwo.googlegroups.com> Alex Martelli wrote: > Fuzzyman wrote: > > > There is already an update method of course. :-) > > > > Slicing an ordered dictionary is interesting - but how many people are > > actually going to use it ? (What's your use case) > > I detest and abhor almost-sequences which can't be sliced (I consider > that a defect of collections.deque). If the ordered dictionary records > by its sequencing the time order of key insertion, being able to ask for > "the last 5 keys entered" or "the first 3 keys entered" seem to me to be > perfectly natural use cases, and most naturally accomplished by slicing > of course, d[-5:] and d[:3] respectively. > If you slice an ordered dictionary, I assume you would expect to get an ordered dictionary back ? Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > Alex From ggrp1.20.martineau at dfgh.net Tue Nov 15 14:02:38 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 15 Nov 2005 11:02:38 -0800 Subject: Default method arguments References: <1132070606.150912.150930@g47g2000cwa.googlegroups.com> <437a0a1b_1@newsgate.x-privat.org> <1132071889.676287.240030@o13g2000cwo.googlegroups.com> <1h628u2.j7q74x1i9uhlvN%aleax@mail.comcast.net> Message-ID: <1132081358.907286.15960@g49g2000cwa.googlegroups.com> Alex Martelli wrote, in part: > If it's crucial to you to have some default argument value evaluated at > time X, then, by Python's simple rules, you know that you must arrange > for the 'def' statement itself to execute at time X. In this case, for > example, if being able to have self.data as the default argument value > is the crucial aspect of the program, you must ensure that the 'def' > runs AFTER self.data has the value you desire. > > For example: > > class A(object): > def __init__(self, n): > self.data = n > def f(self, x = self.data) > print x > self.f = f > > This way, of course, each instance a of class A will have a SEPARATE > callable attribute a.f which is the function you desire; this is > inevitable, since functions store their default argument values as part > of their per-function data. Since you want a.f and b.f to have > different default values for the argument (respectively a.data and > b.data), therefore a.f and b.f just cannot be the SAME function object > -- this is another way to look at your issue, in terms of what's stored > where rather than of what evaluates when, but of course it leads to > exactly the same conclusion. FWIT and ignoring the small typo on the inner def statement (the missing ':'), the example didn't work as I (and possibily others) might expect. Namely it doesn't make function f() a bound method of instances of class A, so calls to it don't receive an automatic 'self'' argument when called on instances of class A. This is fairly easy to remedy use the standard new module thusly: import new class A(object): def __init__(self, n): self.data = n def f(self, x = self.data): print x self.f = new.instancemethod(f, self, A) This change underscores the fact that each instance of class A gets a different independent f() method. Despite this nit, I believe I understand the points Alex makes about the subject (and would agree). -Martin From lists at andreas-jung.com Wed Nov 2 12:41:44 2005 From: lists at andreas-jung.com (Andreas Jung) Date: Wed, 02 Nov 2005 18:41:44 +0100 Subject: subprocess module under Windows 98 In-Reply-To: <1130950104.827867.132670@z14g2000cwz.googlegroups.com> References: <1130950104.827867.132670@z14g2000cwz.googlegroups.com> Message-ID: <544F476776BA799FA6C7C997@suxmac> --On 2. November 2005 08:48:24 -0800 Ernesto wrote: > This worked for me on XP... not sure for 98... > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409002 Thanks, this works! Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From googlinggoogler at hotmail.com Tue Nov 8 13:25:32 2005 From: googlinggoogler at hotmail.com (googlinggoogler at hotmail.com) Date: 8 Nov 2005 10:25:32 -0800 Subject: Pylab and pyserial plot in real time In-Reply-To: References: <1131278509.380060.281410@g44g2000cwa.googlegroups.com> <1131314185.503002.57370@o13g2000cwo.googlegroups.com> Message-ID: <1131474332.625099.146900@o13g2000cwo.googlegroups.com> Juho Schultz: Thanks for that, havent got time to modify it for my needs at the moment, but im sure it'll work as i've just tried it Jeremy Sanders: Cheers for that, i'll check it out. thanks to everyone else to! Thanks David From pkilambi at gmail.com Thu Nov 10 14:03:27 2005 From: pkilambi at gmail.com (pkilambi at gmail.com) Date: 10 Nov 2005 11:03:27 -0800 Subject: help make it faster please In-Reply-To: <1131648018.390959.80610@f14g2000cwb.googlegroups.com> References: <1131645213.492863.19740@g43g2000cwa.googlegroups.com> <1131648018.390959.80610@f14g2000cwb.googlegroups.com> Message-ID: <1131649407.776813.57740@o13g2000cwo.googlegroups.com> ok this sounds much better..could you tell me what to do if I want to leave characters like @ in words.So I would like to consider this as a part of word From apardon at forel.vub.ac.be Mon Nov 21 07:42:01 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Nov 2005 12:42:01 GMT Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> Message-ID: Op 2005-11-20, Roy Smith schreef : > cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote: > >> One example I can think of is a large number of float constants used >> for some math routine. In that case they usually be a full 16 or 17 >> digits. It'd be handy in that case to split into smaller groups to >> make it easier to match with tables where these constants may come >> from. Ex: >> >> def sinxx(x): >> "computes sin x/x for 0 <= x <= pi/2 to 2e-9" >> a2 = -0.16666 66664 >> a4 = 0.00833 33315 >> a6 = -0.00019 84090 >> a8 = 0.00000 27526 >> a10= -0.00000 00239 >> x2 = x**2 >> return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10)))) >> >> (or least that's what I like to write). Now, if I were going to higher >> precision, I'd have more digits of course. > > You have described, if memory serves, a Taylor series, and those > coefficients are 1/3!, 1/5!, 1/7!, etc. Well if you had infinite precision numbers you might be right. However in numerial analysis, one often uses numbers which are slightly different, in order to have a more uniform error spread over the interval used. -- Antoon Pardon From levicc00123 at gmail.com Sun Nov 27 22:25:09 2005 From: levicc00123 at gmail.com (Levi Campbell) Date: 27 Nov 2005 19:25:09 -0800 Subject: reading internet data to generate random numbers. In-Reply-To: References: <1130955687.091682.301670@g14g2000cwa.googlegroups.com> Message-ID: <1133148309.207753.127120@g14g2000cwa.googlegroups.com> thank you, that was what I needed. From robert.h.boyd at gmail.com Tue Nov 1 14:33:19 2005 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Tue, 1 Nov 2005 14:33:19 -0500 Subject: Add attribute using pyxml In-Reply-To: <1130872149.945270.218070@g44g2000cwa.googlegroups.com> References: <1130872149.945270.218070@g44g2000cwa.googlegroups.com> Message-ID: On 1 Nov 2005 11:09:10 -0800, PyPK wrote: > > How do I add a new attribute to the existing xml Document tree??? > Add an attribute of an element, or add a new element? I hope I've understood your question correctly...this demonstrates both adding a brand new element (tag) and an attribute for it. from xml.dom.ext.reader.Sax2 import FromXmlStream doc = FromXmlStream(stream) # or FromXmlStream(open(name_of_file)) NewElement = doc.createElement('NewElement') NewElement.setAttribute('attribute_name', 'attribute_value') doc.documentElement.appendChild(NewElement) You'll wind up with You may need to use getElementsByTagName or other means to find the exact node to place your new element if you aren't putting it directly under the root element. To save into the original xml file, I create a filehandle to the file, then PrettyPrint(doc, fh). DISLAIMER: I just learned this last week, so if anything is wrong or could be improved, the list is welcome to correct me ;) Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Nov 3 01:48:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Nov 2005 07:48:28 +0100 Subject: how can I run python interactively? References: <1130998605.892334.70810@g49g2000cwa.googlegroups.com> Message-ID: "questions?" wrote: > I need to stop the program in the middle and pause there. > > Are there anyway I can stop the program in the middle and have > something like: > > please press y to continue..... portable: raw_input("please press return to continue.....") to get a single character, you can use msvcrt.getch() on windows, or the termios module on unix: http://effbot.org/librarybook/msvcrt.htm http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 http://www.faqts.com/knowledge_base/view.phtml/aid/4490/fid/538 etc From pu at pmville.com Fri Nov 18 01:45:35 2005 From: pu at pmville.com (Ask) Date: Fri, 18 Nov 2005 17:45:35 +1100 Subject: GTK for windows and Linux References: <437c3560@news1.veridas.net> <1132220556.790227.219560@g43g2000cwa.googlegroups.com> Message-ID: <437d78b1@news1.veridas.net> Thanks Renato, I'm downloading now. Pauly "Renato" wrote in message news:1132220556.790227.219560 at g43g2000cwa.googlegroups.com... > You'll need to install the libglade/gtk/pygtk packages from: > > http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ > > When your app is complete you can package it with py2exe > From steve at REMOVETHIScyber.com.au Fri Nov 4 13:02:06 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 05 Nov 2005 05:02:06 +1100 Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <1131023902.277600.189980@g49g2000cwa.googlegroups.com> Message-ID: On Fri, 04 Nov 2005 09:07:38 +0000, Antoon Pardon wrote: >>> Now the b.a on the right hand side refers to A.a the first time through >>> the loop but not the next times. I don't think it is sane that which >>> object is refered to depends on how many times you already went through >>> the loop. [snip] >> Look at that: the object which is referred to depends on how many times >> you've already been through the loop. How nuts is that? > > It is each time the 'x' from the same name space. In the code above the > 'a' is not each time from the same namespace. > > I also think you new very well what I meant. I'm supposed to be a mindreader now? After you've spent multiple posts ranting that, quote, "I don't think it is sane that which object is refered to depends on how many times you already went through the loop", I'm supposed to magically read your mind and know that you don't actually object to what you say you object to, but to something completely different? -- Steven. From iddw at hotmail.com Wed Nov 30 12:53:31 2005 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 30 Nov 2005 11:53:31 -0600 Subject: Quene References: <1133372324.562281.128910@g47g2000cwa.googlegroups.com> Message-ID: On 30 Nov 2005 09:38:44 -0800 in comp.lang.python, "Tuvas" wrote: >I am trying to write a function that holds a variable-length quene. The >quene has 2 bits of information. At some point, I would like to remove >bits of this quene, when they are completed. Is there a way to do this >with something as follows? > the following might work... >quene=[] >quene.append((4,2)) >quene.append((3,6)) >if(4 in quene): #Shows false, what's the correct syntax to >show true? found = [t for t in queue if t[0] == 4] if found: > remove 4 from quene #(Not python code, not sure how to do this...) queue.remove(found[0]) HTH, -=Dave -- Change is inevitable, progress is not. From thomas.weholt at gmail.com Tue Nov 22 07:07:36 2005 From: thomas.weholt at gmail.com (Thomas W) Date: 22 Nov 2005 04:07:36 -0800 Subject: Using gettext to provide different language-version of a script Message-ID: <1132661256.664435.311520@g14g2000cwa.googlegroups.com> I'm trying to wrap my head around the docs at python.org related to the gettext-module, but I'm having some problem getting it to work. Is there any really simple, step-by-step on how to use this module available? This is my script so far : import gettext gettext.install('test2', '.', unicode=1) lang1 = gettext.translation('test2', languages=['no']) print _('writing a log to file') in the folder where the test2.py-script lives I've created a folder-structure like ./locales/NO/LC_MESSAGES/messages.mo the messages.mo-file I've created using the scripts in the \Tools\i18l\-folder by running : python pygettext.py test2.py and renaming the generated messages.pot-file to messages.po, and editing it to look like : # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR , YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2005-11-22 13:02+W. Europe Standard Time\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: pygettext.py 1.5\n" #: test2.py:5 msgid "writing a log to file" msgstr "skriver logg til fil" and then run python msgfmt.py messages.po and moving it to ./locales/NO/LC_MESSAGES/messages.mo When I run python test2.py it gives me this error : Traceback (most recent call last): File "C:\Program Files\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Program Files\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Program Files\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run exec cmd in globals, locals File "C:\Program Files\Python24\Tools\i18n\test2.py", line 4, in ? lang1 = gettext.translation('test2', languages=['no']) File "C:\Program Files\Python24\lib\gettext.py", line 456, in translation raise IOError(ENOENT, 'No translation file found for domain', domain) IOError: [Errno 2] No translation file found for domain: 'test2' Hmmm ... any hints? Thomas From steve at REMOVEMEcyber.com.au Thu Nov 17 02:37:11 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 17 Nov 2005 18:37:11 +1100 Subject: is parameter an iterable? References: <1132081308.036144.13720@g49g2000cwa.googlegroups.com><1132082783.353359.69900@g49g2000cwa.googlegroups.com> Message-ID: <437C3327.3090400@REMOVEMEcyber.com.au> Fredrik Lundh wrote: > Steven D'Aprano wrote: > > >>This means we're no longer assuming what the error message will be, >>which makes our code a lot more future-proof and implementation-proof: if >>some version of Python changes the error string from "iteration over >>non-sequence" to something else, the code should continue to work >>correctly. > > > Alex has already posted the right way to do this. Has he? Where and when? Is my crystal ball broken again? I hate it when I miss the one Usenet post all the cool kids are talking about. > can you please stop Can I please stop what? Using punctuation and capitalization correctly? Learning? Thinking for myself? Posting to Usenet? Programming in Python? Your post is unclear. -- Steven. From fredrik at pythonware.com Wed Nov 9 02:01:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Nov 2005 08:01:03 +0100 Subject: Cursor Position. References: Message-ID: "Samantha" wrote: > Looking at the goto(xy) thread. > Is there a way to get the X,Y position from a cursor click and then use the > position to apply something like a water mark on an image at that position? All GUI toolkits can handle the "click here" part. Which one are you using ? to apply water marks, use PIL: http://www.pythonware.com/products/pil From fperez.net at gmail.com Wed Nov 9 23:59:56 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 09 Nov 2005 21:59:56 -0700 Subject: need an example of Python numarray to C++ and back again, Boost / SWIG? References: <1131547248.473442.313820@g47g2000cwa.googlegroups.com> Message-ID: PL wrote: > I want to pass a 2D array from Python to C++, manipulate it in C++ (for > example, add 1 to each element) and pass it back to Python. > > With these building blocks I will be able to figure out all the rest of > what I need to do for my project. I am very familiar with Python, but > less so with C++ and Boost or SWIG. > > Does anyone have an example with all steps that I can follow? More > specifically I am looking for the C++ code, ".i" file for SWIG and/or > the analagous setup files that Boost would need to do this. You may want to look into weave.inline or weave.blitz, from scipy. Typemaps for conversion to blitz++ were recently posted on the scipy list: http://aspn.activestate.com/ASPN/Mail/Message/numpy-discussion/2883831 In particular look at Stefan's post. For info on weave, here you can find some old slides and example code: http://amath.colorado.edu/faculty/fperez/python/ Cheers, f From ggrp1.20.martineau at dfgh.net Wed Nov 30 19:34:30 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 30 Nov 2005 16:34:30 -0800 Subject: importing a method References: <1133134698.814405.281630@f14g2000cwb.googlegroups.com> <1133191986.034689.59090@g14g2000cwa.googlegroups.com> <1h6q906.wbfwmtxr0zjN%aleax@mail.comcast.net> <1133196211.468791.220480@g47g2000cwa.googlegroups.com> <1h6r2u7.tfin37njer33N%aleax@mail.comcast.net> Message-ID: <1133397270.119967.56990@g14g2000cwa.googlegroups.com> You're not missing anything -- it's my own [mis-]understanding that descriptors would only work with new-style classes, not the old-style ones used in the OP's example. However your example certainly proves that is not the case, even if you go one step further and call the bound method/function: >>> o.z() <__main__.old instance at 0x009D5F30> So I stand corrected -- thank you. Best, -Martin ============== Alex Martelli wrote: > Martin Miller wrote: > > > I'd like to point out to the OP that using a function's __get__ method > > this way only works with new-style classes and their instances...not > > with the example in the shown in original post. > > Uh, why not? > > >>> class old: pass > ... > >>> def f(self): print self > ... > >>> o=old() > >>> o.z = f.__get__(o, old) > >>> o.z > > > >>> > > There's a million reason to avoid using old-style classes in new code, > but it doesn't seem to me that this is one of them. What am I missing? > > > Alex From mensanator at aol.com Sun Nov 6 13:06:03 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 6 Nov 2005 10:06:03 -0800 Subject: GMPY: divm() memory leak revisited In-Reply-To: <1h5kl68.1qpifts1rxnrlpN%aleax@mail.comcast.net> References: <1131151958.314488.310400@z14g2000cwz.googlegroups.com> <1h5kl68.1qpifts1rxnrlpN%aleax@mail.comcast.net> Message-ID: <1131300363.757210.276520@z14g2000cwz.googlegroups.com> Alex Martelli wrote: > mensanator at aol.com wrote: > ... > > Unfortunately, I don't have any means of testing this theory. > > Yep -- I reproduced the memory leak you mentioned, and easily fixed it > (exactly as you suggest) in the current CVS version of gmpy (meant to be > "1.01 release candidate"). I need to fix some other pending bugs, then > remind myself of how the (expl.del) one makes a release on Sourceforge, > then it shd be fine That's great! >(except for Windows -- I have no Windows development > system around to do anything... Mac and Linux only). Well, I hope someone makes a Windows binary once you publish ver 1.01. I downloaded all that MSVC command line stuff (over 800 MB!) but am not looking forward to trying to get it to work. > > One of the bugs I must still get around to examining is the algorithmic > one you mention in your next post, btw. > > Thanks for your diagnostic and debugging help. BTW, should you wish to > mail me privately, I'm "aleaxit" (my favourite userid, with or w/o the > trailing "it" depending on service -- see www.aleax.com to understand > why that is the case), and the best way to reach me these days is > through "gmail.com" . > > > Alex From pu at pmville.com Thu Nov 17 02:46:07 2005 From: pu at pmville.com (Ask) Date: Thu, 17 Nov 2005 18:46:07 +1100 Subject: GTK for windows and Linux Message-ID: <437c3560@news1.veridas.net> Hi All, Can someone please tell me what I need to use GTK with python for windows and Linux? Any links to the appropriate installations would be greatly appreciated as I don't know what I need... GIMP... GTK+ etc Thanks for any advice Pauly From msj at infoserv.dk Wed Nov 16 02:45:51 2005 From: msj at infoserv.dk (Martin) Date: Wed, 16 Nov 2005 08:45:51 +0100 Subject: Python/ASP local characters and 500 server error Message-ID: <437ae3b1$0$46986$edfadb0f@dread15.news.tele.dk> Using Python / ASP on a IIS server with Mark Hammond's win32 extensions, i have the following problem. All occurences of local characters (fx. danish ???) in comments or in strings result in a HTTP/1.1 500 Server Error. Is there a solution to this problem? /Martin From robert.kern at gmail.com Sat Nov 5 23:41:26 2005 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 05 Nov 2005 20:41:26 -0800 Subject: Multiples of a number In-Reply-To: References: <17d4ae400511051621w718075d5i62ab1cd48748e3eb@mail.gmail.com> Message-ID: Steven D'Aprano wrote: > Another way is, if you aren't doing anything *except* counting for the > other 99 values of x, just skip them completely: > > fox x in range(20): > do_something(x*100) > > Ivan, what are you trying to do? Presumably he's doing something substantive on every 1-increment; he just needs to do something extra (like print some diagnostic information) on every 100-increment. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From darkchild50 at gmail.com Fri Nov 11 22:35:41 2005 From: darkchild50 at gmail.com (darkchild50 at gmail.com) Date: 11 Nov 2005 19:35:41 -0800 Subject: changeing users on linux Message-ID: <1131766541.519931.313710@g44g2000cwa.googlegroups.com> how would i go about makeing a program in python that asks for username and password and changes to that user? From jacob.miles at gmail.com Tue Nov 29 01:03:42 2005 From: jacob.miles at gmail.com (jacob.miles at gmail.com) Date: 28 Nov 2005 22:03:42 -0800 Subject: SQLObject transaction rollback not working Message-ID: <1133244222.731035.201540@f14g2000cwb.googlegroups.com> Hello. I'm trying to wrap a function call in a transaction, but when I intentionally throw an exception in the middle of the function it doesn't actually roll back the transaction. The debug output says 1/ROLLBACK, without any 1/COMMITs in there, but when I view the data in the command-line mysql utility the changes have been made. This is the code I'm using to connect to the mysql database and to wrap the function call in a transaction. After that I've invluded the testUpdate method I'm using, and after that the python conversation that ensued. Does anyone see what I'm doing wrong? --- sqlutil.py: from sqlobject import * def connect(): """ Connects SQLObject to the dev database on localhost. """ connectionString = "mysql://admin at localhost/mc_image_library_dev?debug=1" connection = connectionForURI (connectionString) sqlhub.processConnection = connection def wrapInTransaction (func, *args, **kw): """ Got this from the SQLObject mailing list. Calls the given func with the given args and keyword assignments within a db transaction. Rolls back if an exception is thrown, otherwise commits. """ old_conn = sqlhub.getConnection() conn = old_conn.transaction() sqlhub.processConnection = conn try: try: value = func(*args, **kw) except: conn.rollback() raise else: conn.commit() return value finally: sqlhub.processConnection = old_conn ------------------ ----- test.py: from ImageCategory import * def testUpdate (newName, username, fail): category = ImageCategory.get(1) category.name = newName category.updateLastChanged (username) if fail: raise Exception ('spam', 'eggs') ----------------- ------ The python conversation: >>> import sqlutil >>> sqlutil.connect() >>> import test >>> sqlutil.wrapInTransaction (test.testUpdate, 'Animals', 'jake', True) 1/QueryOne: SELECT last_changed_by, last_changed_date, name FROM image_category WHERE id = 1 1/Query : UPDATE image_category SET name = 'Animals' WHERE id = 1 1/Query : UPDATE image_category SET last_changed_by = 'jake' WHERE id = 1 1/Query : UPDATE image_category SET last_changed_date = '2005-11-29 00:36:22' WHERE id = 1 1/ROLLBACK: Traceback (most recent call last): File "", line 1, in ? File "sqlutil.py", line 22, in wrapInTransaction value = func(*args, **kw) File "test.py", line 8, in testUpdate raise Exception ('spam', 'eggs') Exception: ('spam', 'eggs') ------------ After all this, the mysql utility shows that the update did take effect. Any thoughts? - Jake From fuzzyman at gmail.com Wed Nov 23 03:43:48 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Nov 2005 00:43:48 -0800 Subject: Why are there no ordered dictionaries? In-Reply-To: <4383d564.508728452@news.oz.net> References: <1132560333.366063.51130@g49g2000cwa.googlegroups.com> <1132566878.521180.115790@g43g2000cwa.googlegroups.com> <4382592b.411391199@news.oz.net> <1132657667.801751.166830@o13g2000cwo.googlegroups.com> <43835bff.477651596@news.oz.net> <4383d564.508728452@news.oz.net> Message-ID: <1132735428.485669.153090@g43g2000cwa.googlegroups.com> There is already an update method of course. :-) Slicing an ordered dictionary is interesting - but how many people are actually going to use it ? (What's your use case) You can already slice the sequence atribute and iterate over that. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From has.temp2 at virgin.net Fri Nov 18 10:58:11 2005 From: has.temp2 at virgin.net (has) Date: 18 Nov 2005 07:58:11 -0800 Subject: HTML generation vs PSP vs Templating Engines References: <1132158690.299954.90920@g14g2000cwa.googlegroups.com> Message-ID: <1132329491.590169.265630@g44g2000cwa.googlegroups.com> pkassianidis at gmail.com wrote: > Could someone that has used all the different ways mentioned above for > dynamic HTML > content, suggest what the pros and cons of the different methods are? Not used them all - as you say, there's a plethora of options - but to give you a general idea of the territory... First choice you have is between HTML generators vs. HTML templating systems: - HTML generators create all markup from scratch. Useful when producing arbitrary markup/layout whose entire structure must be determined programmatically, e.g. applying paragraph and character styling to a big chunk of text, creating arbitrary HTML form layouts based on other input. Examples: htmlgen (crusty, HTML 3.1-era), Nevow's Stan engine. - HTML templates insert individual items of data into a mostly static block of HTML markup written in advance by e.g. a graphic designer. Useful when creating documents that are fairly regular in structure - most fall into this category - as it's much easier to create the repetitious parts using standard HTML editing tools than write code to produce it all programmatically. Sometimes you might combine the two methods, using an HTML generator to create sections of markup from arbitrary input which is then inserted into a full-page template to produce the finished HTML document. Assuming a templating-based solution is the appropriate choice for you (which it most likely is), there are three general approaches to choose from: 1. Systems that embed markup in code. This is a fairly small category. It's fairly programmer-friendly since you've direct access to all language features, but hostile to web designers as you have to pull your HTML markup apart and insert it into program code to produce the final template, making it a pain to modify that markup later. Examples: ad-hoc solutions using Python's string interpolation, the Quixote framework's built-in templating support, Karrigell (though it supports some aspects of approach 2 as well). 2. Systems that embed code in markup. This is the most common category with a fair amount of variety and capabilities to choose from. Lots of obviously PHP/ASP-inspired designs. Two sub-categories: systems that embed standard Python code, e.g. PSP, and systems that embed a custom language, e.g. Cheetah. Some provide no restrictions on what you can get up to within embedded code, others restrict functionality to enforce a strict separation between presentation logic and model logic. Embedding styles also vary: some mix code statements and markup directly (e.g. Cheetah), some embed code statements in special <%...%> style tags (e.g. PSP), some hide all code within HTML tag attributes (e.g. TAL, Kid), providing varying degrees of designer-friendliness as a result. 3. DOM-style systems. This is a more recent arrival and a smaller category. These systems completely separate markup from presentation logic. Selected HTML elements are flagged using specific named tag attributes (e.g. id="somename") or simple compiler directives, e.g. (nevow:render="somename"); the template is then compiled into a simple templating-oriented (i.e. not w3c) DOM, allowing these elements to be manipulated programmatically by standard Python scripts. Very designer and developer friendly, although less experienced programmers may find the higher level of abstraction involved a bit offputting. Examples: PyMeld, HTMLTemplate [1], Nevow.Render. For a fairly extensive list of available systems, see . Unfortunately they're not well categorised there, but I can't think of a better, up-to-date list off the top of my head and most will provide decent overviews so it shouldn't take too long to take a quick look at each. Note that some templating engines are embedded into larger web programming frameworks and may or may not be usable independently. Conversely, some web frameworks may be coupled to a specific templating system, while others allow you to choose your own. HTH has -- [1] Disclaimer: I wrote HTMLTemplate. Also, shameless plug: From alanmk at hotmail.com Mon Nov 7 17:32:51 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 07 Nov 2005 22:32:51 +0000 Subject: Map of email origins to Python list In-Reply-To: <1131400439.260344.19880@g44g2000cwa.googlegroups.com> References: <1131390365.721288.272070@g47g2000cwa.googlegroups.com> <1131396963.363256.12250@g47g2000cwa.googlegroups.com> <1131400439.260344.19880@g44g2000cwa.googlegroups.com> Message-ID: [Alan Kennedy] >>So presumably "chcgil" indicates you're in Chicago, Illinois? [mensanator at aol.com] > Yes, but why, then, is my name logged into Mountain View, CA? Presumably the creators of the map have chosen to use a mechanism other than NNTP-Posting-Host IP address to geolocate posters. Claire, what mechanism did you use? > That justifies my claim of "all the more stupid", doesn't it? Well, to me it just says that the map creation software has some bugs that need fixing. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From fredrik at pythonware.com Thu Nov 24 09:17:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Nov 2005 15:17:21 +0100 Subject: Writing big XML files where beginning depends on end. References: Message-ID: Magnus Lycka wrote: > We're using DOM to create XML files that describes fairly > complex calculations. The XML is structured as a big tree, > where elements in the beginning have values that depend on > other values further down in the tree. Imagine something > like below, but much bigger and much more complex: > > > > 7 > > 2 > 1 > > > > 5 > > what's the typical overall structure for this tree ? is it short and wide, or tall and narrow ? or in other words, if you would extract all /node/node elements (that is, node elements just under the document root) from a large file, would you typically get a long list with small nodes, or a short list with a few large nodes ? From apardon at forel.vub.ac.be Fri Nov 4 04:26:07 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Nov 2005 09:26:07 GMT Subject: Class Variable Access and Assignment References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <86oe51inmz.fsf@bhuda.mired.org> Message-ID: Op 2005-11-03, Mike Meyer schreef : > Antoon Pardon writes: >>> What would you expect to get if you wrote b.a = b.a + 2? >> I would expect a result consistent with the fact that both times >> b.a would refer to the same object. > > Except they *don't*. This happens in any language that resolves > references at run time. Python doesn't resolve references at run time. If it did the following should work. a = 1 def f(): a = a + 1 f() But letting that aside. There is still a difference between resolving reference at run time and having the same reference resolved twice with each resolution a different result. > Changing that would be changing a fundamental > - and *important* - feature of Python. Arbitrary restrictions to > prevent a single case of this from doing something people who aren't > used to suvh behavior are kludges, and would constitute a wart on the > language, pure and simple. Python already has its warts. If you want to argue that fixing this would make a bigger wart then the wart it is now. Fine I will accept that. > If you think this is bad, you should consider Jensen's device. It uses > call-by-name, which Python doesn't have. Actually, I would have thought it very interesting should python have provided some choice in parameter semantics. >> I think it even less sane, if the same occurce of b.a refers to two >> different objects, like in b.a += 2 > > That's a wart in +=, nothing less. The fix to that is to remove += > from the language, but it's a bit late for that. > > <11mi8n2t39q2534@corp.supernews.com> <11mj21gr6rjgc65@corp.supernews.com> Message-ID: <86ll06jr79.fsf@bhuda.mired.org> Grant Edwards writes: > On 2005-11-02, Neil Schemenauer wrote: >> Grant Edwards wrote: >> Using data from the Internet is just a bad idea. > I think that the timing of certain network events is one of the > Linux kernel's entropy sources. BSD as well. The key word is "one". While network events don't make a good source of random data, proplery combining such sources can create good random data. Randomness is a deep subject. You should use a library built by experts (and appropriate for your application) rather than try and build one yourself. Most modern Unix systems have a /dev/random that qualifies for a lot of applications. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From noway at nospam.com Tue Nov 1 16:10:21 2005 From: noway at nospam.com (CppNewB) Date: Tue, 01 Nov 2005 21:10:21 GMT Subject: Python's website does a great disservice to the language References: Message-ID: <1RQ9f.12985$8K4.11726@tornado.rdc-kc.rr.com> "John J. Lee" wrote in message news:mailman.2805.1130877037.509.python-list at python.org... > Robert Boyd writes: > [...] >> rounded corners. The Python site is clean and to-the-point. I guess I >> could >> admin that the various Python logos look dated, but that's about it. Oh, >> and > [...] > > I love the logos! Exactly my sentiment. I know Python's capabilities and I am more than satisfied. I was introduced by a friend, not the website. But to the masses of asses out there that are quickly evaluating their development choices and jumping from Visual Studio to Delphi's website to Ruby on Rail's website, the aesthetic welcome will be worn out once they get to python.org. From Michael.J.Fromberger at Clothing.Dartmouth.EDU Wed Nov 2 18:38:17 2005 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Wed, 02 Nov 2005 18:38:17 -0500 Subject: Burrows-Wheeler (BWT) Algorithm in Python References: <1130919309.381711.305450@f14g2000cwb.googlegroups.com> Message-ID: In article <1130919309.381711.305450 at f14g2000cwb.googlegroups.com>, "DENG" wrote: > Hi, all > > I've used Python Bz2 module for times and want to kown something about > Burrows-Wheeler (BWT) algorithm, the Bz2 module is wrriten in C, is > there a version in Python too? > > BWT > http://gatekeeper.dec.com/pub/DEC/SRC/research-reports/abstracts/src-rr-124.ht > ml > Python Bz2 module > http://labix.org/python-bz2 It is perfectly possible to implement the BWT in Python. I can send you a Python implementation I wrote, if you like; but if you're interested in better understanding how the transform works, I would recommend you try writing your own implementation. It's not very difficult to do, though for large inputs you may find performance to be an issue. Mark Nelson wrote a nice user-friendly article on the BWT for the Sep. 1996 issue of Dr. Dobbs, you might have a look: http://www.dogma.net/markn/articles/bwt/bwt.htm I hope this helps you get started. -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From mackstevenson at hotmail.com Mon Nov 14 21:30:08 2005 From: mackstevenson at hotmail.com (MackS) Date: 14 Nov 2005 18:30:08 -0800 Subject: modifying small chunks from long string References: <1131951470.660501.68710@g44g2000cwa.googlegroups.com> <*firstname*nlsnews-EFF0CD.11565014112005@news.verizon.net> Message-ID: <1132021808.058509.100340@g49g2000cwa.googlegroups.com> Thank you all for your great help. One of the few things better than python is the knowledgeable community around it. : ) Regards, Mack From *firstname*nlsnews at georgea*lastname*.com Wed Nov 23 23:56:58 2005 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Thu, 24 Nov 2005 04:56:58 GMT Subject: Mixed types and variants References: <1132781170.172321.321750@z14g2000cwz.googlegroups.com> Message-ID: <*firstname*nlsnews-1062E8.23570323112005@news.verizon.net> In article <1132781170.172321.321750 at z14g2000cwz.googlegroups.com>, bearophileHUGS at lycos.com wrote: ... > - Maybe someone here can suggest some other variant type, or some other > solution. Pyrex? Pyrex is mostly like Python with the possibility of C types. It handles mixed types just like Python, and the C code it produces is sort of readable. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From http Wed Nov 2 08:33:44 2005 From: http (Paul Rubin) Date: 02 Nov 2005 05:33:44 -0800 Subject: Most efficient way of storing 1024*1024 bits References: Message-ID: <7x64rbi37r.fsf@ruckus.brouhaha.com> "Tor Erik S?nvisen" writes: > I need a time and space efficient way of storing up to 6 million bits. Time > efficency is more important then space efficency as I'm going to do searches > through the bit-set. Umm, what kind of searches do you want to do? For speed you want to use built-in functions wherever you can, string.find and that kind of thing. So choose your data format accordingly. From lycka at carmen.se Thu Nov 3 09:26:17 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 03 Nov 2005 15:26:17 +0100 Subject: How to print random strings In-Reply-To: <1130978067.685487.194530@g44g2000cwa.googlegroups.com> References: <1130978067.685487.194530@g44g2000cwa.googlegroups.com> Message-ID: theboringdays at gmail.com wrote: > So how would I go about have 5 strings, and running a program that will > randomly pick one of those to print? >>> import random >>> text = "Perhaps reading the manual is a good idea?".split() >>> random.choice(text) 'is' >>> random.choice(text) 'reading' >>> random.choice(text) 'a' >>> random.choice(text) 'the' >>> random.choice(text) 'Perhaps' See http://docs.python.org/lib/module-random.html From jojoba at gmail.com Wed Nov 30 13:12:08 2005 From: jojoba at gmail.com (jojoba at gmail.com) Date: 30 Nov 2005 10:12:08 -0800 Subject: an intriguing wifi http server mystery...please help In-Reply-To: References: <1133324893.968023.79050@z14g2000cwz.googlegroups.com> <438D3186.2070800@ulmcnett.com> <1133372232.737182.98410@g43g2000cwa.googlegroups.com> Message-ID: <1133374328.152569.127690@g14g2000cwa.googlegroups.com> Hello again! Heres the CLIENT info you requested: =========================================================================== Interface List 0x1 ........................... MS TCP Loopback interface 0x20002 ...00 09 5b 41 0c b7 ...... NETGEAR MA311 PCI Adapter - Packet Scheduler Miniport =========================================================================== =========================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.0.1 192.168.0.107 30 127.0.0.0 255.0.0.0 127.0.0.1 127.0.0.1 1 192.168.0.0 255.255.255.0 192.168.0.107 192.168.0.107 30 192.168.0.107 255.255.255.255 127.0.0.1 127.0.0.1 30 192.168.0.255 255.255.255.255 192.168.0.107 192.168.0.107 30 224.0.0.0 240.0.0.0 192.168.0.107 192.168.0.107 30 255.255.255.255 255.255.255.255 192.168.0.107 192.168.0.107 1 Default Gateway: 192.168.0.1 =========================================================================== Persistent Routes: None Here's the SERVER info you requested: =========================================================================== Interface List 0x1 ........................... MS TCP Loopback interface 0x40003 ...00 d0 59 49 2e 2c ...... LAN-Express IEEE 802.11 PCI Adapter =========================================================================== =========================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.0.1 192.168.0.105 30 127.0.0.0 255.0.0.0 127.0.0.1 127.0.0.1 1 192.168.0.0 255.255.255.0 192.168.0.105 192.168.0.105 30 192.168.0.105 255.255.255.255 127.0.0.1 127.0.0.1 30 192.168.0.255 255.255.255.255 192.168.0.105 192.168.0.105 30 224.0.0.0 240.0.0.0 192.168.0.105 192.168.0.105 30 255.255.255.255 255.255.255.255 192.168.0.105 192.168.0.105 1 Default Gateway: 192.168.0.1 =========================================================================== Persistent Routes: None (hope the text-formatting doesn't make it too unreadable!) Note: this is for the condition that is SLOW. Hope this helps Thanks again, jojoba From sybrenUSE at YOURthirdtower.com.imagination Wed Nov 9 10:01:30 2005 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 9 Nov 2005 16:01:30 +0100 Subject: How to use generators? References: Message-ID: Ian Vincent enlightened us with: > I have never used generators before but I might have now found a use > for them. I have written a recursive function to solve a 640x640 > maze but it crashes, due to exceeding the stack. The only way > around this I can think of is to use Generator but I have no idea > how to. A better way is to use a queue. I had the same problem with a similar piece of code. The only thing why you're using a stack is to move to the "next" point, without going back to a visited point. The non-recursive solution is to mark all visited points as such, only consider non-visited points, and then append the coordinates to a list of points yet to visit. Then keep looping over your code until either you found the solution to the maze or there are no points left to visit. 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 durumdara at mailpont.hu Mon Nov 28 12:15:25 2005 From: durumdara at mailpont.hu (durumdara at mailpont.hu) Date: Mon, 28 Nov 2005 18:15:25 +0100 Subject: pcm format to wav... Message-ID: <438B3B2D.8060305@mailpont.hu> Hi ! I have WinXP. I want to convert my PySonic recorded (raw) pcm format files to wav files. How can I do it ? Please help me ! dd From saruis at tiscali.it Wed Nov 2 04:19:14 2005 From: saruis at tiscali.it (DDany) Date: 2 Nov 2005 01:19:14 -0800 Subject: Problem with py2exe In-Reply-To: References: <1130705244.768027.147710@g14g2000cwa.googlegroups.com> Message-ID: <1130923154.591382.262410@f14g2000cwb.googlegroups.com> Hi Miki, I solved this first problem, thank you! I was convinced to done things you suggested me, but... it wasn't!!! I changed the access type of MSVCR71.dll and all went ok! Thank you once again for your interest, bye! P.S Thank you for your final note too, next time I'll make a better subject! Miki Tebeka wrote: > Hello DDany, > My guess in the MSVCR71.dll is a read-only file in system32 and when py2exe > tries to copy it the 2'nd time it fails. > > Either change MSVCR71.dll to read-write in system32 or delete "dist" before > calling to py2exe. > > One final note: > You subject line could have been better, see > http://www.catb.org/~esr/faqs/smart-questions.html. > > Bye. > -- > ------------------------------------------------------------------------ > Miki Tebeka > http://tebeka.bizhat.com > The only difference between children and adults is the price of the toys From steve at holdenweb.com Wed Nov 23 03:15:07 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Nov 2005 08:15:07 +0000 Subject: mxODBC sql MSAccess In-Reply-To: <1132621839.128441.49430@f14g2000cwb.googlegroups.com> References: <1132621839.128441.49430@f14g2000cwb.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Hello, I'm new to python and trying to get records from an MSAccess > database using mxODBC. It works, but the output is not formatted the > way I want it. > > Here's the script: > > import mx.ODBC.Windows as odbc > > driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access > Databases/Quotations2005' > > conn = odbc.DriverConnect(driv) > c = conn.cursor() > c.execute ("SELECT Author, Topic1, Topic2, Quote FROM QuotesToTxt WHERE > Author LIKE 'Mencken%'") > > rows = c.fetchall() > for r in rows: > print r > > And here's what I get: > > ('Mencken, H.L.', 'Americans', 'Democracy', 'Democracy is the theory > that the common people know what they want, and deserve to get it good > and hard.') > ('Mencken, H.L.', 'Conscience', 'Mother-In-Law', 'Conscience is a > mother-in-law whose visit never ends. The inner voice which warns us > that someone may be looking.') > > Where are the parenthese and single quotes coming from? SQL or mxODBC? > And how can I get just simple tab-delimited records with a standard > carriage return separating the records? > > Thanks so much for any help. > > bs > Well you know that answer now. You might also consider using the recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 to give you the column titles and so on. 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 fredrik at pythonware.com Wed Nov 23 03:27:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Nov 2005 09:27:47 +0100 Subject: user-defined operators: a very modest proposal References: <4383C386.5040909@kzoo.edu> Message-ID: Joseph Garvin wrote: > >Jeff Epler's proposal to use unicode operators would synergise most > >excellently with this, allowing python to finally reach, and even surpass, > >the level of expressiveness found in languages such as perl, APL and > >INTERCAL. > > > What do you mean by unicode operators? Link? a few messages earlier in the thead you're posting to. if your mail or news provider is dropping messages, you can read the group via e.g. http://news.gmane.org/gmane.comp.python.general jeff's proposal is here: http://article.gmane.org/gmane.comp.python.general/433247 From fredrik at pythonware.com Wed Nov 2 14:41:01 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Nov 2005 20:41:01 +0100 Subject: Filepath string manipulation help References: <1130959950.485233.230230@z14g2000cwz.googlegroups.com> Message-ID: "mjakowlew"wrote: > filepath='c:\documents\web\zope\file.ext' > > I need to extract everthing after the last '\' and save it. that string doesn't contain what you think it does: >>> filepath='c:\documents\web\zope\file.ext' >>> filepath 'c:\\documents\\web\\zope\x0cile.ext' >>> print filepath c:\documents\web\zope?ile.ext if you fix that, you can use os.path.basename() to strip off the last part: >>> filepath=r'c:\documents\web\zope\file.ext' >>> filepath 'c:\\documents\\web\\zope\\file.ext' >>> print filepath c:\documents\web\zope\file.ext >>> import os >>> os.path.basename(filepath) 'file.ext' for more info on Python's string literal syntax, see section 3.1.2 in the Python Tutorial, and this page: http://docs.python.org/ref/strings.html From skip at pobox.com Thu Nov 10 21:48:49 2005 From: skip at pobox.com (skip at pobox.com) Date: Thu, 10 Nov 2005 20:48:49 -0600 Subject: Printing current time to a file In-Reply-To: <1131673473.043969.226000@f14g2000cwb.googlegroups.com> References: <1131673473.043969.226000@f14g2000cwb.googlegroups.com> Message-ID: <17268.1681.491550.826343@montanaro.dyndns.org> zolaris> self.log.write(time.ctime(time.time())) zolaris> But that prints nothing in the file assigned to log. Is there zolaris> something I should be doing extra? There's no newline in there. You probably need to flush the file: self.log.write(time.ctime(time.time())) self.log.flush() You might want to write a newline after the time as well. If the logfile is line-buffered that will also provoke a flush. Skip From cochrane at esscc.uq.edu.au Sun Nov 6 20:06:19 2005 From: cochrane at esscc.uq.edu.au (Paul Cochrane) Date: Mon, 07 Nov 2005 11:06:19 +1000 Subject: Running autogenerated code in another python instance References: <43685941.1593033671@news.oz.net> Message-ID: On Thu, 03 Nov 2005 19:56:48 +0000, Tom Anderson wrote: > On Thu, 3 Nov 2005, Paul Cochrane wrote: > >> On Wed, 02 Nov 2005 06:33:28 +0000, Bengt Richter wrote: >> >>> On Wed, 2 Nov 2005 06:08:22 +0000 (UTC), Paul Cochrane wrote: >>> >>>> I've got an application that I'm writing that autogenerates python >>>> code which I then execute with exec(). I know that this is not the >>>> best way to run things, and I'm not 100% sure as to what I really >>>> should do. I've had a look through Programming Python and the Python >>>> Cookbook, which have given me ideas, but nothing has gelled yet, so I >>>> thought I'd put the question to the community. But first, let me be a >>>> little more detailed in what I want to do: > Paul, this is a rather interesting problem. There are two aspects to it, > which i believe are probably separable: getting instructions from the > client to the server, and getting data back from the server to the client. > The former is more complex, i think, and what's attracted the attention so > far. Tom, thanks heaps for your reply! > The first thing i'd say is that, while eval/exec is definitely a code > smell, that doesn't mean it's never the right solution. If you need to be > able to express complex things, python code might well be the best way to > do it, and the best way to evaluate python code is eval/exec. After looking at the problem a bit more I've come up with a simpler solution to the problem I initially posted; and it involves exec. I've realised that what I've been doing wrong is to compile the code first before I exec it. If I just exec the generated code (within a predefined namespace) then pyvisi does all of the things I want it to do without needing separate processes for generating and rendering the code. This has also solved my data passing problem. I now just need to pass a reference to the data into the namespace where I'm running the generated code and it all works really nicely. Basically the problem had been staring me in the face for ages and I just hadn't seen it. (duh!) >>> It's a little hard to tell without knowing more about your user input >>> (command language?) syntax that is translated to or feeds the process >>> that "autogenerates python code". >> >> It's basically just a command language I guess. > > Hang on - the stuff that the user writes is what you're calling "pyvisi > code", is that right? That doesn't look like 'just a command language', > that looks like python, using a library you've written. Or is there > another language, the "just a command language", on top of that? You're right, it isn't a command language (I looked up the cmd module in Python in a Nutshell and then realised that a large part of my reply was in the "I guess" part). It is just python code that is being run. > > And what you call "vtk-python code" - this is python again, but using > the renderer's native library, right? That's correct. > > And you generate the vtk-python from the pyvisi-python by executing the > pyvisi-python, there being (pluggable renderer-specific) logic in the > guts of your pyvisi classes to emit the vtk-python code, right? You're > not parsing anything? No parsing going on. Just a translation of high-level ideas into the low level of the renderer underneath. > >>> There are lots of easy things you could do without generating and >>> exec-ing python code per se. >> >> I'd love to know of other options. I like the idea of generating the >> code one would have to write for a particular renderer so that if the >> user wanted to, they could use the autogenerated code to form the basis >> of a specific visualisation script they could then hack themselves. > > If you want vtk-python code as an intermediate, i think you're stuck > with eval/exec [1]. So do I. And as I said above, it seems to have simplified my problem significantly. I've also managed to speed the code up as well! Thanks heaps for the rest of your comments and suggestions. They've been really helpful for me to see alternative and probably cleaner ways of doing what I want to do. > To be honest, i'd go with exec. :-) Again, thanks for your help, I really do appreciate it. Paul From http Wed Nov 30 05:20:51 2005 From: http (Paul Rubin) Date: 30 Nov 2005 02:20:51 -0800 Subject: sha1,256,512 on files References: Message-ID: <7xzmnme8sc.fsf@ruckus.brouhaha.com> "durumdara at mailpont.hu" writes: > I see that Python supports the sha-1. But I need to make sha value in > big files to (swap file, iso-s, etc.). Possible that file size more > than 2 GB, so I cannot read as string... > How to get the sha value of a file ? Use the sha.update method. Something like: ctx = sha.new() while True: x = f.read(16384) if not x: break ctx.update(x) hash = ctx.digest() > How to generate sha-256, or sha-512 values ? There are some modules around for this. Unless you're trying to interoperate with something that needs them, or have some other reason to want them, I wouldn't bother. From vinjvinj at gmail.com Mon Nov 7 21:55:07 2005 From: vinjvinj at gmail.com (vinjvinj) Date: 7 Nov 2005 18:55:07 -0800 Subject: Using python for writing models: How to run models in restricted python mode? In-Reply-To: <86oe4w9kfl.fsf@bhuda.mired.org> References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> <86oe4w9kfl.fsf@bhuda.mired.org> Message-ID: <1131418507.281563.213670@g14g2000cwa.googlegroups.com> I'm more worried about incompetent users then malicious users. I'm going to take the following steps: 1. My users will be paying a decent amount of money to run models on the compute grid. If they are intentionaly writing malicious code then their account will be disabled. 2. Since their models will be fairly basic. - No imports in the code. - No special charters allowed. - No access to special builtins. The users write functions which get called man many times with different variables. I'm not sure how this would work with the rexec module especially since I'll be passing values to th functions and the functions will be returning either None, yes, or False. 3. Pylint has a pretty cool way to write your onw custom plugins. You can write custom handlers for each sort of available node at: http://www.python.org/doc/current/lib/module-compiler.ast.html this will allow me to compile a module and give users feedback on what is wrong and what is not allowed. 4. I'll set up a test sandbox where the models will be run with a smaller dataaset before then can be pushed into production. if the models pass the sandbox test then they will be run in production. I'm going to have write some custom performance monitoring functions to get notified when some models are running for ever and be able to terminate them. vinjvinj From scott.daniels at acm.org Fri Nov 25 14:00:13 2005 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 25 Nov 2005 11:00:13 -0800 Subject: Singleton and C extensions In-Reply-To: <43870caf$0$17254$4d4eb98e@read.news.fr.uu.net> References: <43870caf$0$17254$4d4eb98e@read.news.fr.uu.net> Message-ID: <43875d98$1@nntp0.pdx.net> Emmanuel Briot wrote: > I am participating in the development of a GPL IDE > https://libre2.adacore.com/gps/ > I am not really good at python, but I was trying to implement the > singleton design pattern in C, so that for instance calling the constructor > ed = Editor ("foo") Fredrik's advice is probably better, but if you must: class Editor(object): table = {} def __new__(klass, name): try: return klass.table[name] except KeyError: klass.table[name] = super(Singled, klass).__new__(klass) return klass.table[name] --Scott David Daniels scott.daniels at acm.org From aahz at pythoncraft.com Mon Nov 28 00:01:49 2005 From: aahz at pythoncraft.com (Aahz) Date: 27 Nov 2005 21:01:49 -0800 Subject: General question about Python design goals References: Message-ID: In article , Christoph Zwerschke wrote: >Aahz wrote: >> Christoph deleted his own attribution: >>> >>>For instance, I just wanted to use the index() method on a tuple which >>>does not work. ... >> >> Because Guido believes that tuples should be primarily used as >> lightweight replacements for C structs. Therefore they have minimal >> functionality. > >But the problem is that the tutorials and manuals give the impression >that the difference between lists and tuples is only mutablity versus >immutability. They don't talk about such considerations and honestly >speaking even now I know that it does seem more plausible for me. Then feel free to submit patches for the docs. PS: If you want further responses from me, please follow standard Usenet quoting conventions (like those above). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair From howardrh at westerncom.net Thu Nov 17 19:39:08 2005 From: howardrh at westerncom.net (hrh1818) Date: 17 Nov 2005 16:39:08 -0800 Subject: GTK for windows and Linux References: <437c3560@news1.veridas.net> Message-ID: <1132274348.764132.141460@g47g2000cwa.googlegroups.com> Chapter 13 in "Beginning Python" by Peter Norton has a good introduction to using GTK to create a GUI. . Howard Ask wrote: > Hi All, > > Can someone please tell me what I need to use GTK with python for windows > and Linux? > > Any links to the appropriate installations would be greatly appreciated as I > don't know what I need... GIMP... GTK+ etc > > Thanks for any advice > > Pauly From aleax at mail.comcast.net Wed Nov 23 01:00:54 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Tue, 22 Nov 2005 22:00:54 -0800 Subject: the name of a module in which an instance is created? References: <5cednUHIc9Ss8h7enZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <1h6g7in.1gsnlzmmwbkt4N%aleax@mail.comcast.net> Steven Bethard wrote: ... > Unfortunately, no, this is basically what I currently have. Instead of > a.name printing 'test', it should print '__main__'. I want the name of > the module in which the *instance* is created, not the name of the > module in which the *class* is created. class metaSB(type): def __call__(cls, *a, **t): result = super(metaSB, cls)(*a, **t) result._insmodnam = sys._getframe(1).f_globals['__name__'] return result and set the class's __metaclass__ to metaSB. Untested code, but the general idea should work. You could try to hack this without a custom metaclass, e.g. by trying sys._getframe in __init__, but that's fragile since the __init__ could be called by a *subclass* in whatever module... Alex From roccomoretti at hotpop.com Tue Nov 15 15:02:47 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 15 Nov 2005 14:02:47 -0600 Subject: Proposal for adding symbols within Python In-Reply-To: <87psp2ao7s.fsf@lucien.dreaming> References: <43762d68$0$4335$626a54ce@news.free.fr> <86psp51qlv.fsf@bhuda.mired.org> <4377077d$0$14034$636a15ce@news.free.fr> <861x1k2628.fsf@bhuda.mired.org> <43771efe$0$29517$626a14ce@news.free.fr> <4377c46a$0$82664$ed2619ec@ptn-nntp-reader03.plus.net> <4378b7e7$0$23008$636a15ce@news.free.fr> <87psp2ao7s.fsf@lucien.dreaming> Message-ID: Bj?rn Lindstr?m wrote: > Steven D'Aprano writes: > > >>Why does the byte string "\x6f\x70\x65\x6e\x65\x64" have intrinsic >>meaning when the int 0 doesn't? It certainly doesn't mean anything to >>non-English speakers. >> >>If all you want is human readable byte strings, then just use them: >> >>class MyFile: >> def open(self): >> self.state = "opened" >> def close(self): >> self.state = "closed" > > > So, I guess no one read my explanation of why this an issue about more > than implementing enums (which is fairly trivial, as we have seen). I did, but I still don't see why it is an argument against using strings. The point you may not appreciate is that (C)Python already uses strings to represent names, as an important part of its introspective abilities. ########################################## >>> import dis >>> def f(): module.klass.method() >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (module) 3 LOAD_ATTR 1 (klass) 6 LOAD_ATTR 2 (method) 9 CALL_FUNCTION 0 12 POP_TOP 13 LOAD_CONST 0 (None) 16 RETURN_VALUE >>> f.func_code.co_names ('module', 'klass', 'method') >>> type(f.func_code.co_names[1]) is type('a') True ############################################## I'll let you dig through the interpreter source to convince yourself that, indeed, the names module, klass, and method are stored internally as true python strings. The same holds for other namespaces - the names are stored as real python strings, in a real python dictionary. ############################################ >>> class c: def foo(self): pass def bar(self): pass def baz(self): pass >>> type(c.__dict__) is type({}) True >>> c.__dict__.keys() ['baz', '__module__', 'foo', 'bar', '__doc__'] >>> type(c.__dict__.keys()[0]) is type('a') True ############################################## P.S. This may change for other implementations of Python, but the fact remains - there is less difference between names and strings than you may first think. From nnorwitz at gmail.com Tue Nov 15 00:54:49 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 14 Nov 2005 21:54:49 -0800 Subject: best way to discover this process's current memory usage, cross-platform? In-Reply-To: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> References: <1h6142i.gbmv0i10f79yqN%aleax@mail.comcast.net> Message-ID: <1132034089.402313.67290@o13g2000cwo.googlegroups.com> Alex Martelli wrote: > > So, I thought I'd turn to the "wisdom of crowds"... how would YOU guys > go about adding to your automated regression tests one that checks that > a certain memory leak has not recurred, as cross-platform as feasible? > In particular, how would you code _memsize() "cross-platformly"? (I can > easily use C rather than Python if needed, adding it as an auxiliary > function for testing purposes to my existing extension). If you are doing Unix, can you use getrusage(2)? >>> import resource >>> r = resource.getrusage(resource.RUSAGE_SELF) >>> print r[2:5] I get zeroes on my gentoo amd64 box. Not sure why. I thought maybe it was Python, but C gives the same results. Another possibiity is to call sbrk(0) which should return the top of the heap. You could then return this value and check it. It requires a tiny C module, but should be easy and work on most unixes. You can determine direction heap grows by comparing it with id(0) which should have been allocated early in the interpreters life. I realize this isn't perfect as memory becomes fragmented, but might work. Since 2.3 and beyond use pymalloc, fragmentation may not be much of an issue. As memory is allocated in a big hunk, then doled out as necessary. These techniques could apply to Windows with some caveats. If you are interested in Windows, see: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/html/UCMGch09.asp Can't think of anything fool-proof though. HTH, n From mikael at isy.liu.se Thu Nov 17 02:44:19 2005 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 17 Nov 2005 08:44:19 +0100 Subject: newbie - How do I import automatically? In-Reply-To: <1132154531.395649.168870@g14g2000cwa.googlegroups.com> References: <1132085329.154028.71780@g47g2000cwa.googlegroups.com> <86y83ppr0h.fsf@bhuda.mired.org> <1132092221.672995.103230@z14g2000cwz.googlegroups.com> <3u0el9Fum367U1@individual.net> <1132154531.395649.168870@g14g2000cwa.googlegroups.com> Message-ID: bobueland at yahoo.com wrote: > I tried to put the line > from btools import * > in several places in PyShell.py > but to now avail. It does not work, IDLE does not execute it??? IDLE definitely executes PyShell.py upon startup, since IDLE does not even appear on the screen if there is an error in that file. The following seems to work for me, in PyShell.py. After importing both sys and os, sys.modules['__main__'].__dict__['os'] = os Then, if I start IDLE, the module os is directly available. HTH /MiO From bokr at oz.net Tue Nov 22 23:07:30 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 23 Nov 2005 04:07:30 GMT Subject: Why are there no ordered dictionaries? References: <861x1ahhqk.fsf@bhuda.mired.org> <1132673952.619481.19780@f14g2000cwb.googlegroups.com> <1h6fycc.1xgt1dk1ywf4baN%aleax@mail.comcast.net> <1132715742.672265.259740@o13g2000cwo.googlegroups.com> Message-ID: <4383e912.513766727@news.oz.net> On 22 Nov 2005 19:15:42 -0800, "bonono at gmail.com" wrote: > >Alex Martelli wrote: >> However, since Christoph himself just misclassified C++'s std::map as >> "ordered" (it would be "sorted" in this new terminology he's now >> introducing), it seems obvious that the terminological confusion is >> rife. Many requests and offers in the past for "ordered dictionaries" >> (e.g. on this group) were also "sorted", NOT "ordered", in this new >> terminology. >> >> Maybe it would therefore be clearer to have the name of the new >> container reflect this, with a specific mention of *insertion* order... >> rather than just call it "ordered" and risk probable confusion. >Um, > >what would be the definition of "sorted" and "ordered", before we can >go on ? > For me the implication of "sorted" is that there is a sorting algorithm that can be used to create an ordering from a prior state of order, whereas "ordered" could be the result of arbitrary permutation, e.g., manual shuffling, etc. Of course either way, a result can be said to have a particular defined order, but "sorted" gets ordered by sorting, and "ordered" _may_ get its order by any means. Regards, Bengt Richter From rbt at athop1.ath.vt.edu Thu Nov 10 11:03:04 2005 From: rbt at athop1.ath.vt.edu (rtilley) Date: Thu, 10 Nov 2005 11:03:04 -0500 Subject: IE Temporary Internet Files & Python In-Reply-To: References: Message-ID: Laszlo Zsolt Nagy wrote: > >> The script does not seem to work when used on Temporary Internet Files. >> > Doesn't work well? What does it mean? Is there an exception raised? > > Les > No exception. The files are not deleted. From http Mon Nov 7 21:54:26 2005 From: http (Paul Rubin) Date: 07 Nov 2005 18:54:26 -0800 Subject: Using python for writing models: How to run models in restricted python mode? References: <1131396880.679361.170580@g49g2000cwa.googlegroups.com> <1131401624.263258.185730@z14g2000cwz.googlegroups.com> <43700DDB.3020009@REMOVEMEcyber.com.au> Message-ID: <7x4q6nvogt.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I suspect your best bet might be to write a mini-language using > Python, and get your users to use that. You will take a small > performance hit, but security will be very much improved. > > What do others think? That is the only approach that makes any sense. Even with restricted execution there's no way to stop memory exhaustion with restricted Python statements. Consider xxx = 'x'*10000000000 From R.Brodie at rl.ac.uk Mon Nov 28 05:04:12 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Mon, 28 Nov 2005 10:04:12 -0000 Subject: Writing pins to the RS232 References: <1132953944.656557.31910@g14g2000cwa.googlegroups.com> <3urg78F130gopU1@individual.net> <1133134832.031873.302400@g49g2000cwa.googlegroups.com> Message-ID: "Roy Smith" wrote in message news:roy-D8EE56.19040027112005 at reader2.panix.com... > "jay.dow at gmail.com" wrote: >> While I realize this is more on a driver/hardware level it's >> interesting that it's so difficult to use a different protocol for an >> existing driver. For example, all serial does is a series of high and >> low voltages on specific pins. Why should it be so hard to use an >> existing driver and hold a pin on high? > > It's been a long time since I've looked at this low-level hardware, but > the > answer is almost certainly, "No just 'so hard', but 'impossible'". If you just need one or two signals, then it might be practical to use one of the control lines, and PySerial supports this (UPS monitoring software often works this way). Setting 8 pins to 1 would be impossible, because there plain won't be that number of outputs wired, in addition to all the good stuff about UARTs Roy said. From steve at REMOVETHIScyber.com.au Sun Nov 20 17:02:29 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 21 Nov 2005 09:02:29 +1100 Subject: Underscores in Python numbers References: <1131415329.281998.104970@g43g2000cwa.googlegroups.com> <1132359968.906092.177360@o13g2000cwo.googlegroups.com> <1132392820.882873.183570@g44g2000cwa.googlegroups.com> <1132476670.992305.106250@o13g2000cwo.googlegroups.com> Message-ID: On Sun, 20 Nov 2005 09:27:28 -0500, Peter Hansen wrote: > But why would anyone want to create numeric literals for credit card > numbers? Credit card numbers is not a sensible usage case. Neither are books' ISBNs, or tax file numbers, or telephone numbers -- these are all instances where it makes sense to read them from a data file and use a converter function. One sensible usage case is numeric calculations, where you often are using numeric constants in some formula, and those constants may have ten, twelve, fifteen digits. Being able to group digits makes it considerable easier to enter the numbers, as well as proof-read your code. c = 25.173 268 901 910 023 is considerably easier for the human reader to parse than: c = 25.173268901910023 Calculating the number in place is not an acceptable solution: c = 25.173 + 268e-3 + 901e-6 + 910e-9 + 23e-12 is bad for a number of reasons: - it implies c is a calculated sum when it is not; - it harms comprehension; - it may very well lose accuracy; - it is easy to miscalculate and end up with a completely wrong number; - it complicates and obfuscates the compiled code. Another sensible usage case is in the interactive interpreter. If you are using Python interactively, you may wish to use numeric literals with large numbers of digits. It is not feasible to read them from a data file, and using a special converter function is impractical and unnecessary. I don't know whether these two usage cases will be enough to justify changing the way Python handles numeric literals -- Guido seems quite conservative in what he adds to the language, so unless there is either great demand or it scratches a particular itch he has personally, I doubt it will fly. But we'll never know unless we try, hey? *wink* -- Steven. From usenet at marduk.letterboxes.org Fri Nov 4 12:36:41 2005 From: usenet at marduk.letterboxes.org (marduk) Date: Fri, 04 Nov 2005 17:36:41 GMT Subject: I Need Motivation Part 2 In-Reply-To: References: Message-ID: <1131125801.20182.2.camel@blackwidow> On Fri, 2005-11-04 at 17:06 +0100, Magnus Lycka wrote: > If Python appears more complex > than C++, you must be using a really weird approach. Or a really weird editor ;-) -m > From steve at holdenweb.com Wed Nov 23 12:40:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 23 Nov 2005 17:40:56 +0000 Subject: asyncore question In-Reply-To: References: Message-ID: St?phane Ninin wrote: > Hello, > > Probably a stupid question... but still: > > >>>>from asyncore import dispatcher >>>>d=dispatcher() >>>>print d > > None > >>>>d > > > >>>>print type(d) > > > >>>>d.__class__ > > > >>>>d is None > > False > >>>>^Z > > > why > >>>>print d > > prints None ? > > > > Thanks for your answers, > > > At a guess, because it has a __str__() method that doesn't return anything, while its __repr__() method is probably inherited from object or instance. 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 steve at REMOVETHIScyber.com.au Thu Nov 10 17:36:54 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 11 Nov 2005 09:36:54 +1100 Subject: Newb ?? References: <1131505705.366636.132550@o13g2000cwo.googlegroups.com> <1131506094.767452.156780@o13g2000cwo.googlegroups.com> <1h5rwi5.kp55jh1kncdhvN%aleax@mail.comcast.net> Message-ID: On Thu, 10 Nov 2005 17:31:18 +0000, Steve Holden wrote: > Effectively you want to start with a minposs and maxposs, which are set > to 0 and 100 respectively. Your guess should bisect the range (as nearly > as it can given that you are dealing with integers, and you have to be > careful to get the awkward boundary conditions right). So your first > guess will be 50. If your guess is too low then replace minposs with > your guess (in this case 50); if too high, replace maxposs with your > guess; loop to generate the next guess, and so on. In practice since > log2(100) > 5 your five guesses won't always be enough (though seven > should be). Dude, that's what my code does, although I admit I took zero care to get the awkward boundary conditions right, nor did I put code in to stop the game after five attempts. -- Steven. From alia_khouri at yahoo.com Wed Nov 30 23:42:01 2005 From: alia_khouri at yahoo.com (Alia Khouri) Date: 30 Nov 2005 20:42:01 -0800 Subject: improving pypi / setuptools In-Reply-To: References: <1133321761.109769.87280@f14g2000cwb.googlegroups.com> Message-ID: <1133412121.497730.242030@o13g2000cwo.googlegroups.com> It is still early days for setuptools... still, we are lagging behind the ruby world in this regards. I definitely agree with you that the so-called megaframeworks need to be packaged better (especially all versions of the different components being updated on almost daily basis). AK From cito at online.de Tue Nov 22 14:15:18 2005 From: cito at online.de (Christoph Zwerschke) Date: Tue, 22 Nov 2005 20:15:18 +0100 Subject: Why are there no ordered dictionaries? In-Reply-To: <1132651205.289042.116290@o13g2000cwo.googlegroups.com> References: <1132570504.077360.187490@z14g2000cwz.googlegroups.com> <1132651205.289042.116290@o13g2000cwo.googlegroups.com> Message-ID: >>def __init__(self, init_val = ()): >> dict.__init__(self, init_val) >> self.sequence = [x[0] for x in init_val] Fuzzyman wrote: > But that doesn't allow you to create an ordered dict from another > ordered dict. Right; I did not want to present a full implementation, just the relevant part. Of course, a real implementation should also allow to build an ordered dict from another ordered dict or an ordinary dict. (In the latter case, maybe the keys should be automatically sorted.) But one or two case disctinctions would not make things mentionable slower. -- Christoph From steve at holdenweb.com Mon Nov 7 03:23:09 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 Nov 2005 08:23:09 +0000 Subject: gmpy 1.01 rc near... anybody wanna test> In-Reply-To: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> References: <1h5mjvx.o9ciyp1ncxeijN%aleax@mail.comcast.net> Message-ID: <436F0EED.70804@holdenweb.com> Alex Martelli wrote: > I have fixed almost all of the outstanding bugreports and feature > request for gmpy: divm doesn't leak memory any more, truediv and > floordiv are implemented for all types, etc -- in the current CVS > version (one thing I must still look at is divm's behavior when its args > are not mutually prime). It currently compiles w/o warnings, and passes > all of its 1040+ tests, w/the current release of GMP (4.1.4), Python > (2.4.2), MacOSX (10.4.3), XCode (2.1), gcc (4.0).\\ > > gmpy users able to download and build from sourceforge's cvs are > encouraged to test the current CVS version. This is a great time to > send me any bug reports or (minor;-) feature requests, since I hope to > release a "1.01 release candidate" of gmpy ASAP. I'm currently unable > to build any Windows version -- any volunteer for THAT task is doubly > welcome;-). > I tried compiling it with the MS free toolkit but the C compile complains about the absence of "gmp.h". Since I see such a header in my Cygwin installation I presume it's something that a full VC7 installation could expect to be present. Unfortunately modifying the build to use the Cygwin include directory gave errors, I suspect because other Cygwin headers were also being picked up in error (I just added /cygwin/usr/include to include_dirs. Compilation ran to completion with the header files from both Cygwin and the GNU gmp-static library, but then of course in both cases I was missing the gmp library to link it against. So I'm afraid you might need someone with access to VC to test this on Windows for you, sorry. 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 aleax at mail.comcast.net Mon Nov 28 00:43:51 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 27 Nov 2005 21:43:51 -0800 Subject: should python have a sort list-map object in the std-lib? References: Message-ID: <1h6pg7c.1q4nxaf4virbiN%aleax@mail.comcast.net> Tim Henderson wrote: ... > Hi > > The question why are there no sorted dictionaries in python, seems to > pop up with unseeming regularity. That question in itself in > nonsensical sense dictionaries are hash-maps, however should python > have a sorted map type object is a good question. > > clearly many people like have a sorted map, and sorting the keys every > time seems rather wasteful, as does keeping a separate sorted list of > the keys. It may be the most practical approach, though. Designing ONE "ordered dictionary" needs to answer several questions that will affect (reduce) its usefulness no matter how you answer them, such as: do the keys need to be hashable *as well as* order-comparable? Do copies of key objects get implicitly taken on insertion? Etc, etc. > a related question is, in python is it more efficient to a maintain a > list type in sorted order by inserting each new object in the correct > location (by say finding it with a binary search and then using del > list[x]) or appending each new item to the end of said list and using > the built-in .sort method, or sorted() function? Depends on the patterns of occurrences of insertions and deletions versus needs to use the sortedlist, in terms of how do they get bunched or spread out in time wrt each other. For many cases, the best answer is, neither of those you mentioned, but rather the functions in heapq. Alex From mwm at mired.org Mon Nov 28 15:21:31 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 28 Nov 2005 15:21:31 -0500 Subject: Death to tuples! References: <86y839ux1j.fsf@bhuda.mired.org> <1133163207.641767.210610@o13g2000cwo.googlegroups.com> Message-ID: <86acfov7zo.fsf@bhuda.mired.org> Steven Bethard writes: > Dan Bishop wrote: >> Mike Meyer wrote: >> >>>Is there any place in the language that still requires tuples instead >>>of sequences, except for use as dictionary keys? >> The % operator for strings. And in argument lists. >> def __setitem__(self, (row, column), value): >> ... > Interesting that both of these two things[1][2] have recently been > suggested as candidates for removal in Python 3.0. > [1]http://www.python.org/dev/summary/2005-09-01_2005-09-15.html#string-formatting-in-python-3-0 > [2]http://www.python.org/dev/summary/2005-09-16_2005-09-30.html#removing-nested-function-parameters #2 I actually mentioned in passing, as it's part of the general concept of tuple unpacking. When names are bound, you can use a "tuple" for an lvalue, and the sequence on the rhs will be "unpacked" into the various names in the lvalue: for key, value = mydict.iteritems(): ... a, (b, c) = (1, 2), (3, 4) I think of the parameters of a function as just another case of this; any solution that works for the above two should work for function paremeters as well. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From deets at web.de Wed Nov 9 08:47:25 2005 From: deets at web.de (Diez B. Roggisch) Date: 9 Nov 2005 05:47:25 -0800 Subject: cx_Oracle callproc output parameters In-Reply-To: References: <1131486799.092340.72120@g43g2000cwa.googlegroups.com> Message-ID: <1131544045.438924.15410@g49g2000cwa.googlegroups.com> Gerhard H?ring wrote: > You have to use variable objects to the callproc() that will hold the > output values. This is an example using three VARCHAR output parameters. Oh boy, one never stops learning... I still thing a single in-out-value is crying for a function - but in case of several parameters, this of course is way more elegant as it requires no knowledge about the column-size beforehand. Regards, Diez From bonono at gmail.com Sun Nov 27 22:20:35 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 27 Nov 2005 19:20:35 -0800 Subject: General question about Python design goals In-Reply-To: References: Message-ID: <1133148035.601751.268870@g43g2000cwa.googlegroups.com> Christoph Zwerschke wrote: > >>For instance, I just wanted to use the index() method on a tuple which > >>does not work. ... > > Aahz wrote: > > > Because Guido believes that tuples should be primarily used as > > lightweight replacements for C structs. Therefore they have minimal > > functionality. > > But the problem is that the tutorials and manuals give the impression > that the difference between lists and tuples is only mutablity versus > immutability. They don't talk about such considerations and honestly > speaking even now I know that it does seem more plausible for me. That is the problem of the tutorial or manual, don't read them as if they are ISO specs. From aleax at mail.comcast.net Sat Nov 12 12:46:06 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 12 Nov 2005 09:46:06 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <1h5ty4g.1onzjda6fc7xmN%aleax@mail.comcast.net> Message-ID: <1h5wpwn.116qc6zw7e78N%aleax@mail.comcast.net> Yu-Xi Lim wrote: > I hadn't seen any damage done from misusing "it's". Certainly not on par You should see my pharmacy bill for Maalox... and my liver ain't too happy about it either;-) Alex From mclister at zeesource.net Mon Nov 7 17:50:15 2005 From: mclister at zeesource.net (Claire McLister) Date: Mon, 7 Nov 2005 14:50:15 -0800 Subject: Map of email origins to Python list In-Reply-To: References: <1131390365.721288.272070@g47g2000cwa.googlegroups.com> <1131396963.363256.12250@g47g2000cwa.googlegroups.com> <1131400439.260344.19880@g44g2000cwa.googlegroups.com> Message-ID: <9c7030876cf681218593628f9fb0980f@zeesource.net> Thanks, Alan. You are absolutely right, we are not using the NNTP-Posting-Host header for obtaining the IP address. The Python list is unique among the lists that we have handled so far, in that it has a cross-posting mechanism with a net news. Hence, it seems we are getting many more wrong locations here than any other email list maps we've done so far. We've done them for Linux kernel, postresql, apache, tomcat, etc. You can find them by searching their names in the 'find' box. Not many people reported wrong locations on those maps. So, we'll have to go back and fix the script that is extracting the IP address (which is written in Python, btw). Let me know if someone is interested in taking a look at it and I can post it somewhere. On Nov 7, 2005, at 2:32 PM, Alan Kennedy wrote: > [Alan Kennedy] >>> So presumably "chcgil" indicates you're in Chicago, Illinois? > > [mensanator at aol.com] >> Yes, but why, then, is my name logged into Mountain View, CA? > > Presumably the creators of the map have chosen to use a mechanism other > than NNTP-Posting-Host IP address to geolocate posters. > > Claire, what mechanism did you use? > >> That justifies my claim of "all the more stupid", doesn't it? > > Well, to me it just says that the map creation software has some bugs > that need fixing. > > -- > alan kennedy > ------------------------------------------------------ > email alan: http://xhaus.com/contact/alan > -- > http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Thu Nov 10 14:48:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 10 Nov 2005 20:48:50 +0100 Subject: Python as a HTTP Client References: <1131626098.168521.178600@g49g2000cwa.googlegroups.com> <43739a80$0$2086$edfadb0f@dtext02.news.tele.dk> Message-ID: David Rasmussen wrote: > I do know about www.python.org. I do an extensive amount of googling in > general and searching at python.org before I ask questions such as this. > I did stumble upon urllib, urllib2 and httplib in the documentation, but > let me assure you, as a newbie, that finding this documentation doesn't > make one go "ah, this is what I was looking for". > Specifically, I can't see from reference documentation whether something > even smarter or more highlevel exists. hmm. so if that was your question, why did you write: I am writing a program that has to do some lightweight HTTP communication with a webserver on the internet. I haven't checked, but I'm sure I could do something lowlevel like opening a socket myself and then send/receive everything myself on this (how do I do that?), but I'd bet that Python have some module which is more high level. Something that would just let me connect using an URL, send a few GETs, and receive the answer as a string/file etc. ? ("I haven't checked ... but I'd bet" doesn't really sound like "I've checked the docs and found a couple of modules that seem to do this, but I wonder if there is something better out there") ...especially if you had already seen the tutorial's Internet Protocols There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are urllib2 for retrieving data from urls /.../ (followed by a brief example that shows how to read from an URL) or the reference guide's urllib -- Open arbitrary resources by URL This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built- in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. or urllib2 -- extensible library for opening URLs The urllib2 module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world -- basic and digest authentication, re- directions, cookies and more. which all seem to match "something that would just let me connect using an URL" pretty well. From ale.of.ginger at gmail.com Fri Nov 4 07:30:44 2005 From: ale.of.ginger at gmail.com (ale.of.ginger at gmail.com) Date: 4 Nov 2005 04:30:44 -0800 Subject: Not Equal to Each Other? In-Reply-To: <436ace8a.66565105@news.oz.net> References: <1131066067.980875.223790@g43g2000cwa.googlegroups.com> <436ace8a.66565105@news.oz.net> Message-ID: <1131107444.116585.153760@o13g2000cwo.googlegroups.com> How do I 'define' set? Is there something to include (like import random)? while (choice == 3) and len(set(cellboard[0:8]))==len(cellboard[0:8]): # DEFINE TWO RANDOM VARIABLES (ONE FOR ARRAY, ONE FOR NUMBER VALUE) solvingrandom = random.randint(1,9) cellboardrandom = random.randint(0,8) set(cellboard[0:8]) # CHECK TO MAKE SURE THE RANDOMLY ASSIGNED CELL DOES NOT HAVE A VALUE if (cellboard[cellboardrandom] is not ('1' or '2' or '3' or '4' or '5' or '6' or '7' or '8' or '9')): cellboard[cellboardrandom] = solvingrandom The above is my code (right now it will only work for the first row's numbers). Anything else I need to add? From aleax at mail.comcast.net Sun Nov 27 13:43:54 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sun, 27 Nov 2005 10:43:54 -0800 Subject: Estimating memory use? References: Message-ID: <1h6olhu.12xxjwh12leq0gN%aleax@mail.comcast.net> Roy Smith wrote: ... > Is there any easy way to find out how much memory a Python object takes? No, but there are a few early attempts out there at supplying SOME ways (not necessarily "easy", but SOME). For example, PySizer, at . Alex From pythonnew at gmail.com Tue Nov 22 09:49:15 2005 From: pythonnew at gmail.com (Ben Bush) Date: Tue, 22 Nov 2005 06:49:15 -0800 Subject: after sorted from the lists Message-ID: <8c11e4350511220649h3d3dcb41i1e8fafac5c4b9201@mail.gmail.com> I have a list: [[1,2],[2,1],[3,1],[1,4],[3,3],[1,4]] How to remove all the duplicate or same after sorted from the lists? That is, [1,2] and [2,1] are the same after sorting them. I want the result to be: [[1,2],[3,1],[1,4],[3,3]] From mwm at mired.org Wed Nov 30 15:34:29 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 30 Nov 2005 15:34:29 -0500 Subject: Making immutable instances References: <1h6huee.f74jx2krwvj 2N%aleax@mail.comcast.net> <1h6hyy2.1kys0ai15yqhpoN%aleax@mail.comcast.net> <86lkzexafz.fsf@bhuda.mired.org> <86hda0gosu.fsf@bhuda.mired.org> <8664qgghvu.fsf@bhuda.mired.org> <7xirua3d3p.fsf@ruckus.brouhaha.com> <86u0duodzl.fsf@bhuda.mired.org> <1133333467.677454.134110@g49g2000cwa.googlegroups.com> Message-ID: <86acfloox6.fsf@bhuda.mired.org> bonono at gmail.com writes: > I am puzzled, and could have read what you want wrong. Are you saying > you want something like this : > > a={} > a.something = "I want to hang my stuff here, outside the intended use > of dict" Exactly. For a use case, consider calling select.select on lists of file objects. If the processing is simple enough, the clearest way to associate a handler with each socket is just to add it as an attribute. But that doesn't work - sockets are bulitin types. So you consider less light-weight solutions, like subclassing socket (now that that's possible), or a dictionary of handlers keyed by socket. This works by default with classes written in Python. That it doesn't work for builtins is inconsistent, non-orthogonal, and incomplete. However, it's easy to work around, and the obvious fix - adding a dictionary to every builtin - is rather costly. So we'll live with it since practicality beats purity. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From samrobertsmith at gmail.com Tue Nov 8 05:40:29 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Tue, 8 Nov 2005 02:40:29 -0800 Subject: any python module to calculate sin, cos, arctan? Message-ID: <1d987df30511080240x6e02b542x101442299322805f@mail.gmail.com> any python module to calculate sin, cos, arctan? From bonono at gmail.com Thu Nov 24 22:24:34 2005 From: bonono at gmail.com (bonono at gmail.com) Date: 24 Nov 2005 19:24:34 -0800 Subject: Why is dictionary.keys() a list and not a set? In-Reply-To: <86y83dto2z.fsf@bhuda.mired.org> References: <1132885331.813383.60830@o13g2000cwo.googlegroups.com> <86y83dto2z.fsf@bhuda.mired.org> Message-ID: <1132889074.400918.158030@f14g2000cwb.googlegroups.com> Mike Meyer wrote: > "bonono at gmail.com" writes: > > Christoph Zwerschke wrote: > >> jepler at unpythonic.net schrieb: > >> > You can already get a set from a dictionary's keys in an efficient manner: > >> >>>>l = dict.fromkeys(range(10)) > >> >>>>set(l) > >> > Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > >> Good point. I expected that set(l) = set(l.items()) and not > >> set(l.keys()), but the latter would not work with mutable values. See > >> discussion with Martin. > > puzzled. items() return tuples which I believe can be element of set ? > > Or I misread you ? > > Not all tuples can be elements of a set. Elements of a set have to be > hashable. Tuples compute their hash by hashing their contents. If > their contents aren't hashable, the tuple isn't hashable, and hence > can't be an element of a set. If the values in the dictionary aren't > hashable, then the tuples returned by items() won't be hashable > either, and hence can't be elements of a set. > ah, thanks. I was thinking that tuples being immutable object must be hashable. So it is not about mutable but hashable. From steve at holdenweb.com Thu Nov 3 23:41:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Nov 2005 04:41:06 +0000 Subject: Class Variable Access and Assignment In-Reply-To: References: <1131011012.806470.310870@g43g2000cwa.googlegroups.com> <873bmekk70.fsf@keizer.soze.com> <87psphkiw4.fsf@keizer.soze.com> Message-ID: Antoon Pardon wrote: > Op 2005-11-03, Stefan Arentz schreef : > >>Antoon Pardon writes: >> >>... >> >> >>>>>No matter wat the OO model is, I don't think the following code >>>>>exhibits sane behaviour: >>>>> >>>>>class A: >>>>> a = 1 >>>>> >>>>>b = A() >>>>>b.a += 2 >>>>>print b.a >>>>>print A.a >>>>> >>>>>Which results in >>>>> >>>>>3 >>>>>1 >>>> >>>>I find it confusing at first, but I do understand what happens :-) >>> >>>I understand what happens too, that doesn't make it sane behaviour. >>> >>> >>>>But really, what should be done different here? >>> >>>I don't care what should be different. But a line with only one >>>referent to an object in it, shouldn't be referring to two different >>>objects. >> >>It doesn't. > > > Yes it does. If the b.a refers to the instance variable, then an > AttributeError should be raised, because the instance variable doesn't > exist yet, so you can't add two to it. > Excuse me. The statement a += 2 causes a to refer to a different object after the assignment than it did before. So does the statement self.a += 2 So why are you so concerned that the pre-assignment reference comes from a different scope to the post-assignment reference? The fact remains that after both assignments the rebound name can no longer (ever) be used to refer to its former referent without a further rebinding taking place. > If the b.a refers to the class variable then two should be added to it. > Wring, wring, wring. (Sorry, got that wrong :-) > Neither happens instead we get some hybrid in which an instance varible > is created that gets the value of class variable incrented by two. > Yes. So does this mean you also have a problem with def f(x): x += 2 g = 3 print f(g) When the function call executes, the name x is bound to an object in the call's containing scope. Is it then your contention that the augmented assignment in the function should add two to that object, changing the value of g? For extra marks please explain the difference between augmented assignment to a function argument and augmented assignment to a class variable referenced through self. > >>>In the line: b.a += 2, the b.a should be refering to the class variable >>>or the object variable but not both. So either it could raise an >>>attribute error or add two to the class variable. >> I'm not sure where this moral imperative comes from, and your arguments singularly fail to convince me. >>It does exactly what you say. It adds 2 to the a *instance variable* of >>the object instance in 'b'. > > > There is no instance variable at that point. How can it add 2, to > something that doesn't exist at the moment. > It doesn't, it simply proceeds along the lines of all Python assignments and resolves the name as a reference to a specific object. It then computes a new value from the referenced object and the augmented assignment operator's right operand, and rebinds the name to the newly-computed value. Please stop talking about variables. Although augmented assignment operators have the *option* of updating objects in place, surely not even you can require that they do so when they are bound to an immutable object such as an integer. > >>It doesn't touch the *class variable* A.a which is still 1. > Why "should" it? Why, why, why? And gain, just for good measure, why? Augmented assignment to a function argument doesn't modify the passed object when immutable, and you have no problem with that (I know as I write that this is just asking for trouble, and it will turn out that you also find that behavior deeply controversial ...) > > But it accesses the class variable. > Repeat after me: "Python assignment binds values to names". When I write class something: a = 1 def __init__(self, val=None): if val: self.a += val then in the last statement the augmented assignment rebinds "self.a" from the class "variable" to a newly-created instance "variable". I am of course using the word "variable" here in a Pythonic sense, rather than in the sense that, say, a C programmer would use. In Python I prefer to talk about binding names because talking of variables leads people to expect that a name is bound to an area of memory whose value is modified by assignment, but this is in fact not so. The initial access to self.a uses the defined name resolution order to locate a value that was bound to the name "a" in class scope. So what? This is a long-documented fact of Python life. It's *supposed* to be that way, dammit. I fail to understand why this is such a problem for you. But then it's clear from long past experience that our perceptions of Python's execution model differ quite radically, and that I seem to find it quite satisfactory overall, whereas you are forever banging on about what "should" be true of Python and what Python "should" do. Which, as is probably obvious by now, I sometimes find just a teeny bit irritating. Kindly pardon my tetchiness. I suppose ultimately I'm just more pragmatic than you. Plus I started using Icon, whose assignment semantics are very similar, back in the 1970's, so Python's way of doing things fits my brain quite nicely, thank you. regards Steve PS As a total non-sequitur added for light relief at the end of what seems even to me to be a slightly tedious post, I discover I managed to misspell "assignment" in four distinct ways during the composition of the above. -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ From benmorganpowell at gmail.com Wed Nov 2 08:56:21 2005 From: benmorganpowell at gmail.com (benmorganpowell at gmail.com) Date: 2 Nov 2005 05:56:21 -0800 Subject: Spambayes modifications with web services References: <1130486425.402338.123720@g49g2000cwa.googlegroups.com> Message-ID: <1130939781.817460.142120@g49g2000cwa.googlegroups.com> Thank you for the flippant remarks. Let's just say that I found them to be unproductive. I would like to point out the process was not designed to be automatic and I don't believe made such a statement. I should clarify that my desire was to list each domain that was contained in a spam email, so that the user could then: - check if previously it has been reported as spam, or - open the link in their browser, and - check whether the domain was spam or ham, and then if spam - post it to the web service ("Post Spam Site to Web Service"). Therefore, thanks, yes, I did "think through the consequences of my actions". The line that reads "WARNING: DO NOT BUY FROM THIS WEBSITE. THE SPAMMER IS.....", was tongue in cheek, and it seems to be the line that stirred up the condescending comments. What I should have written was something more along the lines of: "WARNING: The website has been reported by users as a website that uses illegal spam email to generate business leads" I think that is a perfectly useful and fair statement, which I cannot see damaging legitimate business enterprises. I also think it would be quite useful for consumers to know that the domain name they are about to purchase had previously been misused by spammers, and was quite likely to be blacklisted by spam software. I must say that I am surprised that the python group could be so unfriendly and unhelpful. Many thanks. From aleax at mail.comcast.net Sat Nov 19 21:26:11 2005 From: aleax at mail.comcast.net (Alex Martelli) Date: Sat, 19 Nov 2005 18:26:11 -0800 Subject: Python obfuscation References: <1131560203.383820.5220@g49g2000cwa.googlegroups.com> <1h5rwz0.nkpaore20xo6N%aleax@mail.comcast.net> <1131640817.644852.7070@g44g2000cwa.googlegroups.com> <86irv05fh1.fsf@bhuda.mired.org> <1131719917.837060.314410@z14g2000cwz.googlegroups.com> <86br0r40rc.fsf@bhuda.mired.org> <86iruy2zus.fsf@bhuda.mired.org> <1131780165.878093.164510@o13g2000cwo.googlegroups.com> <7xu0ei15v4.fsf@ruckus.brouhaha.com> <1h5wq0i.1x9dw454uxdjsN%aleax@mail.comcast.net> <1132249511.886027.93990@g14g2000cwa.googlegroups.com> <1h662eo.95qjyvd1bcnuN%aleax@mail.comcast.net> <437d0b86.63834689@news.oz.net> <1132325798.806457.91170@g47g2000cwa.googlegroups.com> <1h67rkl.1rkx0mm1hpdql9N%aleax@mail.comcast.net> <1132406038.650352.323390@g14g2000cwa.googlegroups.com> Message-ID: <1h69rhd.a4a8g3p83u9jN%aleax@mail.comcast.net> Anton Vredegoor wrote: ... > Suppose I grant all your theories about optimal marketing strategies. > This still doesn't account for the way the market is behaving *now*. It > isn't in any way logical or optimal. For example in Holland (where I > live) complete governmental departments are dedicated to make life What makes you think that governmental departments are part of the *market*?! Government behavior is controlled by laws that are vastly different from those controlling market behavior; if you're interested, you could study the "theory of public choice". Studying "perfect" markets (which can be mathematically proven to be optimal in some senses -- the Arrow-Debreu Model, for example) is parallel to studying physical systems that do not have attrition or other such complications -- it's mathematically sharp (not easy, but WAY easier than taking account of all the complications of the real world), intellectually fascinating, AND practically useful in many (not all) cases, since many real systems can be usefully modeled as "perfect" ones with "perturbations" (second-order effects) considered separately. If Galileo had tried to START physics by studying real-world systems in all of their complexity, we'd still be at square zero; fortunately, he was able to identify systems "close enough to perfect" (e.g., heavy weights faling to the ground, compact enough to ignore air resistance, etc) to get the ball rolling. Physics still faces a lot of challenges after many centuries in areas where the "perturbations" are much stronger than "second-order" -- I'm told our physical modeling of cloud systems or such everyday phenomena as welding is still way from perfect, for example (forget quantum and relativistic effects... I'm talking of everyday observations!-), and of course so does the much younger discipline of mathematical economics. Nevertheless the study of the "perturbations" is well under way, with Nobel memorial prizes having already been awarded in such fields as "bounded rationality" and asymmetric-information markets. Just like a gunner in the mid-19th century had to know fundamental physics pretty well, but also developed experience-based heuristics to compensate for all of the "perturbations" in his system, so the practicing economic actor today needs a mix of science and art (in the original meaning of "art", of course). > You seem to tackle the problem of python obfuscation by first proving > that it isn't feasible and then giving some kind of solution that will > work and give the desired result: webservices. However when I look at That seems to me to be a practicable technical approach, yes. > obfuscation techniques I see a desire to profit from giving some person > the idea that he or she is superior to someone else because he has a > better product. In order to avoid copying we now need obfuscation. The You're discussing the *motivation* for obfuscating, while what I was giving was a possible way of *implementing* similar effects. > difficulty to copy the thing (whether it is a swiss watch, a sportscar, > designer clothes, the latest computer game, an ipod, a computer > program) is part of the advertising game and is the basis for > associating it with a certain status. If you look for a few minutes at Yes, this is close to the theory of luxury goods (which is WAY underdeveloped, by the way: if you're a post-doctoral student in economics and are wondering where best to direct your research in order to stand a chance to gain a Nobel memorial prize some day, you could do worse than turn your efforts to this field). The maths are complicated, in the theory of luxury goods, because utility is RELATIVE: buyer's advantage cannot be computed, even theoretically, from knowing just the buyer's utility curve and the amount of good supplied to that buyer, because the curve depends on the *relative* amounts supplied to that buyer versus other buyers. Throw asymmetric information into the mix, and, besides a mathematically unmanageable mess, you get the famous anomaly whereby an INCREASE i the price may locally result in an INCREASE in demand (backwards-sloping price-demand curve) -- each buyer, lacking information about other buyers, infers it from price signals, and *assumes* (as is normally the case) that higher price means fewer buyers; since fewer buyers means a higher relative advantage, this assumption increases each buyer's appetite and thus, in the aggregate, raises demand. While this is fascinating as an open research topic, AND crucial to economic survival for purveyors of luxury good, I dispute the wisdom of trying to model MOST markets of interest as subject to the fascinating complications of "luxury goods theory". Take, again, the specific example of the sawmill with NC saws, doing custom work by cutting customer-specified shapes out of standard planks of wood. If things can be optimized, so that six such shapes can be cut out of each plant rather than the five which would result from a simple layout of the shapes, the mill can meet an order for 3000 shapes by consuming 500 planks of wood, rather than taking up 600 planks. There is no need at all for any of the complications of luxury-goods theory to understand and model this: the developer of the superior heuristic has created "objective" value, under the simple and natural assumptions that wood costs money and wasting less wood for the same output is therefore an indisputable savings. NOW you may get into the issue of how that value is split between supplier (of the heuristic) and buyer (the sawmill), under various possible arrangements. Market segmentation may well enter the picture here, because there may be different orders of widely different sizes -- maybe 3000 shapes is a typical order, but there may be some for 300 shapes and some for as many as 30,000; if the supplier charges the same price for usage of his heuristic for any size of order, either the heuristic will not get used for the smaller orders (making the overall "pie" of value to share smaller), or the buyer will capture close to all the value for larger orders ("buyer's advantage" situation). So, it is definitely to the supplier's advantage, and it can be shown that situation exists in which it's of MUTUAL advantage, if different prices can be used for the same (good of) service when used in different situations (size of orders), which is exactly what market segmentation is all about. > a TV screen and notice what the commercials are trying to tell you, you > will see that it's almost always that you will be better, stronger, > more popular or beautyfull etc. if only you use product X. Whether such ads WORK, of course, is an entirely open question; targeted ads, which get paid for only when they DO work, appear to be the direction advertising is taking these days. Anyway, ads are practically _irrelevant_ to all we were talking about so far, except in as much as they may help in asymmetric information markets, which is a separate (and infinitely fascinating) sector of economic theory. It seems to me that you're mixing in all sort of somewhat anecdotal observations, without a sound basis in either economical theory or deep practical experience, just as when you were taking your opinions about government departments as somehow related to the working of markets (?). If Galilei had started dispersing his energies and attention by worrying about the COLORS in which the balls he was dropping to the ground were painted, rather than focusing on RELEVANT issues such as size and mass, he'd hardly have made much progress on the issue, would he?-) > You are perfectly right if you would say that it is an illogical > strategy to make people feel better relative to other people in order > to get them to do something you want. Commercial entities could in I'm not saying that: if I had to sell luxury goods, I would definitely pursue such a strategy. However, there are plenty of goods and services which do NOT particularly need the complications of luxury-goods theory. > principle be free of such things but we live in a world that is > dominated by this worldview and if one tries to sell something one has > to take that into account. If you're selling luxury goods, sure, you can't afford to ignore related issues. But for most goods and services, particularly in the "business to business" sector, the approach (which DOES get tried, as you can see by some ads in magazines such as the Economist, Business Week, Forbes, and so on) is IMHO quite silly (and a good example of that 50% of money spent on advertising that is proverbially wasted). > So how to get the same kind of market segmentation (as you call it) > when you deploy your program as a webservice and where essentially the > cost for you (moving a few electrons to produce a solution to a > problem) is exactly the same whether you give the user a good or a bad > result. If you give optimal results to everyone, users will go to other > sites just because these sites give them opportunity to feel better > than other people, not because this is objectively better, but just > because that is how they think the world "works". I believe that you are quite wrong: if your results are in fact better than other sites', users will come get your results. Markets are imperfect, rationality is bounded, etc, etc, but users in general are not total morons, to deliberately go and get worse results "to feel better than other people". For example...: I was reading recently that Google's market share of web searches has grown from 47% to 57%, comparing September 2004 with Sep 2005, for example. If your theory had ANY validity whatsoever, this should be impossible, since Google does give the best results it can to any comer; therefore, it would follow from your theory, another site could steal our traffic by serving artificially-degraded results to the non-paying public, and true search results only to subscriber, or something. The world just does not work this way -- thanks be. Similarly: until recently, Opera "degraded" the user experience of non-fee-paying users (by devoting a portion of its window to showing banner ads) and required user to pay a fee (so, according to your theory, "felling better than other people") to get a pure, undegraded browsing experience. Firefox came along and "gave optimal results to everyone" instead. Result: Firefox ate Opera's lunch, forcing Opera to change its business model drastically. These events, once again, are totally incompatible with the theory you advance in this paragraph. I doubt you will be able to do a good job of comprehending, much less _explaining_, market segmentation strategies and tactics, unless you take the trouble to shed the ideological baggage, and stop trying to force a vision of the huge system that's the complex of markets in this world through the narrow slit of that small subset of those which are "luxury-good markets". I don't deny that luxury goods exist (that would be just as silly as your attempt to claim that ALL goods and services fall under the complexity of luxury-good market theory!): I specifically claim that luxury-goods situations are a small subset of markets (they may be very visible, and can command large profit margins to offset their small volumes and large advertising costs, but they're still NICHES compared to "where the action is", namely ALL OTHER markets put together). > Alternatively, lets just forget about obfuscation and try to get > people to freely share by promoting open source (and open webservices). I tend to a more pragmatic stance, just like Eric Raymond: although open source is going to prove preferable in _most_ cases, there _will_ be other cases (like the NC saw example, where ESR himself was the consultant who advised the inventors to keep their new heuristic a secret) where the overall production of value in the world (quite apart from who's going to capture what fraction of that value) will increase if certain kinds of innovations can be exploited by their inventor. Since redistribution of value, as long as a lot of value is created, can be dealt with by other means, maximizing the creation of value tends to be the goal I prefer -- a policy that quashes part or all of value creation based on redistributive precepts is, by this very fact, going to be something I look askance at (making the pie smaller to try to ensure that what little is left gets sliced according to your political preferences, rather than ensuring the pie is as big as possible as the first order of business, and dealing with the slicing issues as _secondary_ ones). Alex From tuvas21 at gmail.com Fri Nov 4 13:01:16 2005 From: tuvas21 at gmail.com (Tuvas) Date: 4 Nov 2005 10:01:16 -0800 Subject: Tkinter- New Window In-Reply-To: <1131126422.958411.66860@f14g2000cwb.googlegroups.com> References: <1131126422.958411.66860@f14g2000cwb.googlegroups.com> Message-ID: <1131127276.362431.222560@z14g2000cwz.googlegroups.com> Okay, never mind about my first question, I got that answer by using Toplevel. However, there' s still a question to be answered. I popped up this new window with the intent to have something like this: "what is your question" ____________________