BayPIGgies: July 14, 7:30pm (Google)
The next meeting of BayPIGgies will be Thurs, July 14 at 7:30pm at Google, building 40, room Temp Tech Talk. Alex Martelli will be doing his Black Magic talk on descriptors, decorators, and metaclasses. Prepare to have your head exploded! 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 may meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. This week, there has been discussion of a potluck -- if you want a potluck, speak up NOW on the mailing list. Advance notice: The August 11 meeting agenda has not been set. Please send e-mail to [EMAIL PROTECTED] if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
Kay Schluehr wrote: Dan Sommers schrieb: How about this: def __init__(self, self.x, y, self.z): # self.x, self.z from first and third explicit parameters do_something_with_y() Can you tell me in which way it is anyhow better than the original proposal def __init__(self, .x, y, .z): # self.x, self.z from first and third explicit parameters do_something_with_y() besides that it is more verbose? It is more explicit. Explicit is better than implicit. But as with many proposals, this raises consequential questions, for example, how self.x parameters are handled in other methods, or even functions, as __init__ is not special-cased by the parser. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
C/API importing a module as __main__
Hello All, Is there a way to import module as __main__? Say hw.py is: if __name__ == __main__: print Hello And the C code is (error handling omitted): int main(int argc, char *argv[]) { Py_Initialize(); PySys_SetArgv(argc, argv); atexit(Py_Finalize); PyImport_ImportModule(module); return 0; } When importing hw using PyImport_ImportModule nothing is printed (as expected). The documentation says that Py_Initialize already creates a __main__ module and hw.py is imported as hw. Any way to import hw as __main__? Thanks. -- Miki Tebeka [EMAIL PROTECTED] http://tebeka.bizhat.com The only difference between children and adults is the price of the toys pgpTrBHMvpC1T.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expresiveness in a Computer Language?
Paul Bilnoski wrote: The barbar generals will just grunt while the French generals will inspire with some poetic invocation. For auction: One authentic French army-issued rifle. Only dropped once. What has that got to do with the king of the elephants? -- If you want to post a followup via groups.google.com, don't use the broken Reply link at the bottom of the article. Click on show options at the top of the article, then click on the Reply at the bottom of the article headers. - Keith Thompson -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
On Friday 08 July 2005 01:31 pm, gov wrote: Where I work, we receive large quantities of data which is currently all printed on large, obsolete, dot matrix printers. This is a problem because the replacement parts will not be available for much longer. So I'm trying to create a program which will capture the fixed width text file data and convert as well as sort the data (there are several different report types) into a different format which would allow it to be printed normally, or viewed on a computer. If this is really your reason for wanting to do this, it seems like your solutions is overkill. If you really just want the data to get reformatted for printing on a modern printer, it would be trivial to do this with a text-formatter like enscript (see, e.g.: http://people.ssh.com/mtr/genscript/ ) which produces Postscript output from ASCII text. On a typical Linux system, this sort of tool is usually part of your printer installation, after which it runs more or less invisibly. OTOH, if the *real* reason is that you don't like the look of the dot matrix output and you want it *rearranged* and reformatted for aesthetic reasons, then you might reasonably want to use Python to do that as you suggest. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: ZipFile and file rigths
Robert Kern enlightened us with: Yes, the .zip file format does store file permissions appropriate to the platform that generates the file. I never knew that! Thanks for correcting me ;-) 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 -- http://mail.python.org/mailman/listinfo/python-list
Earthquake Forecasting Program July 11, 2005
PROPOSED EARTHQUAKE FORECASTING COMPUTER PROGRAM DEVELOPMENT EFFORT Posted July 11, 2005 My main earthquake forecasting Web page is: http://www.freewebz.com/eq-forecasting/Data.html Newsgroup Readers: If you circulate copies of this report to groups of computer programmers at different universities etc. around the world then they might find the subject matter to be interesting. The information in this report represents expressions of personal opinion. THE GOAL OF THIS REPORT This is part of an effort to get some idea regarding how many computer programmers and other researchers around the world might be interested in participating in a project aimed at developing life saving earthquake forecasting computer programs. That effort is not presently underway. And I don't know when or if it will get started. I am simply attempting to determine if other people believe that large numbers of volunteers would be interested in working on such a project or if there would instead be little interest in it. That information would be helpful for developing a plan for establishing a Web site where the project would be centered. Personnel running the following Web site have volunteered to make their site available for such an effort. But nothing has gotten underway so far. http://www.ictwhoiswho.net/comprend/index.cfm If quite a few people were interested in such a Web site based computer program development effort then after it got started work would undoubtedly progress quite rapidly. If only a few were interested then it might never get started. If you would like to express an opinion on the likelihood of people being interested in the idea then you can try posting a note in response to this one. The sci.geo.earthquakes or comp.lang.misc newsgroups might be appropriate if you wish to post to just one newsgroup. Of you can try contacting me by e-mail. THE CORE OF THE PRESENT EARTHQUAKE FORECASTING PROGRAM In connection with an earthquake forecasting effort which has been underway for the past 15 years I believe I have been able to crack the Earthquake Code. That means making crucially important discoveries regarding how earthquakes are being triggered. Two of them which are discussed on the following Web page are called the Gravity Point and Earthquake Triggering Symmetry. http://www.freewebz.com/eq-forecasting/90-05.html The earthquake triggering and forecasting theories and data on that Web page were discussed on my behalf by one of my research colleagues in the People's Republic of China at a disaster mitigation conference in that country in December of 2003. Governments and disaster mitigation groups around the world were told about the Web site earlier this year. And my Web site visitor counter indicates that some 100 to 200 people around the world are presently downloading information from the site each day. My earthquake forecasting computer programs use those Gravity Point and Earthquake Triggering Symmetry discoveries and others to compare electromagnetic energy field fluctuation type signals (EM signals) with more than 30,000 earthquakes which occurred since the beginning of 1990. Some 100 to 200 signals detected during a 3 month period of time are involved. For some as yet unknown reason they are often highly selective for earthquakes which are likely to occur near populated areas, making them unusually valuable. The earthquake which is the best match with all of those signals is rated # 1. The worst match would have a rating number greater than 30,000. A listing of more than 100 of the best matches is then posted perhaps once a week to the following Web page: http://www.freewebz.com/eq-forecasting/Data.html For a recent example of how well that approach to forecasting earthquakes can work, data displayed on that Web page on June 27, 2005 gave the following earthquake a # 3 rating (possible rating range: 1 to 30,000+): 2005/01/11 19:19:48 11.40N 86.51W 40.7 5.0 Near the Coast of Nicaragua (U.S. National Earthquake Information Service data) And less than a week later on July 2, 2005 the following powerful and strongly felt earthquake occurred: 2005/07/02 02:16:46 11.18N 86.40W 45.5 6.7 Near the Coast of Nicaragua 11.40N and 86.51W versus 11.18N and 86.40W Pretty good accuracy for a forecasting program! That earthquake was reportedly strongly felt in Managua. Had it occurred directly beneath the city and near the surface then I expect that it would have been devastating. WHAT NEEDS TO BE DONE Basically, more sophisticated data processing and data display computer program subroutines need to be developed. They could be built on my already existing computer programs and data. People would develop new subroutines, give them a try, and see if they did a better job of determining or displaying where an earthquake might be about to occur. The subroutines could be stored at the proposed Web site.
Re: ZipFile and file rigths
OTOH, I don't know if this has any relevance to the problem that you are seeing. not really, i have used the 'os.chmod' trick, but it's still interesting. thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Forum
Throne Software wrote: Throne Software has opened up a Python Forum at: http://www.thronesoftware.com/forum/ Join us! Why should we ? -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
gettext and disambiguating comments
I'm looking at the gettext module for the first time and learning how to write internationalized code in Python. Naturally, I also looked at the original Gnu gettext manual, which mentions that comments can be captured into the .po (.pot?) file for translators' benefit: /* Comment right before the gettext call, obviously in C */ printf(_(Apparently ambiguous string to translate)); This will get captured into the .po file, according to the gettext manual and appear as a comment right before the msgid (i.e. next to the line number reference). Is there an equivalent Python gettext idiom? I've tried the obvious # Comment right before the gettext call, now in Python print _(Apparently ambiguous string to translate) But this is ignored by both pygettext and xgettext. I also saw some discussion (from the Gnome project) about gettext variations which capture comments from within the text: _(comment for translators| Spam) But, Python's gettext happily renders the entire comment into the program, so this isn't doing anything either. Clearly, I could edit the .pot file after creation to include comments, but that's probably undesireable since the file is meant to be machine-generated. I have no pressing immediate need for this functionality (that I know of), but I'd like to understand how to access this capability if it exists. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
__eq__ on a dict
Hello, I can't find the docs for __eq__ on a dict and I can't find a description on what the eq does (strangely it does implement and but I have no idea what that does). Does anyone know (definitively) what the __eq__, __gt__, __lt__ methods do. BTW, google is not my friend - I invited it out for a drink last week and it stood me up :-). Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Cat and Mouse (wes Re: Efficiency of using long integers to hold bitmaps)
On Mon, 11 Jul 2005 02:58:29 +, Bengt Richter wrote: I think you are right about some game happening, but I'm not sure it's cat and mouse. To me, an incomplete question feels like an invitation to play 20 questions regarding what the real problem is. So I get a little annoyed, and often just bypass the post. If I answer, the residual annoyance sometimes leads me to withhold my best guess, and complain instead. Hence probably the cat and mouse impression. Not very big of me, but OTOH a think a bit of a nudge towards better questions is not a bad thing. OTO3H, maybe I should just silently pass up 20-questions invitations and not pollute this pleasant space with perfumes of annoyance (since however diffuse, they are apparently pungent enough for some to notice ;-) If it helps, I find the entertainment value of the gentle nudging is the only thing that makes the smell of stupid questions bearable. It isn't true that there is no such thing as a stupid question. There are intelligent questions that are asked in a rude and stupid way. Expecting people to read your mind and understand what your question is about is rude. Expecting people to decipher poorly written, badly spelt, incomprehensible ramblings is rude. (Allowance should be made for those whose native language is not English, and those with good excuses for bad spelling, eg broken keyboard, actual dyslexia.) Some allowance for the occasional brain-fart or typo should be made, but communication requires two parties. You wouldn't expect a mail server to accept any random malformed packets and try to make sense of it, and you shouldn't expect others to put in more work understanding your post than you put in writing it. As they say, be strict when sending and tolerant when receiving. I'm all for that. But when people insist on sending broken packets, I see nothing rude about bouncing those packets back with a error message or a creative misunderstanding. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: __eq__ on a dict
These methods are documanted here: http://docs.python.org/ref/customization.html -- http://mail.python.org/mailman/listinfo/python-list
Re: __eq__ on a dict
On Mon, 11 Jul 2005 12:42:55 +0200, Neil Benn wrote: Hello, I can't find the docs for __eq__ on a dict and I can't find a description on what the eq does (strangely it does implement and but I have no idea what that does). Does anyone know (definitively) what the __eq__, __gt__, __lt__ methods do. BTW, google is not my friend - I invited it out for a drink last week and it stood me up :-). It works for me. Google on __eq__ Python and the 5th and 6th sites are: http://python.active-venture.com/ref/customization.html http://www.network-theory.co.uk/docs/pylang/ref_32.html Normally, asking Python for help is a good way to read the docs, but in this particular case, it is a big let-down: py help({}.__eq__) Help on method-wrapper: __eq__ = method-wrapper object For any two objects x and y, when you call x == y Python calls x.__eq__(y). That includes dicts: py dictA = {0: spam} py dictB = {0: sp + am} py dictC = {1: ham} py py dictA == dictB True py dictA.__eq__(dictB) # same as dictA == dictB True py dictB == dictC # calls dictB.__eq__(dictC) False Two dicts are equal if they have the same keys and the same values. In general, you should not call __eq__ directly, but use the == operator instead. Likewise: x y becomes x.__gt__(y) x y becomes x.__lt__(y) x = y becomes x.__ge__(y) x = y becomes x.__le__(y) x != y becomes x.__ne__(y) x y also becomes x.__ne__(y) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: __eq__ on a dict
[EMAIL PROTECTED] wrote: These methods are documanted here: http://docs.python.org/ref/customization.html Hmm, can't see anything about implementation of python dict methods __eq__, __lt__ or __gt__ there - general docs but not specific to the dict here - at least not as far as I can see from these docs. Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
Re: __eq__ on a dict
Steven D'Aprano [EMAIL PROTECTED] writes: On Mon, 11 Jul 2005 12:42:55 +0200, Neil Benn wrote: Hello, I can't find the docs for __eq__ on a dict and I can't find a description on what the eq does (strangely it does implement and but I have no idea what that does). Does anyone know (definitively) what the __eq__, __gt__, __lt__ methods do. [snip] For any two objects x and y, when you call x == y Python calls x.__eq__(y). That includes dicts: py dictA = {0: spam} py dictB = {0: sp + am} py dictC = {1: ham} py py dictA == dictB True py dictA.__eq__(dictB) # same as dictA == dictB True py dictB == dictC # calls dictB.__eq__(dictC) False Two dicts are equal if they have the same keys and the same values. That is what I would expect, but where is that documented? Also, where is the behavior of the much less obvious dictionary methods __ge__, __gt__, __le__, __lt__, and __cmp__ methods documented? In general, you should not call __eq__ directly, but use the == operator instead. That is clear enough, the OP was seeking information about the behavior of these operators when used with dictionaries. Thanks, -- Aaron Bingham Senior Software Engineer Cenix BioScience GmbH -- http://mail.python.org/mailman/listinfo/python-list
Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
Reinhold Birkenfeld schrieb: Kay Schluehr wrote: Dan Sommers schrieb: How about this: def __init__(self, self.x, y, self.z): # self.x, self.z from first and third explicit parameters do_something_with_y() Can you tell me in which way it is anyhow better than the original proposal def __init__(self, .x, y, .z): # self.x, self.z from first and third explicit parameters do_something_with_y() besides that it is more verbose? It is more explicit. Explicit is better than implicit. The punctuation syntax makes it explicit too. But maybe a point is a more tiny and less explicit symbol than an @ that makes a decorator explicit ;) But as with many proposals, this raises consequential questions, for example, how self.x parameters are handled in other methods, or even functions, as __init__ is not special-cased by the parser. Reinhold Yes. My argument against the syntax is more that of a language lawyer: how a class uses the argument parameters of a constructor is an implementation detail of a class and should not be published in the constructor interface. One may assign special attributes to the classes ( e.g. tagging it with a metaclass ) or a qualifier. I had recently a look on Scala an object-functional language running on top of the JVM. Scala introduces the concept of a case class to represent object trees. All arguments passed into a case class constructor become automagically object attributes. This is for convenience and let the tree grow if the passed arguments are case class instances again. Here it is the class type that determines how it's construction is handled. I think this is a reasonable approach. Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: math.nroot [was Re: A brief question.]
Tim Peters [EMAIL PROTECTED] writes: [Tim Peters] All Python behavior in the presence of infinities, NaNs, and signed zeroes is a platform-dependent accident, mostly inherited from that all C89 behavior in the presence of infinities, NaNs, and signed zeroes is a platform-dependent crapshoot. [Michael Hudson] As you may have noticed by now, I'd kind of like to stop you saying this :) -- at least on platforms where doubles are good old-fashioned 754 8-byte values. [Tim] Nope, I hadn't noticed! I'll stop saying it when it stops being true, though wink. Note that since there's not even an alpha out for 2.5 yet, none of the good stuff you did in CVS counts for users yet. [Michael] Well, obviously. OTOH, there's nothing I CAN do that will be useful for users until 2.5 actually comes out. Sure. I was explaining why I keep saying what you say you don't want me to say: until 2.5 actually comes out, what purpose would it serve to stop warning people that 754 special-value behavior is a x-platform crapshoot? Much of it (albeit less so) will remain a crapshoot after 2.5 comes out too. Well, OK, I phrased my first post badly. Let me try again: I want to make this situation better, as you may have noticed. But first, I'm going to whinge a bit, and lay out some stuff that Tim at least already knows (and maybe get some stuff wrong, we'll see). Floating point standards lay out a number of conditions: Overflow (number too large in magnitude to represent), Underflow (non-zero number to small in magnitude to represent), Subnormal (non-zero number to small in magnitude to represent in a normalized way), ... The 754 standard has five of them: underflow, overflow, invalid operation, inexact, and divide by 0 (which should be understood more generally as a singularity; e.g., divide-by-0 is also appropriate for log(0)). OK, the decimal standard has more, which confused me for a bit (presumably it has more because it doesn't normalize after each operation). The conditions in IBM's decimal standard map, many-to-one, on to a smaller collection of signals in that standard. It has 8 signals: the 5 I named above from 754, plus clamped, rounded, and subnormal. Distinctions are excruciatingly subtle; e.g., rounded and inexact would be the same thing in 754, but, as you suggest, in the decimal standard a result can be exact yet also rounded (if it rounds away one or more trailing zeroes), due to the unnormalized model. Right, yes, that last one confused me for a while. Why doesn't 754 have subnormal? Actually, I think I'm confused about when Underflow is signalled -- is it when a denormalized result is about to be returned or when a genuine zero is about to be returned? For each condition, it should (at some level) is possible to trap each condition, or continue in some standard-mandated way (e.g. return 0 for Underflow). 754 requires that, yes. While ignoring the issue of allowing the user to control this, I do wish sometimes that Python would make up it's mind about what it does for each condition. Guido and I agreed long ago that Python should, by default, raise an exception on overflow, invalid operation, and divide by 0, and should not, by default, raise an exception on underflow or inexact. And, I'll add, should not on rounded, clamped and subnormal too. Sure, but we already have a conforming implementation of 854 with settable traps and flags and rounding modes and all that jazz. Maybe we should just implement floats in Python. Such defaults favor non-expert use. Experts may or may not be happy with them, so Python should also allow changing the set. Later :) That's a problem, though. 754 subsets are barely an improvement over what Python does today: Well, my contention is that the consistent application of one particular 754 subset would be an improvement. Maybe I'm wrong! (In the mean time can we just kill fpectl, please?) Has it been marked as deprecated yet (entered into the PEP for deprecated modules, raises deprecation warnings, etc)? I don't know. IMO it should become deprecated, but I don't have time to push that. A bit of googling suggests that more people pass --with-fpectl to configure than I expected, but I doubt more than 1% of those actually use the features thus provided (of course, this is a guess). There are a bunch of conditions which we shouldn't and don't trap by default -- Underflow for example. For the conditions that probably should result in an exception, there are inconsistencies galore: inf = 1e300 * 1e300 # - Overflow, no exception nan = inf/inf # - InvalidOperation, no exception Meaning you're running on a 754 platform whose C runtime arranged to disable the overflow and invalid operation traps. Isn't that the standard-mandated start up environment? The 754 standard mandates non-stop mode (all traps disabled) at
Re: __eq__ on a dict
Steven D'Aprano wrote: On Mon, 11 Jul 2005 12:42:55 +0200, Neil Benn wrote: Hello, I can't find the docs for __eq__ on a dict and I can't find a description on what the eq does (strangely it does implement and but I have no idea what that does). Does anyone know (definitively) what the __eq__, __gt__, __lt__ methods do. BTW, google is not my friend - I invited it out for a drink last week and it stood me up :-) . It works for me. Google on __eq__ Python and the 5th and 6th sites are: http://python.active-venture.com/ref/customization.html http://www.network-theory.co.uk/docs/pylang/ref_32.html snip As previous reply Normally, asking Python for help is a good way to read the docs, but in this particular case, it is a big let-down: py help({}.__eq__) Help on method-wrapper: __eq__ = method-wrapper object For any two objects x and y, when you call x == y snip snip That's the empirical evidence that I got but I want to be 100% sure that this holds in all cases - I'm wary about using empirical evidence leading to assumptions in my code - I take the paradigm that 'Assumption is the mother of all f**k-ups'. In general, you should not call __eq__ directly, but use the == operator instead. snip Yeah I'm aware of that, I didn't want to start talking about ==, etc or I may mislead people into the - this is what __eq__ means path of explanation. Thanks for your response. Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
On Mon, 11 Jul 2005 08:34:45 +0200, Reinhold Birkenfeld [EMAIL PROTECTED] wrote: Kay Schluehr wrote: Dan Sommers schrieb: How about this: def __init__(self, self.x, y, self.z): # self.x, self.z from first and third explicit parameters do_something_with_y() Can you tell me in which way it is anyhow better than the original proposal def __init__(self, .x, y, .z): # self.x, self.z from first and third explicit parameters do_something_with_y() besides that it is more verbose? It is more explicit. Explicit is better than implicit. But as with many proposals, this raises consequential questions, for example, how self.x parameters are handled in other methods, or even functions, as __init__ is not special-cased by the parser. So why limit it to __init__? Bengt Richter's idea of generalizing it is a good one. Currently, when this method: def f(self, x, y, z): pass is called, Python binds self to a reference to the object, x to the first argument, y to the second argument, z to and the third. By extension, hypothetically, this method: def new_f(self, self.x, y, self.z): do_something_with_y() would be semantically identical to: def new_f(self, __anonymous_argument_1, y, __anonymous_argument_2): self.x = __anonymous_argument_1 del __anonymous_argument_1 # look: a use case for del! wink self.z = __anonymous_argument_2 del __anonymous_argument_2 do_something_with_y() It's not too far from the tuple unpacking that happens now: def g(x, (a, b)): pass q = (3, 4) g(1, q) # inside g, x = 1, a = q[0] = 3, b = q[1] = 4 and it's certainly not less explicit than properties. Without thinking it all the way through, I suppose these: def method_1(self, *self.l): pass def method_2(self, **self.d): pass could act as if they were these: def method_1(self, *args): self.l = args del args def method_2(self, **kw): self.d = kw del kw Regards, Dan -- Dan Sommers http://www.tombstonezero.net/dan/ -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators as generalized pre-binding hooks
George Sakkis schrieb: 1. classes have metaclasses, functions don't have metafunctions. No one gave an example for classes not handled at least as well with a metaclass. Would something like the following count ? @abstractclass class AbstractFrame(object): @abstractclass @innerclass class AbstractPanel(object): pass For one thing, it's more readable than the respective __metaclass__ declarations. Moreover, stacking two or more decorators is syntactically straightforward, while for metaclasses you have to write boilerplate code for making a subclass of the components, e.g.: class AbstractInnerClass(AbstractClass, InnerClass): pass Fortunately metaclasses are not that commonly used to cause combinatorial explosion of such boilerplate classes. I think it would be a good idea to pronounce the similarity between function decorators and metaclasses. Metaclasses were once introduced as an arcane art of fuzzy bearded hackers or supersmart 'enterprise architects' that plan at least products of Zope size but not as a tool for the simple programmer on the street. But maybe they should be and there should also be librarys of them representing orthogonal customizations ready for plug in. Since metaclasses follow an adapt, customize or decorate semantics it is a good idea not to use inheritance to stack them which implies that one metaclass refines an other. +1 for metaclasses as class decorators. Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: __eq__ on a dict
Use the source, Luke dict_richcompare: http://fisheye.cenqua.com/viewrep/python/python/dist/src/Objects/dictobject.c?r=2.165#l1510 dict_compare: http://fisheye.cenqua.com/viewrep/python/python/dist/src/Objects/dictobject.c?r=2.165#l1425 /Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators as generalized pre-binding hooks
Kay Schluehr wrote: I think it would be a good idea to pronounce the similarity between function decorators and metaclasses. Metaclasses were once introduced as an arcane art of fuzzy bearded hackers or supersmart 'enterprise architects' that plan at least products of Zope size but not as a tool for the simple programmer on the street. But maybe they should be and there should also be librarys of them representing orthogonal customizations ready for plug in. In which case, I point out the need for better, more accessible documentation. The Python 2.4 tutorial, for example, doesn't mention them at all as far as I've noticed. -- http://mail.python.org/mailman/listinfo/python-list
Re: pyo contains absolute paths
V Sat, 09 Jul 2005 10:22:06 -0400, Peter Hansen napsal(a): David Siroky wrote: When I compile my python files with python -OO into pyo files then they still contain absolute paths of the source files which is undesirable for me. How can I deal with that? Don't do that? Delete the pyo files? Stop using Python? I could guess at a few more possibilities, but since you don't actually say what you *want* to happen, just what you don't want to happen, there are an infinite number of ways to satisfy you right now. wink (Hint #1: absolute paths are always, AFAIK, put into the .pyc or .pyo files.) (Hint #2: maybe explaining why you don't want this to happen would help too, since that will probably determine the best solution.) -Peter I want to write a commercial application in Python and I don't want the customer to see the source code and absolute paths of my modules which have btw. the same base path as the main module so I would expect only relative paths in the compiled files. David -- http://mail.python.org/mailman/listinfo/python-list
Re: pyo contains absolute paths
V Sat, 09 Jul 2005 11:48:51 -0700, ncf napsal(a): Python is compiling the files with absolute paths because it is much faster to load a file when you know where it is, than to have to find it and then load it. I'm guessing you're wondering this so you can distribute it compiled or such? If so, I wouldn't do that in the first place. Python's compiled files might be version/architecture dependant. -NcF I want to write a commercial application in Python and I don't want the customer to see the source code and absolute paths of my modules which have btw. the same base path as the main module so I would expect only relative paths in the compiled files. David -- http://mail.python.org/mailman/listinfo/python-list
cursor positioning
Dear All, I am writing a database import script in python and I would like to print the percentage of the process to the last line. I would like to update the last line at every percent. You know what I mean. How can the cursor be positioned to the last line or somewhere else on the screen? Curses starts with clearing the whole screen and it is overkill. Many modules are on the net but I would like to resolve this simply task with native python. I tried: for something: print chr(8)*20+mystring, but it is nasty and didn't work well. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: PPC floating equality vs. byte compilation
Terry Reedy [EMAIL PROTECTED] writes: Tim Peters [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] [Donn Cave] I ran into a phenomenon that seemed odd to me, while testing a build of Python 2.4.1 on BeOS 5.04, on PowerPC 603e. test_builtin.py, for example, fails a couple of tests with errors claiming that apparently identical floating point values aren't equal. But it only does that when imported, and only when the .pyc file already exists. Not if I execute it directly (python test_builtin.py), or if I delete the .pyc file before importing it and running test_main(). This is a known problem with marshalling INFs and/or NANs. I hope you've also read all the bits and pieces where Tim says whatever happens to INFs and NANs is a platform dependent crapshoot. We don't test platform dependent crapshoots in test_builtin (or at least, I hope not!). *This* has supposedly been fixed for 2.5. Actually, it's likely that Donn's failure has been fixed for Python 2.5 as well, at least if Tim's guess is correct, because the C string-float routines aren't invovled in loading .pycs any more. It would be most helpful to open a bug report, with the output from failing tests. And assign to Tim. That's mean! :) In general, this can happen if the platform C string-float routines are so poor that eval(repr(x)) != x ... The ultimate cause is most likely in the platform C library's string-float routines (sprintf, strtod, that kind of thing). It would also be helpful if you could do some tests in plain C (no Python) testing, for instance, the same values that failed. Hardly anyone else can ;-). If you confirm a problem with the C library, you can close the report after opening, leaving it as a note for anyone else working with that platform. I agree with this bit! Cheers, mwh -- 112. Computer Science is embarrassed by the computer. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html -- http://mail.python.org/mailman/listinfo/python-list
httplib/HTTPS Post Problem
Hi, Sorry to post what might seem like a trivial problem here, but its driving me mad! I have a simple https client that uses httplib to post data to a web server. When I post over http https using curl the data is recieved by the web server with no problems. When I post using my python client the headers get there, but the body of the message does not. My code is pretty standard and has the format: httplib.HTTPSConnection.debuglevel = 1 connection = httplib.HTTPSConnection(host_name, key_file = key, cert_file = cert) connection.putrequest(POST, path) connection.putheader(Content-Length, str(len(body))) ...(some more headers)... connection.endheaders() connection.send(body) response = connection.getresponse() connection.close() (some code has been removed for clarity).. I can see in the debug messages the body getting sent, but nothing arrives at the server... I think I would understand whats going on better if I knew how Python uses the underlying socket - does it a) open the socket, send the header body together or b) send the header, wait, then send the body? I think the answer to this question solve my problem - can anyone help? Thanks. p.s. I'm using Python 2.3.3 [GCC 3.3.3 (SuseLinx)] -- http://mail.python.org/mailman/listinfo/python-list
Re: pyo contains absolute paths
David Siroky [EMAIL PROTECTED] writes: Hi! When I compile my python files with python -OO into pyo files then they still contain absolute paths of the source files which is undesirable for me. How can I deal with that? Are you trying to save space? In 2.4 and later each code object will contain the same copy of the absolute path, so you can't save that much space. There are probably ways to make .pycs that have a path of , if you really want (see py_compile in the stdlib). Cheers, mwh -- I located the link but haven't bothered to re-read the article, preferring to post nonsense to usenet before checking my facts. -- Ben Wolfson, comp.lang.python -- http://mail.python.org/mailman/listinfo/python-list
Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
Dan Sommers wrote: Without thinking it all the way through, I suppose these: def method_1(self, *self.l): pass def method_2(self, **self.d): pass could act as if they were these: def method_1(self, *args): self.l = args del args def method_2(self, **kw): self.d = kw del kw I still think it's too specialized. What would, hypothetically, this do? class Bar: pass class Foo: x = Bar() def method_1(self, x.y): pass It's hard to explain that you can autoassign self.y but not x.y. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: importing files from a directory
Am Sat, 09 Jul 2005 20:30:04 -0700 schrieb spike grobstein: I'm a total Python newbie, so bear with me here... I'm writing a program that has a user-configurable, module-based architecture. it's got a directory where modules are stored (.py files) which subclass one of several master classes. [cut] for item in dir_list: # strip off the extensions... if (item == __init__.py): continue elif (item[-3:] == '.py'): item.endswith(.py) would be more python-like. mod_name = item[:-3] elif (item[-4:] == '.pyc'): elif item.endswith(.pyc): continue # Don't load module twice else: continue print Loading %s... % mod module_list.append(__import__(Modules.%s % mod)) print Done. it works more or less like I expect, except that... A. the first time it runs, blah.py then has a blah.pyc counterpart. When I run the program again, it imports it twice. Not horrible, but not what I want. is there any way around this? See above: Just don't load it. The compiled pyc file is taken automatically if it is newer than the py file. B. module_list winds up consisting of items called 'Modules.blah' and I'd like to have just blah. I realize I could say: my_module = __import__(Modules.%s % mod) module_list.append(getattr(my_module, mod)) I use this getattr() after __import__, too. I don't think there is a easier way. HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: httplib/HTTPS Post Problem
Am Mon, 11 Jul 2005 06:29:23 -0700 schrieb michaelparkin: Hi, Sorry to post what might seem like a trivial problem here, but its driving me mad! I have a simple https client that uses httplib to post data to a web server. When I post over http https using curl the data is recieved by the web server with no problems. When I post using my python client the headers get there, but the body of the message does not. Hi, can you look at the access log of the server? A slash at the end of a URL is important (www.google.com/ is different from www.google.com) response = connection.getresponse() What does print response do? You can listen on the wire with ethereal (Capture, then follow tcp-stream) HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyo contains absolute paths
David Siroky wrote: When I compile my python files with python -OO into pyo files then they still contain absolute paths of the source files which is undesirable for me. How can I deal with that? Use the script compileall.py (in Lib) to compile all the files. This script has an option -d dir that allows to set the directory name compiled into the .pyo files. From the help: -d destdir: purported directory name for error messages Daniel -- http://mail.python.org/mailman/listinfo/python-list
ImportError: No module named numarray
when i write a code to import some module like the following : from nltk.probability import ConditionalFreqDist I got the error : Traceback (most recent call last): File "C:\Python24\toky.py", line 1, in -toplevel- from nltk.probability import ConditionalFreqDist File "C:\Python24\Lib\site-packages\nltk\probability.py", line 56, in -toplevel- import types, math, numarrayImportError: No module named numarray can you please tell me the cause Sell on Yahoo! Auctions - No fees. Bid on great items.-- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp development with macros faster than Python development?..
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Well, his Viaweb company was founded in about '95, right? So he probably just used Lisp because Python wasn't as well known yet. ;-) David That is what I thought too. It makes sense but I wasn't sure. Still ain't. The problem is that questions like 'What lang is fastest to develop in?' are hard to answer definitively. No it's not. The answer is always whatever language you enjoy the most and know the best. That's a somewhat redundant statement because if you enjoy a language, you are highly motivated to use it often and learn it well. An intimate knowledge of any particular language is *far* more important than the syntactic and semantic arcana that people usually argue over. So - what the question really boils down to is which language(s) have the best balance of approachability (easy to learn!) and capability. Bear in mind though, that if the language sacrifices capability in favor of being easy, then the fun runs out of it too soon :-) Thomas Bartkus -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
While not curses based this class will update screen as you want. You could use it as a basis upon which to do a curses version with your cursor positioning. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 -Larry Bates Mage wrote: Dear All, I am writing a database import script in python and I would like to print the percentage of the process to the last line. I would like to update the last line at every percent. You know what I mean. How can the cursor be positioned to the last line or somewhere else on the screen? Curses starts with clearing the whole screen and it is overkill. Many modules are on the net but I would like to resolve this simply task with native python. I tried: for something: print chr(8)*20+mystring, but it is nasty and didn't work well. Mage -- http://mail.python.org/mailman/listinfo/python-list
relative import packages/modules workaround
Hello all, I've read all the posts concerning relative imports of modules and I am glad I saw some consensus on a syntax. At this moment I am however bound to python 2.3. Does anyone know a good workaround (or a library) which can achieve a relative import for this python version kind regards Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
Larry Bates wrote: While not curses based this class will update screen as you want. You could use it as a basis upon which to do a curses version with your cursor positioning. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 Thank you. This is good for displaying the percentage. However it fails to display this: 100 files read 200 files read 300 files read of course all in the same line and not under the last line. Mage -- http://mail.python.org/mailman/listinfo/python-list
RE: cursor positioning
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Mage Sent: 11 July 2005 04:28 PM To: python-list@python.org Subject: Re: cursor positioning Larry Bates wrote: While not curses based this class will update screen as you want. You could use it as a basis upon which to do a curses version with your cursor positioning. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 Thank you. This is good for displaying the percentage. However it fails to display this: 100 files read 200 files read 300 files read of course all in the same line and not under the last line. Mage -- Why not use something like this? counter = 0 while 1: if (counter % 100) == 0: print'%s files read '%counter counter += 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python exception hook simple example needed
Ed Leafe wrote: On Jul 7, 2005, at 7:27 AM, Fuzzyman wrote: Do you have an exception handling dialog ? Not per se, as there hasn't been a request for one; we have several dialogs ranging from simple messages to alerts to interactive dialogs, much as wxPython offers. But I'll make this offer: give me a spec as to what you need this exception handling dialog to do, and I'll have it added to the framework within 24 hours. Deal? Hello Ed, It's a brilliant offer - and dabo sounds very interesting. I was responding to someone else's question though ! Next time I need to code a GUI app I'll take a look at dabo. Thanks Fuzzy http://www.voidspace.org.uk/python Can you use the UI layer without being tied to the rest of the framework ? They seemed pretty integrated to me. They are integrated, but nothing forces you to use anything you don't want. I know of several people who have developed UI-only apps, with no need for business objects or database connectivity. They started in plain wxPython, and switched to Dabo because it was so much easier, and so much more Pythonic. ___/ / __/ / / Ed Leafe http://leafe.com/ http://dabodev.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
I haven't tried this myself, but I think the secret to displaying a continuously updating %done on the command line is to print file 100, 1% done then send exactly 7 backspaces to the terminal, then print 2% done... so the backspaces will write over the previous text. Backspace is a \x08 (ascii character with the value 8.) It _could_ work... -Jim On 7/11/05, Albert Leibbrandt [EMAIL PROTECTED] wrote: -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Mage Sent: 11 July 2005 04:28 PM To: python-list@python.org Subject: Re: cursor positioning Larry Bates wrote: While not curses based this class will update screen as you want. You could use it as a basis upon which to do a curses version with your cursor positioning. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 Thank you. This is good for displaying the percentage. However it fails to display this: 100 files read 200 files read 300 files read of course all in the same line and not under the last line. Mage -- Why not use something like this? counter = 0 while 1: if (counter % 100) == 0: print'%s files read '%counter counter += 1 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
James Carroll wrote: I haven't tried this myself, but I think the secret to displaying a continuously updating %done on the command line is to print file 100, 1% done then send exactly 7 backspaces to the terminal, then print 2% done... so the backspaces will write over the previous text. Backspace is a \x08 (ascii character with the value 8.) It _could_ work... I tried but printing backslashes won't work in a loop (i think the screen was not refreshed correctly). You can use stdout and flush. Actually I am using this: for (s,i) in [(list[i],i) for i in range(len(list))]: content = file(s).read() sys.stdout.write(chr(8)*35 + str(i + 1) + ' of ' + str(len(list)) + ' files read') sys.stdout.flush() Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: importing files from a directory
my reason for loading both the .py and .pyc files was just in case compiled files were supplied as modules... but I'm gonna disallow that, so yeah. I also got a response in email and I've been dabbling with my code since I posted this and found a slightly better way of handling this plugin system... I stuck the import code into the Modules/__init__.py file, so it can act as a kind of manager (instead of moving the files to a Modules(disabled) directory) and appended the __import__s to an array. like this: [EMAIL PROTECTED] ~/Aphex $ cat Modules/__init__.py module_list = [] def load_module(mod_name): mod = __import__(Modules.%s % mod_name) mod = getattr(mod, mod_name) module_list.append(mod.module()) def load_modules(): load_module(nes) load_module(snes) load_module(mame) load_modules() [end code] I then just have to 'import Modules' from my main program and the whole module import thing is encapsulated and invisible to my main program. I'm gonna add some functions to the Modules module to make fetching plugins a little less ambiguous (get_module(index) and get_named_module(module_name), etc). Thanks for the help. Python's making me have to think a little backwards. I have to make sure I declare my functions before I call them, but it's a very cool language overall. ...spike -- http://mail.python.org/mailman/listinfo/python-list
Re: Read-only class properties
On Sun, 10 Jul 2005 21:10:36 -0700, Michael Spencer [EMAIL PROTECTED] wrote: Bengt Richter wrote: ... class Foo(object): class __metaclass__(type): def __setattr__(cls, name, value): if type(cls.__dict__.get(name)).__name__ == 'Descriptor': raise AttributeError, 'setting Foo.%s to %r is not allowed' %(name, value) type.__setattr__(cls, name, value) @classproperty def TheAnswer(cls): return The Answer according to %s is 42 % cls.__name__ @classproperty def AnotherAnswer(cls): return Another Answer according to %s is 43 % cls.__name__ or, simply put the read-only descriptor in the metaclass: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. def classproperty(function): ... class Descriptor(object): ... def __get__(self, obj, objtype): ...return function(objtype) ... def __set__(self, obj, value): ... raise AttributeError, can't set class attribute ... return Descriptor() ... class A(object): ... class __metaclass__(type): ... @classproperty ... def TheAnswer(cls): ... return The Answer according to %s is 42 % cls.__name__ ... A.TheAnswer 'The Answer according to __metaclass__ is 42' A.TheAnswer = 3 Traceback (most recent call last): File input, line 1, in ? File input, line 6, in __set__ AttributeError: can't set class attribute class B(A): pass ... B.TheAnswer 'The Answer according to __metaclass__ is 42' this means that the getter doesn't automatically get a reference to the class (since it is a method of metaclass), which may or may not matter, depending on the application It appears that you can use an ordinary property in the metaclass, and get the reference: (I tried doing this but I still had the classproperty decorator and somehow inside a metaclass it bombed or I typoed, and I forgot to try the plain property, so I hacked onwards to the more involved __setattr__ override). Anyway, class A(object): ... class __metaclass__(type): ... def TheAnswer(cls): ... return The Answer according to %s is 42 % cls.__name__ ... def __refuse(cls, v): ... raise AttributeError, Refusing to set %s.TheAnswer to %r%(cls.__name__, v) ... TheAnswer = property(TheAnswer, __refuse) ... ... A.TheAnswer 'The Answer according to A is 42' A.TheAnswer = 123 Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 6, in __refuse AttributeError: Refusing to set A.TheAnswer to 123 Of course, access through an instance won't see this: a=A() a.TheAnswer Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'A' object has no attribute 'TheAnswer' since TheAnswer is found in type(a)'s mro, but not type(A)'s: type(a).mro() [class '__main__.A', type 'object'] type(A).mro() Traceback (most recent call last): File stdin, line 1, in ? TypeError: descriptor 'mro' of 'type' object needs an argument looks like you get type.mro as an unbound method that way... type(A).mro(type(A)) [class '__main__.__metaclass__', type 'type', type 'object'] or type.mro(A) [class '__main__.A', type 'object'] type.mro(type(A)) [class '__main__.__metaclass__', type 'type', type 'object'] or even type.__dict__['mro'] method 'mro' of 'type' objects type.__dict__['mro'](A) [class '__main__.A', type 'object'] type.__dict__['mro'](type(A)) [class '__main__.__metaclass__', type 'type', type 'object'] type(A) class '__main__.__metaclass__' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
Here's a simple module for doing progress reporting. On systems without curses, it simply uses \r to return the cursor to the first column. On systems with curses, it also clears to the end of the line. This means that when the progress message gets shorter, there aren't droppings left from the longer ones. You have to take care that the progress message isn't wider than the screen, but I don't know a nice way to *find* the width of the screen that will work on windows and unix. Hardcoding 80 ain't it either. import sys def progress(s): sys.stderr.write(s + CLEAR_EOL + \r); sys.stderr.flush() try: import curses except ImportError: CLEAR_EOL = '' else: curses.setupterm() CLEAR_EOL = curses.tigetstr(el) or '' def test(): import time for j in range(2): for i in range(100): progress(Doing item %d, %d%% % (i * 100, i)) time.sleep(.01) if __name__ == '__main__': test() pgpzfL5bt0IvZ.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Getting files in a subdirectory in a zip
What would the best way to get a list of files in a subdirectory in a zip? The only thing I can come up with is to extract the zip into a temp directory and then just grab the list of files in the subdirectory that I need. This way seems very messy to me and I was wondering if there are any better ways. -- -Echo -- http://mail.python.org/mailman/listinfo/python-list
regular expression questions in Python
I am (very) new top regular expressions and I am having a difficult time understanding how to do them. I have the following in my script: zaidsearch = r'''^ {5,}([\d]{4,5})(.\d{2,2}c)''' ZAIDSearch = re.compile(search, re.IGNORECASE) When I do: ZAID.search(...) then this works fine. I would like to write it as: zaidsearch = r'''^ {5,}([\d]{4,5}) #My comments (.\d{2,2}c)#More of my comments''' ZAIDSearch = re.compile(zaidsearch, re.VERBOSE) but this doesn't work. I get the following error: raise error, v # invalid expression sre_constants.error: nothing to repeat So I guess my question is: how do I use the VERBOSE option to make my regular expression easier to understand for a human? Secondly, how can I use both the VERBOSE and IGNORECASE options? Thanks, Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I use if or try (as a matter of speed)?
def joels_function(args): error_result = 0 good_result = None process(args) if error_condition(): error_result = -1 # flag for an error elif different_error_conditon(): error_result = -2 else: more_processing() if another_error_conditon(): error_result = -3 do_more_work() good_result = Success! if error_result != 0: return (False, error_result) else: return (True, good_result) and then call it with: status, msg = joels_function(args) if status == False: print msg # and fail... else: print msg # and now continue... This is how I would write it in Python: def my_function(args): process(args) if error_condition(): raise SomeError(An error occurred) elif different_error_conditon(): raise SomeError(A different error occurred) more_processing() if another_error_conditon(): raise SomeError(Another error occurred) do_more_work() return Success! and call it with: try: result = my_function(args) print Success!!! except SomeError, msg: print msg # and fail... # and now continue safely here... In the case of Python, calling a function that may raise an exception is I tend to use exceptions, but I think Joel has a point. Taking the example code that you have given above. Let us assume that somebody else is using my_function and DOES NOT write a try except block. This code will run fine except, when the exception is thrown and it will suddenly pop up in some other error handler which may not be handling the situation correctly. You have to plan and create a series of errorhandling classes to handle such situations. However Joels_function forces the caller to write some kind of error handler. If he doesnt write the program will not run. After reading that I have been giving this option some thought. The nice thing about Python is I can easily return tuples. In C++ you have to jump through hoops because you cant return two values easily. DarkCowherd -- http://mail.python.org/mailman/listinfo/python-list
Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
On Mon, 11 Jul 2005 01:44:07 -0400, Terry Reedy [EMAIL PROTECTED] wrote: Bengt Richter [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Me too. I liked the leading _, but on second thought it is a weird language change re names in a special context. Probably not so good. To repeat: while my '_' proposal could have been for a language change (in 3.0), it was actually for a convention recognized by a metaclass or, more likely, decorator (and implementable now, I think). *Any* flag would serve the purpose, but I picked one that was a single char while being visually striking and, as far as I know, rarely used in current practice even though quite legal. A 'self_' prefix would do as well except for being more to type. The prefix could even be an argument to the decorator! Yes, sorry, I should have read more carefully. Yours is the high ground ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet Another Python Web Programming Question
Python using CGI, for example, was enough for him until he started getting 500 errors that he wasn't sure how to fix. A common error is that python cgi files need line endings to be in unix text file format, not windows text file format (\n instead of \r\n) [1]. Why this is, I don't know, but it causes a lot of errors for windows folks. I'm a frequent linux/windows switcher, and it's caused me no end of troubles - if you're getting premature end of script headers in your apache error logs, this may be your problem. Peace Bill Mill bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression questions in Python
Jeremy wrote: I am (very) new top regular expressions and I am having a difficult time understanding how to do them. I have the following in my script: zaidsearch = r'''^ {5,}([\d]{4,5})(.\d{2,2}c)''' ZAIDSearch = re.compile(search, re.IGNORECASE) When I do: ZAID.search(...) then this works fine. I would like to write it as: zaidsearch = r'''^ {5,}([\d]{4,5}) #My comments ^ This space will not be a space in the RE. You have to specify a space with '[ ]' or '\ ' when using re.VERBOSE (.\d{2,2}c)#More of my comments''' ZAIDSearch = re.compile(zaidsearch, re.VERBOSE) but this doesn't work. I get the following error: raise error, v # invalid expression sre_constants.error: nothing to repeat Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators as generalized pre-binding hooks
Christopher Subich schrieb: Kay Schluehr wrote: I think it would be a good idea to pronounce the similarity between function decorators and metaclasses. Metaclasses were once introduced as an arcane art of fuzzy bearded hackers or supersmart 'enterprise architects' that plan at least products of Zope size but not as a tool for the simple programmer on the street. But maybe they should be and there should also be librarys of them representing orthogonal customizations ready for plug in. In which case, I point out the need for better, more accessible documentation. The Python 2.4 tutorial, for example, doesn't mention them at all as far as I've noticed. That's true also for properties and decorators - the latter may be excused because they are new in Python 2.4. There are a few good documents out there explaining advanced stuff e.g. mro and descriptors. Maybe those texts should be delivered with the doc and linked from the tutorial as further reading? But maybe the whole document structure could be redesigned providing a Wikipedia style with seperated but linked articles, example code etc. ? Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
On Mon, 11 Jul 2005 15:37:35 +0200, Reinhold Birkenfeld [EMAIL PROTECTED] wrote: Dan Sommers wrote: Without thinking it all the way through, I suppose these: def method_1(self, *self.l): pass def method_2(self, **self.d): pass could act as if they were these: def method_1(self, *args): self.l = args del args def method_2(self, **kw): self.d = kw del kw I still think it's too specialized. What would, hypothetically, this do? class Bar: pass class Foo: x = Bar() def method_1(self, x.y): pass It's hard to explain that you can autoassign self.y but not x.y. No, that limitation wouldn't exist, so you wouldn't have to explain it ;-) I.e., the above would act like class Foo: x = Bar() def method_1(self, _anonymous_arg_1): x.y = _anonymous_arg_1 and would do whatever it would do now (probably look for a global x or a closure cell x, but it wouldn't find the class variable in a normal method call) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
Actually, we receive the data in the form of a text file. The original data is sent from an IBM mainframe then to Ottawa where it is captured by an SNA Print Server that receives the VPS print jobs, writes them to disk and then runs a PERL script program on the disk file. This PERL script program scans the file's VPS banner page for key words (e.g. JobName, Destination, Form) and then creates a Plain Text and a Rich Text Format (RTF). This system is available Nationally for every region in Canada. It is unfortunate that our government has been so slow in updating such an old process. Since I don't really know (or have access to) the inner workings of the mainframe or the conversion process, I can't really do much there. The reason why I don't wish to simply replace the printer simply convert it so it can be used on newer printers is because the data will also be used to automate tasks (such as creating form letters to clients). -- http://mail.python.org/mailman/listinfo/python-list
C API : Creating a Py_Method object from a C function.
I've got a pure python module that parses a certain type of file. It has a load() function that allows a callback function to be passed for getting progress information. In straight python, this works fine. However, I'm now trying to use this from a C++ program. The current flow that I'm trying to get is as follows: C++ calls python interface function, passing a C++ function pointer Python interface function stores C++ function pointer Python interface function generates new Py_Object method pointer pointing to a different C python function. (This different function calls the stored C++ function pointer) Python interface function calls python function Python function calls the python method pointer it was passed C python function then calls the stored C++ function pointer. The problem in this workflow is taking the C python function that I've defined (using the standard static PyObject *someFunction(PyObject *self, PyObject *args) method) and converting this into a Py_Object. Any ideas? Py_Method doesn't seem to allow you to generate a new one with your own pointers inside... and I can't see anything else in the docs that might allow me to do this... Thanks for any advice! -- Hugh Macdonald -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting files in a subdirectory in a zip
Echo wrote: What would the best way to get a list of files in a subdirectory in a zip? The only thing I can come up with is to extract the zip into a temp directory and then just grab the list of files in the subdirectory that I need. This way seems very messy to me and I was wondering if there are any better ways. import zipfile z = zipfile.ZipFile('block.zip') names = [name[7:] for name in z.namelist() if name.startswith('others/')] --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
ftputil - uploading many files too long
Hi, When I try to upload many files I get such a error message: Traceback (most recent call last): File I:\Python\my_py\wwwzaci\xcopy_ftp.py, line 51, in ? except: x=host.upload(zdroj, cilFTP,'b') File C:\prg\python24\Lib\site-packages\ftputil\ftputil.py, line 463, in uplo ad self.__copy_file(source, target, mode, open, self.file) File C:\prg\python24\Lib\site-packages\ftputil\ftputil.py, line 452, in __co py_file target = target_open(target, target_mode) File C:\prg\python24\Lib\site-packages\ftputil\ftputil.py, line 265, in file host = self._copy() File C:\prg\python24\Lib\site-packages\ftputil\ftputil.py, line 241, in _cop y return FTPHost(*self._args, **self._kwargs) File C:\prg\python24\Lib\site-packages\ftputil\ftputil.py, line 138, in __in it__ self._session = self._make_session() File C:\prg\python24\Lib\site-packages\ftputil\ftputil.py, line 235, in _mak e_session return ftp_error._try_with_oserror(factory, *args, **kwargs) File C:\prg\python24\Lib\site-packages\ftputil\ftp_error.py, line 78, in _tr y_with_oserror raise TemporaryError(obj) ftputil.ftp_error.TemporaryError: 421 Login Timeout (25 seconds): closing contro l connection. I think its not about many files but because of it takes too long for my ftp server (25s). I tried many things but nothing helps. Any help is appreciated... -- geon -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expresiveness in a Computer Language?
Randy Howard wrote: Keith Thompson wrote (in article [EMAIL PROTECTED]): \/| |\| __\,,\ /,,/__ \||/ | | | jgs (__Y__) /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ == Out of curiosity, does anyone remember who 'jgs' refers to above? http://en.wikipedia.org/wiki/Joan_Stark Brian -- http://mail.python.org/mailman/listinfo/python-list
Tricky Dictionary Question from newbie
Hi all, I have a dictionary containing about 300 items, some of the values being repeated. Both keys and values are strings. How can I turn this thing on its head so that we create a key based on each unique value and build the values based on the keys corresponding to the repeated values? It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} I am still learning Python and have struggled with this for hours before deciding to go for help. Unfortunately, I didn't really know how to search for this in google and decided to post it here. I apologise if this is too basic for this newsgroup... Ric -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Hello, Try that, it may not be the better solution, but it seems to work: #def invertDict(d): # d2 = {} # for k, v in d.iteritems(): # d2.setdefault(v, []).append(k) # return d2 Cyril On 7/11/05, Ric Da Force [EMAIL PROTECTED] wrote: Hi all,I have a dictionary containing about 300 items, some of the values beingrepeated.Both keys and values are strings.How can I turn this thing onits head so that we create a key based on each unique value and build the values based on the keys corresponding to the repeated values?It is hard to explain but this is what I mean:Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This isnot'}I want this to return a new dict with string keys and lists containing the previous keys for repeated values.NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']}I am still learning Python and have struggled with this for hours beforedeciding to go for help.Unfortunately, I didn't really know how to search for this in google and decided to post it here.I apologise if this is toobasic for this newsgroup...Ric--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Hi! Dict = {'rt': 'repeated', 'sr':'repeated', 'gf':'not repeated'} NewDic = {} for k,v in Dict.items(): NewDic.setdefault(v, []).append(k) Regards, mawe -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Hum... I think an iteritems is better, this way, python don't need to create in memory a complete list of couple key, value.On 7/11/05, Markus Weihs [EMAIL PROTECTED] wrote: Hi! Dict = {'rt': 'repeated', 'sr':'repeated', 'gf':'not repeated'} NewDic = {} for k,v in Dict.items(): NewDic.setdefault(v, []).append(k)Regards, mawe-- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Ric Da Force [EMAIL PROTECTED] writes: It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} NewDict = {} for x in Dict.keys(): try: NewDict[Dict[x]].append(x) except KeyError: NewDict[Dict[x]] = [x] -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson It is difficult for men in high office to avoid the malady of self-delusion.- Calvin Coolidge -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Mark Jackson wrote: Ric Da Force [EMAIL PROTECTED] writes: It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} NewDict = {} for x in Dict.keys(): try: NewDict[Dict[x]].append(x) except KeyError: NewDict[Dict[x]] = [x] Or, more up-to-date: NewDict = {} for key, val in Dict.iteritems(): NewDict.setdefault(val, []).append(key) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
Hi, On Mon, 11 Jul 2005 15:29:41 +0200, Mage wrote: Dear All, I am writing a database import script in python and I would like to print the percentage of the process to the last line. I would like to update the last line at every percent. You know what I mean. How can the cursor be positioned to the last line or somewhere else on the screen? Curses starts with clearing the whole screen and it is overkill. Many modules are on the net but I would like to resolve this simply task with native python. I tried: for something: print chr(8)*20+mystring, but it is nasty and didn't work well. Mage If you only want to support ansi terminals (which is questionable, but possible), then there are escape codes that are very helpful (searching for ansi escape codes or something in google should help you find the remainder): the general syntax is ESC[parameteraction action usually is the first letter in the sequence, hence parameters are usually numbers (duh :)) ESC is chr(27) (ascii 27, octal \033) actions are Hcursor go home (top left corner usually) Cgo right parameter times Dgo left parameter times Ago up parameter times Bgo down parameter times Kclear to end of line 2J clear screen (yes, to every rule there are exceptions :), note that this does not make the cursor go home) mset color/highlight/formatting flags Examples ESC[2JESC[H same as clear, clear screen, go home \rESC[Kprogress %dprobably what you want :) The downside of this is that determining the size of the screen is pretty hard to do right. Process is usually, read TERM environment variable, read /etc/termcap (deprecated) co attribute (columns), li attribute (rows). That has been deprecated because of all those resizeable terminals out there. Now its something like outputting some magical stuff to make the terminal emulator send back the current sizes immediately once, and whenever they change. I'm not totally clear how that works since I'm too lazy to care :) What you want is probably prc = 0 for prc in range(100): sys.stderr.write(\r\033[KProgress %d%% ... % prc) sys.stderr.flush() time.sleep(0.5) though :) Note that this can wreck havoc onscreen if the terminal is smaller than what is needed to print that horizontally, so technically its not totally clean code. Hope that helps cheers, Danny -- http://mail.python.org/mailman/listinfo/python-list
Re: relative import packages/modules workaround
On Monday 11 July 2005 09:19 am, peter wrote: I've read all the posts concerning relative imports of modules and I am glad I saw some consensus on a syntax. At this moment I am however bound to python 2.3. Does anyone know a good workaround (or a library) which can achieve a relative import for this python version Basically, you can use information from the sys module to dynamically determine your module or package's absolute path. Then you construct the absolute path to the module you want by a fairly simple application of os.path from the relative path. How exactly to do that is not something I remember off the top of my head, but I remember it's not hard -- check the sys and os.path modules' documentation. You probably also want to look at the __path__ property of packaged loaded with __init__.py, as I believe there is some special magic behavior designed for packages to make this a little easier. You can easily encapsulate this in a function under your module with just a few lines of code. Zope provides a function called package_home that does this. I'm sure there are other examples. The missing thing here is not that there's no way to do it, but rather that it's a common enough task that there ought to be *one* way to do it and it ought to be in the library. Otherwise, there's a lot of redundancy. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
--- Bengt Richter [EMAIL PROTECTED] wrote: I still think it's too specialized. What would, hypothetically, this do? class Bar: pass class Foo: x = Bar() def method_1(self, x.y): pass It's hard to explain that you can autoassign self.y but not x.y. No, that limitation wouldn't exist, so you wouldn't have to explain it ;-) I.e., the above would act like class Foo: x = Bar() def method_1(self, _anonymous_arg_1): x.y = _anonymous_arg_1 and would do whatever it would do now (probably look for a global x or a closure cell x, but it wouldn't find the class variable in a normal method call) I am a bit afraid of opening a door for weird side effects. E.g. class unrelated: pass u = unrelated() class grouping: def __init__(self, self.x, u.y, self.z): pass Is this really a good thing to allow? I am afraid it will be abused. My prime concern was to provide a good solution for a very common problem. If we stray too far from this most important goal we may get nothing in the end. self (or whatever people prefer as a name for the first argument of a bound function) *is* special. I think therefore it deserves special support. I think it would be fantastic if we could push through the def __init__(self, self.x, y, self.y) syntax, with the explicit limitation that only the first argument can be used on the left side of the dot. I'd also happily settle for a decorator approach, __autoinit__ or over variations, as long as they are built-in and easy to remember/use/explain to a novice. However, to me the self.x approach seems to be just right because: 1. It is a good compromise between redundant and explicit; i.e.: too redundant: def __init__(self, x, y, z): self.x = x self.y = y self.z = z middle ground: def __init__(self, self.x, self.y, self.z): pass the other extreme: def __init__(self, .x, .y, .z): pass I am thinking people can understand the middle ground approach even without looking at release notes and will not be surprised if unrelated.y doesn't work. 2. This approach is open to full optimization for runtime performance and should therefore be faster than the redundant conventional approach. I.e. the arguments can directly be inserted into the desired dictionary (or slot), without ever being added to locals(). 3. The user can always write grouping(x=1,y=2,z=3). I.e. how the arguments are used is strictly an implementation detail, as it should be. Cheers, Ralf Sell on Yahoo! Auctions no fees. Bid on great items. http://auctions.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: ImportError: No module named numarray
enas khalil wrote: when i write a code to import some module like the following : from nltk.probability import ConditionalFreqDist I got the error : Traceback (most recent call last): File C:\Python24\toky.py, line 1, in -toplevel- from nltk.probability import ConditionalFreqDist File C:\Python24\Lib\site-packages\nltk\probability.py, line 56, in -toplevel- import types, math, numarray ImportError: No module named numarray can you please tell me the cause I already did. You need to install numarray. http://www.stsci.edu/resources/software_hardware/numarray -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
--- Robert Williscroft [EMAIL PROTECTED] wrote: My apologies for having to resort to email but for some reason I can't post this message to comp.lang.python. I've tried about 4 times including starting a new thread, but for some reason it doesn't turn up, though I've followed up on another thread without problem. Very strange. I hope it is not a conspiracy! :) You can email to the list directly (that's what I am doing): python-list@python.org Is there a way out with Python as-is? - Yes. If you take the time to look at the file in the CVS you'll find that I was cheating a bit. To reduce the terrible clutter above, I am actually using a simple trick:: adopt_init_args(self, locals()) Also there is a decorator solution: def init_self( init ): vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] def decorated_init(self, *args, **kw): off = 0 for name in vn: if not name.startswith('_'): if name in kw: value = kw[name] else: value = args[off] off += 1 setattr( self, name, value ) init( self, *args, **kw ) return decorated_init class MyClass(object): __slots__ = ['x', 'z'] @init_self def __init__( self, x, _y, z ): pass def show( self ): for i in self.__slots__: print 'self.%s = %d' %(i,eval('self.%s' % (i,))) MyClass( 1, 2, 3 ).show() MyClass( z = 1, x = 2, _y = 3 ).show() The __slots__ is in the test just because you mentioned you like it, the decorator doesn't need a slots class. AFAICT this differs from your proposal in that in your proposal you want to use '.' as an include prefix the above uses '_' as an exclude prefix. Rob. I like the looks of the decorator approach a lot. Could this somehow be enhanced such that the user doesn't have to know about the underscore? Thinking about runtime efficiency, could the decorator approach somehow achieve that the attribute-to-be arguments are never added to locals()? Cheers, Ralf Sell on Yahoo! Auctions no fees. Bid on great items. http://auctions.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Environment Variable
Is it possible to set an environment variable in python script whose value is retained even after the script exits. Doing the following creates an environment variable name which is visible to only subprocesses created by os.system() and os.popen(). os.putvar(name, vivek) Is it possible to somehow create this environment variable inside python script which will be avaibale even after the script exits. In otherwords, after I run my script, if I do a echo $name in my shell, it should return the value vivek -- http://mail.python.org/mailman/listinfo/python-list
Re: Environment Variable
On 2005-07-11, Vivek Chaudhary [EMAIL PROTECTED] wrote: Is it possible to set an environment variable in python script whose value is retained even after the script exits. No, not in Unix/Linux. In VMS I think there is. -- Grant Edwards grante Yow! I think my CAREER at is RUINED!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: computer algebra packages
François Pinard [EMAIL PROTECTED] wrote: Mascyma is (trying to be) a user-friendly graphical frontend for the Computer Algebra System GNU MAXIMA. I was not successful googling for this one. Would you have an URL handy? Oops, OK! Found it at http://cens.ioc.ee/~pearu/misc/maxima/ . As I'm reading news offline I don't know what's on that page. The Ubuntu Linux copyright file says the files are obtained from http://mulk.dyndns.org/cgi-bin/viewcvs.cgi/trunk.tar.gz?root=Python-Mascyma view=tar and you can find more information at http://www.brummulk.de.vu/projects/mascyma/ Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end -- http://mail.python.org/mailman/listinfo/python-list
Parsing Data, Storing into an array, Infinite Backslashes
I am using this function to parse data I have stored in an array. This is what the array looks like: [['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed', 'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ['Memory', '0', 'Size', '512'], ['Memory', '0', 'Slot', 'DIMM0/J11'], ['Memory', '0', 'ConfigurationType', '2'], ['Memory', '1', 'Summary', '0'], ['Memory', '1', 'Speed', 'PC3200U-30330'], ['Memory', '1', 'Type', 'DDR SDRAM'], ['Memory', '1', 'Size', '512'], ['Memory', '1', 'Slot', 'DIMM1/J12'], ['Memory', '1', 'ConfigurationType', '2'], ['Memory', '2', 'Summary', '0'], ['Memory', '2', 'Speed', 'PC3200U-30330'], ['Memory', '2', 'Type', 'DDR SDRAM'], ['Memory', '2', 'Size', '512'], ['Memory', '2', 'Slot', 'DIMM2/J13'], ['Memory', '2', 'ConfigurationType', '2'], ['Memory', '3', 'Summary', '0'], ['Memory', '3', 'Speed', 'PC3200U-30330'], ['Memory', '3', 'Type', 'DDR SDRAM'], ['Memory', '3', 'Size', '512'], ['Memory', '3', 'Slot', 'DIMM3/J14'], ['Memory', '3', 'ConfigurationType', '2']] This is the code to parse the array: count=0 place=0 query=[] while 1: try: i=fetch.next() except StopIteration: break if i[1] != count: ++count query.append(count) qval=`query[count]` query[count]=qval+i[2]+=+i[3]+, print qval,\n When it runs I get an output similar to this. \\\'Type=DDR SDRAM, \\\'Size=512, \\\'Slot=DIMM2/J13, \\\'ConfigurationType=2, \\\'Summary=0, \\\'Speed=PC3200U-30330, \\\'Type=DDR SDRAM, \\\'Size=512, \'Slot=DIMM3/J14, ' When it's supposed to print just the plain text with the numbers etc. I have changed these lines: qval=`query[count]` query[count]=qval+i[2]+=+i[3]+, To this: query[count]=query[count]+i[2]+=+i[3]+, I get this error: Traceback (most recent call last): File infnode.py, line 60, in ? query[count]=query[count]+i[2]+=+i[3]+, TypeError: unsupported operand type(s) for +: 'int' and 'str' So I try and fix it by doing this: query[count]=`query[count]`+i[2]+=+i[3]+, Can someone please point me in the right direction I am sure that the `query[count]` is causing the backslashes. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
BayPIGgies: July 14, 7:30pm (Google)
The next meeting of BayPIGgies will be Thurs, July 14 at 7:30pm at Google, building 40, room Temp Tech Talk. Alex Martelli will be doing his Black Magic talk on descriptors, decorators, and metaclasses. Prepare to have your head exploded! 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 may meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. This week, there has been discussion of a potluck -- if you want a potluck, speak up NOW on the mailing list. Advance notice: The August 11 meeting agenda has not been set. Please send e-mail to [EMAIL PROTECTED] if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. -- http://mail.python.org/mailman/listinfo/python-list
Re: Environment Variable
Vivek Chaudhary enlightened us with: Is it possible to set an environment variable in python script whose value is retained even after the script exits. It is, if you have absolute control over the calling environment. Is it possible to somehow create this environment variable inside python script which will be avaibale even after the script exits. In otherwords, after I run my script, if I do a echo $name in my shell, it should return the value vivek Here is an example Python script: import sys name = sys.stdin.readline() print export name=%s % name.strip() If you call it like this: bash$ $(python examplescript) It'll change the 'name' variable of your shell. It's not really a generic nor an elegant way of doing this. Heck, it even depends on the type of shell you're using. If it suits your needs, be happy ;-) 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 -- http://mail.python.org/mailman/listinfo/python-list
Extending and embedding Python
I want to write an application that embeds and extends (at least) the Python and Perl interpreters. Now i want to find as much as possible about the Python tools used for extending and embedding Python. To be more specific: My app should: 1. Parse an input file. 2. Call a script in some scripting language, to generate an output file, for example in C++. For task 2 I need to call an embedded interpreter, and also provide call backs from the scripting language to C++, in order to read global information collected during parsing. In order to correctly compile and link my Application, I need a OS independent way to find compiler options and linker options necessary to find header files and libraries. What methods should I use from DistUtils for this purpose. I also need to find some way to verify that linker options necessary for embedding Perl is not incompatible with linking options for embedding Python. Stockholm July 11, 2005 Tommy Nordgren -- http://mail.python.org/mailman/listinfo/python-list
Environment Variable
Is it possible to set an environment variable from inside the python script which will be retained after the script exits. If I use the following code: import os os.putvar(name, tuxlover) the enivironment variable name is visible to only the sub-process created by os.system and os.popen. But as soon as the python script vanishes, the environment variable name is gone. What I am wondering is that is it possible to set a environment variable from inside a python script, and then access it (say, echo $name from the shell) after the python script exits. Thanks Tuxlover -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Data, Storing into an array, Infinite Backslashes
Your code is needlessly complicated. Instead of this business while 1: try: i = fetch.next() except stopIteration: break simply write: for i in fetch: (if there's an explicit 'fetch = iter(somethingelse)' in code you did not show, then get rid of that and just loop 'for i in somethingelse') i[1] will never compare equal to count, because i[1] is always a string and count is always an integer. Integers and strings are never equal to each other. Wring code like x = a string + 3 does not work in Python. You can either convert to a string and then use the + operator to concatenate: x = a string + str(3) or you can use %-formatting: x = a string %s % 3 (%s accepts any sort of object, not just strings) Using repr(...) (`...` is just a shorthand for this) is what is really introducing the backslashes. When it outputs a string, it quotes the string using backslashes. But you pass the old part of the prepared string through it each time, which leads to doubling backslashes. Below is a program I wrote to process the data in your message. It prints out Memory 2 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM2/J13, ConfigurationType=2 Memory 3 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM3/J14, ConfigurationType=2 Memory 0 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM0/J11, ConfigurationType=2 Memory 1 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, Slot=DIMM1/J12, ConfigurationType=2 the result is out of order because the result of calling .items() on a dict is in an arbitrary order. Jeff s = [['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed', 'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ['Memory', '0', 'Size', '512'], ['Memory', '0', 'Slot', 'DIMM0/J11'], ['Memory', '0', 'ConfigurationType', '2'], ['Memory', '1', 'Summary', '0'], ['Memory', '1', 'Speed', 'PC3200U-30330'], ['Memory', '1', 'Type', 'DDR SDRAM'], ['Memory', '1', 'Size', '512'], ['Memory', '1', 'Slot', 'DIMM1/J12'], ['Memory', '1', 'ConfigurationType', '2'], ['Memory', '2', 'Summary', '0'], ['Memory', '2', 'Speed', 'PC3200U-30330'], ['Memory', '2', 'Type', 'DDR SDRAM'], ['Memory', '2', 'Size', '512'], ['Memory', '2', 'Slot', 'DIMM2/J13'], ['Memory', '2', 'ConfigurationType', '2'], ['Memory', '3', 'Summary', '0'], ['Memory', '3', 'Speed', 'PC3200U-30330'], ['Memory', '3', 'Type', 'DDR SDRAM'], ['Memory', '3', 'Size', '512'], ['Memory', '3', 'Slot', 'DIMM3/J14'], ['Memory', '3', 'ConfigurationType', '2']] query = {} for a, b, c, d in s: if not query.has_key((a,b)): query[(a,b)] = [] query[(a,b)].append(%s=%s % (c, d)) for (a,b), v in query.items(): print a, b, , .join(v) pgp7XL3vVj4PO.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Minor correction July 11, 2005
edgrsprj [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] PROPOSED EARTHQUAKE FORECASTING COMPUTER PROGRAM DEVELOPMENT EFFORT it jumps strait to the display routine and uses the entered command to begin Should be the word straight instead of strait. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
Ralf W. Grosse-Kunstleve wrote in news:[EMAIL PROTECTED] in comp.lang.python: --- Robert Williscroft [EMAIL PROTECTED] wrote: My apologies for having to resort to email but for some reason I can't post this message to comp.lang.python. I've tried about 4 times including starting a new thread, but for some reason it doesn't turn up, though I've followed up on another thread without problem. Very strange. I hope it is not a conspiracy! :) You can email to the list directly (that's what I am doing): python-list@python.org I'll follow up and post this, and then see what happens :). Is there a way out with Python as-is? - Yes. If you take the time to look at the file in the CVS you'll find that I was cheating a bit. To reduce the terrible clutter above, I am actually using a simple trick:: adopt_init_args(self, locals()) Also there is a decorator solution: def init_self( init ): vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] def decorated_init(self, *args, **kw): off = 0 for name in vn: if not name.startswith('_'): if name in kw: value = kw[name] else: value = args[off] off += 1 setattr( self, name, value ) init( self, *args, **kw ) return decorated_init class MyClass(object): __slots__ = ['x', 'z'] @init_self def __init__( self, x, _y, z ): pass def show( self ): for i in self.__slots__: print 'self.%s = %d' %(i,eval('self.%s' % (i,))) MyClass( 1, 2, 3 ).show() MyClass( z = 1, x = 2, _y = 3 ).show() The __slots__ is in the test just because you mentioned you like it, the decorator doesn't need a slots class. AFAICT this differs from your proposal in that in your proposal you want to use '.' as an include prefix the above uses '_' as an exclude prefix. Rob. I like the looks of the decorator approach a lot. Could this somehow be enhanced such that the user doesn't have to know about the underscore? The underscore is just there so there is a way of having arguments that aren't added as attributes to the first object, so if that isn't required it could just be omited. Also AIUI (the above is my first attempt to write a decorator), decorators can have arguments so the decorator could take an omit_prefix argument, so the user could specify there own prefix. Or maybe have an include prefix, say self_, if thats what you prefer. Personaly I'm happy with the underscore, 1 leading underscore at module scope means hide the name, 2 at class scope means hide the name, so I kinda like that an undersore is used to omit an argument. Thinking about runtime efficiency, could the decorator approach somehow achieve that the attribute-to-be arguments are never added to locals()? Again AIUI, locals() is an inbuild that constructs a dict of the local arguments and variables, IOW the dict doesn't exist *until* you call locals(). Wether or not the fact the decorator doesn't call locals() makes any difference though I don't know, the real arguments will get passed to decorated_init() in some way and then setattr()'d to the self object. But then again there is a loop, 2 if's and a lookup of the keyword dictionary in there, using this as it stands is going to hurt compared to doing the asignments manually inside __init__(), though as I haven't timed it, I could be wrong ;-). Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
tuple.index(item)
Why don't tuples support an index method? It seems natural enough ... Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Environment Variable
[EMAIL PROTECTED] wrote: Is it possible to set an environment variable from inside the python script which will be retained after the script exits. If I use the following code: import os os.putvar(name, tuxlover) the enivironment variable name is visible to only the sub-process created by os.system and os.popen. But as soon as the python script vanishes, the environment variable name is gone. What I am wondering is that is it possible to set a environment variable from inside a python script, and then access it (say, echo $name from the shell) after the python script exits. No, I regret it is currently not. But I see a significant chance that someone gets on the time machine and implants this into Thompson's head some 30 years earlier as soon as you post that a third time. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
IIRC, the self.__dict__.update(locals()) trick confuses psyco. But you can make a decorator to achieve the same result. There's not really a convincing case for extending python syntax. def attribute_decorator(f): import inspect argnames = inspect.getargspec(f)[0] def decorator(*args, **keywords): bound_instance = args[0] for name, value in zip(argnames[1:], args[1:]): setattr(bound_instance, name, value) return f(*args, **keywords) return decorator #- example use: class foo(object): @attribute_decorator def __init__(self, thing): print init: self.thing is, repr(self.thing) f = foo('hello world') --ljp -- http://mail.python.org/mailman/listinfo/python-list
read output and store in file
Hi, I'm a beginner, and what I want to accomplish is this: 1. For all files under several folders, do some processing (using an existing program). The program will output one line of text for each file. 2. Store the output of all files in one file. It would be great if someone can give me a crash start on accomplishing this. If you think there is a definitely better tool than Python for doing this, please tell me so. I just heard that Python or Perl are better in these kind of jobs. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: read output and store in file
On 2005-07-11, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I'm a beginner, and what I want to accomplish is this: 1. For all files under several folders, do some processing (using an existing program). The program will output one line of text for each file. 2. Store the output of all files in one file. It would be great if someone can give me a crash start on accomplishing this. If you think there is a definitely better tool than Python for doing this, please tell me so. I just heard that Python or Perl are better in these kind of jobs. Using bash and find: (find path1 path2 path3 -type f -exec existingProgram {} \;) outputFile -- Grant Edwards grante Yow! You can't hurt at me!! I have an ASSUMABLE visi.comMORTGAGE!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Environment Variable
Sorry for posting twice. -- http://mail.python.org/mailman/listinfo/python-list
Re: read output and store in file
use os.path.walk() or os.walk() Tuxlover -- http://mail.python.org/mailman/listinfo/python-list
Re: Environment Variable
[EMAIL PROTECTED] wrote: Sorry for posting twice. Sorry for forgetting my wink. wink Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
--- Lonnie Princehouse [EMAIL PROTECTED] wrote: IIRC, the self.__dict__.update(locals()) trick confuses psyco. But you can make a decorator to achieve the same result. There's not really a convincing case for extending python syntax. Not if you have (enough memory for) psyco. :) I am doing C++ extensions by hand; did quite a lot of them. Anything that helps in pushing back the point where I have to move from Python to C++ is highly appreciated. That's probably the strongest argument for the (self, self.x, ...) approach. I believe it can be made more efficient than any other solution. But see also the two other arguments: http://mail.python.org/pipermail/python-list/2005-July/289721.html def attribute_decorator(f): import inspect argnames = inspect.getargspec(f)[0] def decorator(*args, **keywords): bound_instance = args[0] for name, value in zip(argnames[1:], args[1:]): setattr(bound_instance, name, value) return f(*args, **keywords) return decorator #- example use: class foo(object): @attribute_decorator def __init__(self, thing): print init: self.thing is, repr(self.thing) f = foo('hello world') Thanks! Rob Williscroft had a similar suggestion: http://mail.python.org/pipermail/python-list/2005-July/289734.html Does anyone know if there is a way to hide the _ or self_ from the user of the class, i.e. given: class foo(object): @attribute_decorator def __init__(self, x, _y, z): pass can we make it such that the user can still write foo(x=1,y=2,z=3) without the underscore? Cheers, Ralf __ Discover Yahoo! Use Yahoo! to plan a weekend, have fun online and more. Check it out! http://discover.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Help with report
I have some data in the following format: Fred Flintstone,445553454,47634565 Wilma Flintstone,74857346,27576847 Barney Rubble,73487346,27576435 I need to convert this data into a report with the user's name and difference between the 2 numbers. Can someone recommend a good way to do this? BTW, it would be best if I can have it up and running by tomorrow. Also, html would be the preferred format, but not required. Any help would be greatly appreciated!! -- http://mail.python.org/mailman/listinfo/python-list
Re: [Baypiggies] BayPIGgies: July 14, 7:30pm (Google)
I'd like to proffer the suggestion we meet for dinner at 6pm at Mei Long in Mountain View, although it's probably best to run it past our dinner coordinator first to make sure it gets his OK. What say you Brian ? On 7/11/05, Aahz [EMAIL PROTECTED] wrote: Before the meeting, we may meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. This week, there has been discussion of a potluck -- if you want a potluck, speak up NOW on the mailing list. Advance notice: The August 11 meeting agenda has not been set. Please send e-mail to [EMAIL PROTECTED] if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. ___ Baypiggies mailing list [EMAIL PROTECTED] http://www.baypiggies.net/cgi-bin/mailman/listinfo/baypiggies -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with report
On 2005-07-11, ChrisH [EMAIL PROTECTED] wrote: I have some data in the following format: Fred Flintstone,445553454,47634565 Wilma Flintstone,74857346,27576847 Barney Rubble,73487346,27576435 I need to convert this data into a report with the user's name and difference between the 2 numbers. Can someone recommend a good way to do this? BTW, it would be best if I can have it up and running by tomorrow. You really oughtn't put off homework assignments until the last minute. Especially if you don't know how to do them. Also, html would be the preferred format, but not required. Any help would be greatly appreciated!! Hints: The string object's split method: http://docs.python.org/lib/string-methods.html for line in file('inputfile.txt','r') the built-in int() the string formatting operator %: http://docs.python.org/lib/typesseq-strings.html -- Grant Edwards grante Yow! All right, you at degenerates! I want this visi.complace evacuated in 20 seconds! -- http://mail.python.org/mailman/listinfo/python-list
Re: gettext and disambiguating comments
Terry Hancock wrote: /* Comment right before the gettext call, obviously in C */ printf(_(Apparently ambiguous string to translate)); This will get captured into the .po file, according to the gettext manual and appear as a comment right before the msgid (i.e. next to the line number reference). Not automatically. You need to pass the -c option to xgettext to make that happen, preferably using a tag: /* TRANSLATORS: Comment right before the gettext call */ Is there an equivalent Python gettext idiom? I've tried the obvious # Comment right before the gettext call, now in Python print _(Apparently ambiguous string to translate) But this is ignored by both pygettext and xgettext. Did you give -c to xgettext? It works for me, for xgettext 0.14.5. -c appears to be unimplemented in pygettext. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
How does this code works:
Here's an example from some book: def foo(n): s = [n] def bar(i): s[0] += i return s[0] return bar what I don't understand is how this example works, taking into account the LGB rule. I thought that s is not accessible from bar, but it is, apparently. Why? -- http://mail.python.org/mailman/listinfo/python-list
Re: C API : Creating a Py_Method object from a C function.
Hugh Macdonald wrote: The problem in this workflow is taking the C python function that I've defined (using the standard static PyObject *someFunction(PyObject *self, PyObject *args) method) and converting this into a Py_Object. Any ideas? You should use PyCFunction_New(Ex), passing a static PyMethodDef variable that you define along with your function definition. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Extending and embedding Python
Tommy Nordgren wrote: In order to correctly compile and link my Application, I need a OS independent way to find compiler options and linker options necessary to find header files and libraries. What methods should I use from DistUtils for this purpose. I don't think distutils supports linking applications that embed Python, yet. It might be possible to write a distutils command for that purpose, but I'd advise against that. Instead, you should integrate the Python embedding into the build process you alread have (e.g. make, shell scripts, whatever). You can simplify the process by having a Python script compute all the necessary parameters. You find the configuration-specific information in distutils.sysconfig. HTH, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: How long is a piece of string? How big's a unit?
The correct answer to the above question How long is a piece of string? is 2 times half it's length CEC -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
Ralf W. Grosse-Kunstleve wrote in news:[EMAIL PROTECTED] in comp.lang.python: Does anyone know if there is a way to hide the _ or self_ from the user of the class, i.e. given: class foo(object): @attribute_decorator def __init__(self, x, _y, z): pass can we make it such that the user can still write foo(x=1,y=2,z=3) without the underscore? light-goes-on/ Sorry I didn't understand what you ment before: def init_self( init ): class KeywordArgumentError(Exception): pass vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] def decorated_init(self, *args, **kw): off = 0 for name in vn: if not name.startswith('_'): if name in kw: value = kw[name] else: value = args[off] off += 1 setattr( self, name, value ) else: off += 1 #was missing (a bug) in last version. if name in kw: raise KeywordArgumentError( Use %s not %s % (name[1:],name) ) if name[1:] in kw: kw[name] = kw[name[1:]] del kw[name[1:]] init( self, *args, **kw ) return decorated_init class MyClass(object): @init_self def __init__( self, x, _y, z ): print in __init__() _y =, _y def show( self ): for i in self.__dict__: print 'self.%s = %d' %(i,eval('self.%s' % (i,))) MyClass( 1, 2, 3 ).show() MyClass( z = 1, x = 2, y = 3 ).show() MyClass( z = 1, x = 2, _y = 3 ).show() Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How does this code works:
vch wrote: Here's an example from some book: def foo(n): s = [n] def bar(i): s[0] += i return s[0] return bar what I don't understand is how this example works, taking into account the LGB rule. I thought that s is not accessible from bar, but it is, apparently. Why? Python now has nested scopes. http://www.python.org/peps/pep-0227.html -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
--- Rob Williscroft [EMAIL PROTECTED] wrote: def init_self( init ): class KeywordArgumentError(Exception): pass vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ] def decorated_init(self, *args, **kw): off = 0 for name in vn: if not name.startswith('_'): if name in kw: value = kw[name] else: value = args[off] off += 1 setattr( self, name, value ) else: off += 1 #was missing (a bug) in last version. if name in kw: raise KeywordArgumentError( Use %s not %s % (name[1:],name) ) if name[1:] in kw: kw[name] = kw[name[1:]] del kw[name[1:]] init( self, *args, **kw ) return decorated_init class MyClass(object): @init_self def __init__( self, x, _y, z ): print in __init__() _y =, _y def show( self ): for i in self.__dict__: print 'self.%s = %d' %(i,eval('self.%s' % (i,))) MyClass( 1, 2, 3 ).show() MyClass( z = 1, x = 2, y = 3 ).show() MyClass( z = 1, x = 2, _y = 3 ).show() Wow! Here is the output, so everyone can see it immediately: in __init__() _y = 2 self.x = 1 self.z = 3 in __init__() _y = 3 self.x = 2 self.z = 1 Traceback (most recent call last): File /net/cci/rwgk/decorated_init.py, line 45, in ? MyClass( z = 1, x = 2, _y = 3 ).show() File /net/cci/rwgk/decorated_init.py, line 21, in decorated_init raise KeywordArgumentError( __main__.KeywordArgumentError: Use y not _y I am impressed. I'll do some timings to see where we stand... Cheers, Ralf __ Discover Yahoo! Use Yahoo! to plan a weekend, have fun online and more. Check it out! http://discover.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list