Re: how to ncurses on win32 platform
> * Curses for Windows for Python (It was previously > mentioned on a follow-up. there are some missing > features): > http://flangy.com/dev/python/curses/ I've posted an update to this module (better color support, half delay input, some other stuff) and the source code, in case anyone wants to try it on Python 2.4 or tinker with it. -- http://mail.python.org/mailman/listinfo/python-list
Re: String Fomat Conversion
Stephen Thorne wrote: f = file('input', 'r') labels = f.readline() # consume the first line of the file. Easy Option: for line in f.readlines(): x, y = line.split() x = float(x) y = float(y) Or, more concisely: for line in f.readlines(): x, y = map(float, line.split()) Somewhat more memory efficient: lines_iter = iter(file('input')) labels = lines_iter.next() for line in lines_iter: x, y = [float(f) for f in line.split()] By using the iterator instead of readlines, I read only one line from the file into memory at once, instead of all of them. This may or may not matter depending on the size of your files, but using iterators is generally more scalable, though of course it's not always possible. I also opted to use a list comprehension instead of map, but this is totally a matter of personal preference -- the performance differences are probably negligible. Steve -- http://mail.python.org/mailman/listinfo/python-list
(no subject)
Subscribe -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
On Wed, 2005-01-26 at 17:32 -0500, rbt wrote: > Grant Edwards wrote: > > On 2005-01-26, rbt <[EMAIL PROTECTED]> wrote: > > > > > >>Is there an easy way to exclude binary files (I'm working on > >>Windows XP) from the file list returned by os.walk()? > > > > > > Sure, assuming you can provide a rigorous definition of 'binary > > files'. :) > > non-ascii That's not really safe when dealing with utf-8 files though, and IIRC with UCS2 or UCS4 as well. The Unicode BOM its self might (I'm not sure) qualify as ASCII. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
On Wed, 2005-01-26 at 22:28 -0500, Davor wrote: > I browsed docs a bit today, and they also confirm what I have believed - > that OO is totally secondary in Python. In fact, > object/classes/metaclasses are nothing but *dictionaries with identity* > in python. Love this approach. I was really impressed with the design of the language, especially this bit. I first "got" it when reading Learning Python 2nd Ed (well *after* I'd been using Python for a while, but it's always good to read even intro books to fill out "obvious" things you might've missed). I love the way the same "It's just a dictionary search" principle applies to inheritance, scoped variable lookups, etc. In Python, even metaclasses just operate on the class dictionary. How pleasantly simple :-) - especially how the step from class factory to metaclass is so small and approachable. I also love the way I can chuck a bunch of objects into a functionally styled processing pipeline, say a series of functions that each just return the result of a listcomp/genexp. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
> "beliavsky" == beliavsky <[EMAIL PROTECTED]> writes: beliavsky> I think the OO way is slightly more obscure. It's beliavsky> obvious what x = reverse(x) does, but it is not clear beliavsky> unless you have the source code whether x.reverse() beliavsky> reverses x or if it returns a reversed list. What make it so clear to you that reverse(x) will always return a reversed list rather than reversing x in place and return nothing? beliavsky> It is clearer and more concise to write beliavsky> z = reverse(x) + reverse(y) beliavsky> than beliavsky> x.reverse() beliavsky> y.reverse() beliavsky> z = x + y This isn't anything to do with OO programming. It is something about using in interface that your audience expects. You have exactly the same problem whether you are using procedural or OO style. It might be a case for functional programming, but that's something off-topic. beliavsky> Furthermore, if in Python the algorithm for the reverse beliavsky> function applies to many kinds of objects, it just beliavsky> needs to be coded once, whereas a reverse method would beliavsky> have to provided for each class that uses it (perhaps beliavsky> through inheritance). That the reverse() wants to be a function doesn't mean that the thing that reverse() operate on doesn't want to be an object. So this isn't very clear a problem about OO style vs. procedural style, but instead a problem about "generic" programming style vs. "concrete" programming style. On the other hand, if the thing that reverse() operate on isn't an object sharing the same interface, it will be more clumsy to implement a generic reverse() that works for all the different kinds of object---even if they share similar interfaces. Try to implement a generic "reverse" in C when the different type of containers are encoded as different style struct's accessible from different function, and you will understand what I mean. So this is, marginally, a case *for* OO style. Regards, Isaac. -- http://mail.python.org/mailman/listinfo/python-list
python module in webmin
Hi, Had anyone written any python module for webmin? Since webmin is written in perl, but I want to write a python app/module used by webmin. If you know the detail of writing a python module for use in perl webmin, please drop me some guideline. Perhaps It is better off to find/write a python version of webmin first. Thanks Sam. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's so funny? WAS Re: rotor replacement
Jeremy Bowers <[EMAIL PROTECTED]> writes: > The policy has been laid out, multiple times, by multiple people now. The > answer is, you are not going to get any such indication that will satisfy > you. Actually I already got an indication that satisfied me, from Guido and Andrew, although it was later withdrawn for nontechnical reasons (i.e. legal restrictions) that I don't feel entitled to argue against very much. I do, however, believe that what Frederik and Martin are saying is bogus on technical grounds, and furthermore, they're just being busybodies, since they've had no involvement at all in what's happened already with that module, and their picture of the Python development process doesn't have much resemblance to how the current Python distro got to be the way it is. > Note that I am not a Python contributor of any kind. Also note that I > figured this out about two days ago. You can wheedle these guys all you > want, I have not asked them for anything, since they are not in a position to give it. >but they are too experienced for you to extract a promise from them. Actually, one of them already gave a promise that he couldn't keep even if he wanted to. He said that if I wrote a crypto module and got it tested enough, it would be considered for inclusion (i.e. based on its technical merits). But, he doesn't get to decide that. Current policy per per Guido seems to be that because of the legal stuff, there will be no crypto module in the stdlib regardless of its merits. -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is faster?
"Aggelos I. Orfanakos" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > 'a/b/c/'.rstrip('/') I find the first easier to read and mentally process. Others may have a different answer. But perhaps you meant with the CPython 2.x implementation ;-) > P.S. I could time it but I thought of trying my luck here first, in > case someone knows already, and of course the reason. For more on the CPython (2.2) reason, consider >>> def f1(s): return s[:-1] ... >>> def f2(s): return s.rstrip('/') ... >>> import dis >>> dis.dis(f1) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_FAST0 (s) 9 LOAD_CONST 1 (-1) 12 SLICE+2 13 RETURN_VALUE 14 LOAD_CONST 0 (None) 17 RETURN_VALUE >>> dis.dis(f2) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_FAST0 (s) 9 LOAD_ATTR1 (rstrip) 12 LOAD_CONST 1 ('/') 15 CALL_FUNCTION1 18 RETURN_VALUE 19 LOAD_CONST 0 (None) The second has a load attribute (via dict lookup) that the first does not. More important, the second has a generic function call versus a specific byte-coded slice call. The rstrip will also do a slice after it determines the endpoint of the slice. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: how to write a tutorial
On Wed, 2005-01-26 at 09:35 +, Keith Thompson wrote: > "Xah Lee" <[EMAIL PROTECTED]> writes: > [snip] > > Following is a tutorial on Python's classes. > [snip] > > Please stop posting this to comp.lang.c. I'm sure the folks in most > of the other newsgroup aren't interested either -- or if they are, > they can find it in comp.lang.python. Going by the general reaction on c.l.py, I think it'd be more accurate if you left that at "Please stop posting". Sorry for the cross-post, and for this "perl-python" moron who appears to have nothing to do with either, or any knowledge of them. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: What's so funny? WAS Re: rotor replacement
On Thu, 27 Jan 2005 04:04:38 +, phr wrote: > Skip Montanaro <[EMAIL PROTECTED]> writes: >> Because good requirements specification is difficult and testing improves >> the breed. Better to have the major API changes and bugs taken care of, and >> to have its popularity demonstrated *before* it gets into the Python >> distribution. The best way to do something isn't always obvious at the >> outset. > > That is sometimes true, but not always. Sometimes the best way is > obvious. With all due respect, you aren't arguing very well. Your posts are, like this quote, more reactionary than thought-out. You need to stop arguing for the sake of argument, read more carefully, and think more about your global goals in this conversation than your local ones. I'm 99% certain that you've already gotten all the answers you're going to get and all the answers you need in this thread, but you're so busy arguing the local points like this, you haven't noticed. (Either that, or it's the "you haven't answered me because you haven't given the exact answer I want" bit, which I find quite tiresome; there's another list where there are these three teenagers that don't even realize they've defined "answer" that way and keep bitching that they aren't being "answered" when the "answer" is, basically, "it's nice that you feel that way." But I digress.) > I don't need your permission to do that. What I'm looking for is an > indication that it's worth my while, before I spend the effort. The policy has been laid out, multiple times, by multiple people now. The answer is, you are not going to get any such indication that will satisfy you. Note that I am not a Python contributor of any kind. Also note that I figured this out about two days ago. You can wheedle these guys all you want, but they are too experienced for you to extract a promise from them. -- http://mail.python.org/mailman/listinfo/python-list
Re: String Fomat Conversion
On 26 Jan 2005 20:53:02 -0800, mcg <[EMAIL PROTECTED]> wrote: > Investigating python day 1: > > Data in file: > x y > 1 2 > 3 4 > 5 6 > > Want to read file into an array of pairs. > > in c: scanf("%d %d",&x,&y)---store x y in array, loop. > > How do I do this in python?? > In the actual application, the pairs are floating pt i.e. -1.003 f = file('input', 'r') labels = f.readline() # consume the first line of the file. Easy Option: for line in f.readlines(): x, y = line.split() x = float(x) y = float(y) Or, more concisely: for line in f.readlines(): x, y = map(float, line.split()) Regards, Stephen Thorne -- http://mail.python.org/mailman/listinfo/python-list
String Fomat Conversion
Investigating python day 1: Data in file: x y 1 2 3 4 5 6 Want to read file into an array of pairs. in c: scanf("%d %d",&x,&y)---store x y in array, loop. How do I do this in python?? In the actual application, the pairs are floating pt i.e. -1.003 -- http://mail.python.org/mailman/listinfo/python-list
Re: building Python: up arrow broken on SuSE Linux 8.2
"Erik Johnson" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > So I downloaded & built libreadline version 5.0. I have libreadline.a > and shlib/libreadline.so.5.0 files. Having done Python & other scripting > languages for a while, I have sort of forgotten all the ugly details about C > compilation. I'm trying to figure out how to get Python2.3.4. statically > linked with the .a file and not muck with the system shared libraries and > let other applications fend for themselves. Any advice on how to statically > link in this library so the Python build is happy? What I thought might be obvious and easy does not work, BTW... In the Modules/Setup file I put this... readline readline.c -I/home/ej/readline-5.0 -L/home/ej/readline-5.0 -lreadline re-ran configure and tried the make again. No joy. :( Now I remember why I ended up using things like Perl & Python in the first place... [EMAIL PROTECTED]:~/Python-2.3.4> make gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototyp es -I. -I./Include -DPy_BUILD_CORE -o Modules/config.o Modules/config.c gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototyp es -I. -I./Include -DPy_BUILD_CORE -DPYTHONPATH='":plat-linux2:lib-tk"' \ -DPREFIX='"/usr/local"' \ -DEXEC_PREFIX='"/usr/local"' \ -DVERSION='"2.3"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -I/home/ej/readline-5.0 -c ./Modules/readline.c -o Modules/readline.o Modules/readline.c:26:31: readline/readline.h: No such file or directory Modules/readline.c:27:30: readline/history.h: No such file or directory Modules/readline.c: In function `parse_and_bind': Modules/readline.c:49: warning: implicit declaration of function `rl_parse_and_bind' Modules/readline.c: In function `read_init_file': Modules/readline.c:68: warning: implicit declaration of function `rl_read_init_file' Modules/readline.c: In function `read_history_file': Modules/readline.c:89: warning: implicit declaration of function `read_history' Modules/readline.c: In function `write_history_file': Modules/readline.c:111: warning: implicit declaration of function `write_history' Modules/readline.c:113: warning: implicit declaration of function `history_truncate_file' Modules/readline.c: In function `set_completer_delims': Modules/readline.c:287: error: `rl_completer_word_break_characters' undeclared (first use in this function) Modules/readline.c:287: error: (Each undeclared identifier is reported only once Modules/readline.c:287: error: for each function it appears in.) -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
> "beliavsky" == beliavsky <[EMAIL PROTECTED]> writes: beliavsky> I think the OO way is slightly more obscure. It's beliavsky> obvious what x = reverse(x) does, but it is not clear beliavsky> unless you have the source code whether x.reverse() You don't need to read the src, you just need to read the docs >>> help([].reverse) Help on built-in function reverse: reverse(...) L.reverse() -- reverse *IN PLACE* beliavsky> reverses x or if it returns a reversed list. If beliavsky> x.reverse() does the former, a disadvantage relative to beliavsky> the procedural approach is that a function can be used beliavsky> in an expression. It is clearer and more concise to beliavsky> write beliavsky> z = reverse(x) + reverse(y) The distinction is not OO versus procedural, it is a decision about how you choose to write "reverse". The python list implementers of the reverse object method could have decided to return a new reversed list rather than do the reverse in place and return None. Then you could have done z = x.reverse() + y.reverse() They could have chosen to reverse the list *in place* and also returned a reference to self rather than None, in which case you could do the above as well. w/o digging up the transcripts from the python-dev mailing list, my guess is that they choose to do it in place for efficiency in memory and cpu, and chose not to return self to prevent user confusion. Ie, if a user was allowed to do 'z = x.reverse() + y.reverse()' they might be surprised to find the side effect of in place modification. Likewise, I could easily write a procedural "in place" reverse that returns None, in which case 'z = reverse(x) + reverse(y)' would not do what you suggest. My point is that whether a function/method such as reverse operates in place or on a copy, and whether it returns None or a reference to a list is independent of OO vs procedural style and is motivated by considerations of efficiency, readability, and usability. beliavsky> Furthermore, if in Python the algorithm for the reverse beliavsky> function applies to many kinds of objects, it just beliavsky> needs to be coded once, whereas a reverse method would beliavsky> have to provided for each class that uses it (perhaps beliavsky> through inheritance). True, a generic reverse procedure/function can be applied to any data structure that supports iteration. In the case of python, however, some iterable data structures are mutable (lists, dicts) and some are not (strings, tuples). For mutable sequences, an in place reverse is likely to be more efficient in memory and perhaps CPU than a generic reverse which returns a new copy. So a specialized method "reverse" applicable to lists (but not strings and tuples) can be a big win. Fortunately, python supports both, allowing you to define a general "reverse" that works for any object that supports the sequence protocol, as well as to define an object specific reverse method that may be faster in time and space. JDH -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
"The object-oriented programming paradigm has an undeserved reputation as being complicated; most of the complexity of languages such as C++ and Java has nothing to do with their object orientation but comes instead from the type declarations and the mechanisms to work around them. This is a prime example of how Scheme's approach of removing restrictions compares with the "piling feature on top of feature" needed in other languages, such as the C++ template mechanism." "Handbook of Programming Languages, Volume IV: Functional and Logic Programming Languages" Peter H. Salus, editor 1998 page 63 Similarly, now, Java's generics! -- Regards, Casey -- http://mail.python.org/mailman/listinfo/python-list
Re: What's so funny? WAS Re: rotor replacement
Skip Montanaro <[EMAIL PROTECTED]> writes: > Because good requirements specification is difficult and testing improves > the breed. Better to have the major API changes and bugs taken care of, and > to have its popularity demonstrated *before* it gets into the Python > distribution. The best way to do something isn't always obvious at the > outset. That is sometimes true, but not always. Sometimes the best way is obvious. > If multiple solutions exist in the community, everyone benefits. > The best survive. The worst don't. What's needed here "good enough", not necessarily "the best conceivable", a level of perfection which is perhaps unattainable. > If one implementation is prematurely chosen for inclusion in the > Python distribution, it stifles the vetting process. There have been exactly zero alternative implementations proposed. > Finally, what if, saints be preserved, your whizbang new module is It is not a whizbang module. It is a stripped-down, basic implementation of a well-accepted set of standards that are being used in thousands of other applications in other languages. > included in the core distribution and it's just not as popular as > was first thought? There is demand for it. Look at how this thread started: some crypto user noticed that rotor was gone and wanted to know what to do instead. The issue of whether there's enough desire for a crypto module to warrant including one in the stdlib was decided a long time ago. The proof of that somebody decided to accept the rotor module into the distro. That decision, that enough users want crypto to make having a stdlib module worthwhile, has never been reversed as far as I know. Rather, the specific module (rotor) was withdrawn because it turned out not to do the job on technical grounds. And the decision not to replace it was based on new legal and political concerns that outweighed the technical side, not on thinking that there wouldn't be enough users. > It just winds up as a weight around the maintainers' necks. Once > included in the distribution it's difficult to remove. The rotor module is gone (and good riddance). That's how this thread started, remember? It shows that bogus modules can be removed. Have you ever used a crypto library in a serious way? Which ones have you used? The python-crypto folks (including myself) have used quite a few of them, and after a while one realizes that the usable ones all do pretty much the same stuff. The one we're talking about does about the same stuff that the rest of them do. It does the same stuff listed in PEP 272, although it's organized a little bit differently in order to make supplying multiple cipher primitives more convenient, which the application that drove PEP 272 apparently didn't need to do. Andrew (the author of PEP 272) has said that the different organization is fine. The different organization is similar to what's done internally in OpenSSL, in Peter Gutmann's cryptlib, in GnuPG, and various other successful programs. It's not radical or experimental. It's old hat and low risk. It provides functionality that's missing from the stdlib. > Even rexec and Bastion, which are both known to be inadequate from a > security standpoint, are still in the distribution. They should be removed pronto, just as rotor was removed. Some other ones should be removed too, like SmartCookie. > So, feel free to implement whatever it is you propose. I don't need your permission to do that. What I'm looking for is an indication that it's worth my while, before I spend the effort. > Register it with PyPI, announce it on comp.lang.python.announce, etc. I don't know how to do that, but the folks who care about it are mostly on the python-crypto mailing list, and the module has been discussed at length there and has been well-received. > Support it for awhile. Run it through a couple revisions to fix API > warts and bugs. I already did that with the Python implementation, and did in fact revise the API somewhat based on reviewer feedback. The C implementation would have the exact same API that the reviewers seem to be happy with. > When it's the category king and there is substantial community > support for inclusion, It's already the category king, because there are precisely zero other entrants in the category. If someone else wants to do one and can get it into the stdlib, I will gladly use theirs and stop worrying about mine. > it will be considered. Not according to how I currently interpret Guido's posts to python-dev about it. I read those as saying that no crypto module will be considered for inclusion whether or not it's the category king, because any such module might conflict with crypto regulations in some countries. No matter how much community support or technical perfection it has, it's just won't be included, period. So tell me again what to do after writing and releasing a C module. There's just no reason to write one, if the module can'
Re: Where can I find Mk4py.dll for python24 ?
I don't know what metakit or the file you are looking for is, but a simple search on google turns up the following article where a guy built it for Python 2.2 and was willing to mail that to people. Try contacting him: http://www.equi4.com/pipermail/metakit/2002-March/000560.html HTH, -ej "Jose Rivera" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I installed the new release and I have not been able to make work metakit. > > Please give me some help to enjoy metakit and python 24. > > Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
John Hunter wrote: > > "Davor" == Davor <[EMAIL PROTECTED]> writes: > > Davor> not really - it was not my intention at all - but it seems > Davor> people get upset whenever this OO stuff is mentioned - and > Davor> what I did not expect at all at this forum as I believed > Davor> Python people should not be so OO hardcore (seems not all > Davor> as quite a few have indicated in their > Davor> replies)... Nevertheless, I think the discussion has > Davor> several quite good points! -- > Davor> http://mail.python.org/mailman/listinfo/python-list > > Consider the case of a list, say > > x = [1,2,3,4] > > suppose you wanted to reverse the list, so that x becomes [4,3,2,1]. > In a procedural language, one might do > > x = reverse(x) > > In an OO language such as python, one might do > > x.reverse() > > Is the OO way more obscure and complicated, etc? Not really -- it's > only a minor syntactical difference. One of the core ideas behind OO > programming is that data (the contents of the list 1,2,3,4) and > methods (sorting, reversing) are bound together into a single entity, > the object. On the face of it, this is rather sensible. I think the OO way is slightly more obscure. It's obvious what x = reverse(x) does, but it is not clear unless you have the source code whether x.reverse() reverses x or if it returns a reversed list. If x.reverse() does the former, a disadvantage relative to the procedural approach is that a function can be used in an expression. It is clearer and more concise to write z = reverse(x) + reverse(y) than x.reverse() y.reverse() z = x + y Furthermore, if in Python the algorithm for the reverse function applies to many kinds of objects, it just needs to be coded once, whereas a reverse method would have to provided for each class that uses it (perhaps through inheritance). -- http://mail.python.org/mailman/listinfo/python-list
Re: threading.py Condition wait overflow error
[Tim Peters] ... >> The most common cause for "impossible exceptions" > is flawed C code in an extension that fails to >> check a Python C API call for an error return. [Mark English] > Yes, I use a lot of C modules which I wrote. Then you know where to start looking . > It could certainly be one of them (although which one could be an > interesting challenge to find out). It may even have something to do > with moving to the VC7.1 compiler. Hard to say in advance. Since you have VC7.1, that opens a world of possiblities if you recompile Python. There are extra checks in ceval.c in a debug build, trying to catch "a call lied about whether it raised an exception" soon(er) after it happens. Rebuilding all your extensions in debug mode too could be a PITA, so you could get the same effect by #define'ing CHECKEXC in a release build. But a debug build has all sorts of extra checks that can help, and you could get into the debugger then and set a breakpoint on the unexpected OverflowError ... a quick check of the source shows that "long int too large to convert to int" is produced only by longobject.c's PyLong_AsLong() function. There's no way we _should_ be getting into that function by applying min() to floats, of course. > Thank you very much for your suggestion. Without it I would never have > thought to look at that code. Nobody ever does . -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
I'd like to thank everyone for their replies. The main important lesson I got is: Python does not have that many issues with misuse of OO as compared to Java/C++ because it's *dynamically* typed language and extremely powerful *dictionary* data structure. I browsed docs a bit today, and they also confirm what I have believed - that OO is totally secondary in Python. In fact, object/classes/metaclasses are nothing but *dictionaries with identity* in python. Love this approach. In fact, you can very easily implement your own *OO model* completely separate of Python's OO model... Now I actually strongly believe that Python's author has introduced the whole OO model just to attract and make happy OO population... In fact, *Python's dynamic type checking mechanisms + dictionary is way more powerful than Java/C++'s static type checking mechanisms + their OO mechanisms* and you can definitely be more productive using Python's structured programming than Java/C++ OO programming :-)... and Python is probably the best example why we should have skipped OO all together.. --- second, instead of playing with OO plagued design principles do as follows: 1. separate data, functionality, and structure from each other as much as you can (in Python only valid structural element I've seen so far is module - ignore objects & classes!) 2. do not assume any have identity (even if the underlying language model provides and uses one) - so don't pass them around and crazy stuff... so you get a nice program with separate data structures and functions that operate on these data structures, with modules as containers for both (again ideally separated). Very simple to do and maintain no matter what OO preachers tell you... Davor -- http://mail.python.org/mailman/listinfo/python-list
Re: 20050126 find replace strings in file
kosh wrote: > Nah it is daily humor. Just think of it like a joke list. :) Or a daily puzzler: how many blatantly stupid things can you find in 5 mins? -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
> "Davor" == Davor <[EMAIL PROTECTED]> writes: Davor> not really - it was not my intention at all - but it seems Davor> people get upset whenever this OO stuff is mentioned - and Davor> what I did not expect at all at this forum as I believed Davor> Python people should not be so OO hardcore (seems not all Davor> as quite a few have indicated in their Davor> replies)... Nevertheless, I think the discussion has Davor> several quite good points! -- Davor> http://mail.python.org/mailman/listinfo/python-list Consider the case of a list, say x = [1,2,3,4] suppose you wanted to reverse the list, so that x becomes [4,3,2,1]. In a procedural language, one might do x = reverse(x) In an OO language such as python, one might do x.reverse() Is the OO way more obscure and complicated, etc? Not really -- it's only a minor syntactical difference. One of the core ideas behind OO programming is that data (the contents of the list 1,2,3,4) and methods (sorting, reversing) are bound together into a single entity, the object. On the face of it, this is rather sensible. You may rightly recoil against unnecessary abstraction and complexity, abuse of multiple inheritance and so on. That's perfectly sensible. But object orientation is probably not the bogey man here. python values readable code that is as simple as possible (but no simpler!) as you seem to. Focus on the actual problem, which is probably not OO programming, but colleagues who are making a design more complex than need be. Indeed, the third chant in the mantra of python is "Simple is better than complex." John-Hunters-Computer:~> python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! -- http://mail.python.org/mailman/listinfo/python-list
Re: building Python: up arrow broken on SuSE Linux 8.2
> Do you have the GNU readline library installed and within Python's > reach (lib in LD_LIBRARY_PATH or in /etc/ld.so.conf with subsequent > call of ldconfig)? I think you are on the right path. I later found an Apple article online that answered essentially my question saying libreadline wasn't included on the Apple Python distribution the OP was asking about. I now notice this in the output of configure: checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... no My system has /lib/libreadline.so.4.3. I guess it does not define these newer functions and so that is why the readline module was not configured in Setup to start with? That is the presumption I am working on. So I downloaded & built libreadline version 5.0. I have libreadline.a and shlib/libreadline.so.5.0 files. Having done Python & other scripting languages for a while, I have sort of forgotten all the ugly details about C compilation. I'm trying to figure out how to get Python2.3.4. statically linked with the .a file and not muck with the system shared libraries and let other applications fend for themselves. Any advice on how to statically link in this library so the Python build is happy? Thanks, -ej - Original Message - From: "Peter Maas" <[EMAIL PROTECTED]> Newsgroups: comp.lang.python Sent: Wednesday, January 26, 2005 3:22 AM Subject: Re: building Python: up arrow broken on SuSE Linux 8.2 > Erik Johnson schrieb: > > I am trying to upgrade my Python installation. After downloading > > sources and building Python 2.3.4, I am unable to use the command > > history editing feature in the interactive interpreter (where the > > up-arrow would previously give you the last command line to edit, > > it now just prints "^[[A".) > > > -- > --- > Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') > --- -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
Timo Virkkala wrote: This guy has got to be a troll. No other way to understand. not really - it was not my intention at all - but it seems people get upset whenever this OO stuff is mentioned - and what I did not expect at all at this forum as I believed Python people should not be so OO hardcore (seems not all as quite a few have indicated in their replies)... Nevertheless, I think the discussion has several quite good points! -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is faster?
Yes, I could do the timing myself. Sorry if this was impolite -- it was not in my intentions. The main reason I asked was about the reason. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's so funny? WAS Re: rotor replacement
phr> I don't see why you can't make up your mind enough to issue simple phr> statements like "the Python lib should have a module that does phr> so-and-so, and it should meet such-and-such requirements, so if phr> someone submits one that meets the requirements and passes code phr> review and testing and doesn't have unexpected issues or otherwise phr> fail to meet reasonable expectations, we'll use it". Because good requirements specification is difficult and testing improves the breed. Better to have the major API changes and bugs taken care of, and to have its popularity demonstrated *before* it gets into the Python distribution. The best way to do something isn't always obvious at the outset. If multiple solutions exist in the community, everyone benefits. The best survive. The worst don't. If one implementation is prematurely chosen for inclusion in the Python distribution, it stifles the vetting process. Finally, what if, saints be preserved, your whizbang new module is included in the core distribution and it's just not as popular as was first thought? It just winds up as a weight around the maintainers' necks. Once included in the distribution it's difficult to remove. Even rexec and Bastion, which are both known to be inadequate from a security standpoint, are still in the distribution. So, feel free to implement whatever it is you propose. Register it with PyPI, announce it on comp.lang.python.announce, etc. Support it for awhile. Run it through a couple revisions to fix API warts and bugs. When it's the category king and there is substantial community support for inclusion, it will be considered. Python is popular in part because of its fairly conservative development strategy. That goes for the libraries as well as the language itself. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is faster?
Thus spake Aggelos I. Orfanakos ([EMAIL PROTECTED]): > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here > first, in case someone knows already, and of course the > reason. Expecting other people to do something simply because you couldn't be bothered to do it yourself is not polite... That said, here are the timings on my system: > python ./timeit.py "'a/b/c/'[:-1]" 100 loops, best of 3: 0.511 usec per loop > python ./timeit.py "'a/b/c/'.rstrip('/')" 100 loops, best of 3: 1.3 usec per loop As you can see, this suggests that the list access method is quicker. This is to be expected, since the two methods don't do the same thing - rstrip will return a copy of your string with any number of trailing '/'es removed. If there aren't any, it will return the string as-is. The string access method will always chop exactly one character off the end. Even though the results for your specific input are the same, rstrip is a more complex, and therefore slower, beast. Cheers, Aldo -- Aldo Cortesi [EMAIL PROTECTED] http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 -- http://mail.python.org/mailman/listinfo/python-list
RE: Which is faster?
> Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here > first, in case someone knows already, and of course the reason. Timing it is almost no work, though: >>> import timeit >>> timeit.Timer("'a/b/c/'[:-1]").timeit() 0.23856551600831949 >>> timeit.Timer("'a/b/c/'.rstrip('/')").timeit() 0.74258655778876914 The obvious reason for the former to be faster (although I haven't checked to see whether it's true) is because the latter checks for a specific character, whereas the former just snips it off whatever it is. =Tony.Meyer -- http://mail.python.org/mailman/listinfo/python-list
RE: Which is faster?
Aggelos I. Orfanakos wrote: > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here first, in > case someone knows already, and of course the reason. First, it almost certainly doesn't matter. Use the one that is self-documenting. Secondly, time it yourself. It's incredibly easy. There's a module written especially for doing this - and surprise surprise, it's called "timeit.py" and it's in the /Lib directory. Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Which is faster?
Any idea which of the following is faster? 'a/b/c/'[:-1] or 'a/b/c/'.rstrip('/') Thanks in advance. P.S. I could time it but I thought of trying my luck here first, in case someone knows already, and of course the reason. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's so funny? WAS Re: rotor replacement
"Martin v. Löwis" <[EMAIL PROTECTED]> writes: > > That it's not appropriate for the > > distro maintainers to look at the spec and the reference (pure Python) > > implementatation and say "yes, we want this, go write the C version > > and we'll include it after it's had some testing". > > I know that I'm not going to give a blanket promise to include some > code in the future. I can give blanket promises to *review* such > code. Actually, assuming I find the time, I will review *any* > code that is contributed. I don't see why you can't make up your mind enough to issue simple statements like "the Python lib should have a module that does so-and-so, and it should meet such-and-such requirements, so if someone submits one that meets the requirements and passes code review and testing and doesn't have unexpected issues or otherwise fail to meet reasonable expectations, we'll use it". > Sure. That is because O'Reilly is willing to take a financial risk > of failure of a book product. I'm not willing to take similar risks > for Python code (risk of having to redesign the interface, Again, we're talking about straightforward modules whose basic interface needs are obvious. And interfaces in stdlib do get extended from version to version all the time, if users turn out to need additional features beyond the obvious basics. > fix bugs in the implementation, Obviously there must be testing and review before inclusion. Acceptance is contingent on the module passing tests and review. > or have the submitter run away after the contribution). There is no way to know in advance whether that's going to happen. A lot of work on the ANSI X9 crypto standards came to a screeching halt a few years ago when one of the more prolific contributors tripped over his vacuum cleaner cord, fell down the stairs, and was killed. So if you have to be absolutely sure that the submitter will always be around, you can never accept anything. I think you mostly have to go by how maintainable the code looks and how much maintainance you think it will actually need and how many people you think are around who can take care of it when needed. And I do believe that experienced programmers are capable of making reasonable judgements about those questions, so they should not refuse to ever make such judgements. > > Similarly, look at how the whole PEP process works. There are lots of > > times when a PEP has been accepted before any working code is > > distributed. > > Indeed. For new language features, it is more difficult to try them out > in advance than for new library API. I don't see why that should be. Nothing stops anyone from implementing and testing a language feature before standardizing it. It will get even easier with PyPy, which is perhaps a reason to ban further language changes until PyPy is deployed. > Taking it to the extreme misses the point. I'm asking for field > testing for new modules - not for all changes. "Field testing" to most people means testing that a specific implementation is reliable enough for inclusion. It is the final step in a normal process of declaring a feature ready for deployment, not the initial step: 1) think about whether you want the feature 2) decide you want it 3) implement 4) field test (this naturally recognizes the possibility of reversing step 2, if something unexpectedly goes wrong in testing that's not easily repaired, but step 2 declares the basic intention for what should happen after a successful test). 5) deploy You wanted much more than for step 4 to always happen before step 5, which is reasonable. You claimed step 4 should always happen before step 1, which is silly. > > That's bizarre and abnormal as a development process. What kind of > > development process in industry doesn't decide whether to include a > > feature, until after the feature is completely implemented at a > > production scale? > > Any high-quality standardization process. Standards in IETF and OMG > are only accepted after implementations have been available. I don't know what OMG is, but there is no IETF requirement that any implementations be available in any particular language. There are also plenty of instances where the IETF decides that it wants something to be standardized (e.g. IPSEC) so it invites a working group to develop a specification. The WG members then spend a lot of time in meetings and discussions reaching a consensus on what the spec should say. They are willing to spend that time because the IETF has already given them reasonable expectation that their end result will actually be used. The IETF doesn't say "go develop a complete standard and implementation and put it in the field for a year before we [the IETF] will even think about whether we want to standardize it". They are capable of announcing in advance that they want to standardize something. I don't see why the Python folks have to be incapable of ever doing the same. For the mod
Re: 20050126 find replace strings in file
On Wednesday 26 January 2005 7:13 pm, Tad McClellan wrote: > [ Followup set ] > > Dan Perl <[EMAIL PROTECTED]> wrote: > > I can't imagine why or how, but there are > > actually 26 members in the perl-python Yahoo! group who have registered > > to get these bogus lessons sent to them daily! > > There is one born every minute. > Nah it is daily humor. Just think of it like a joke list. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: 20050126 find replace strings in file
[ Followup set ] Dan Perl <[EMAIL PROTECTED]> wrote: > I can't imagine why or how, but there are > actually 26 members in the perl-python Yahoo! group who have registered to > get these bogus lessons sent to them daily! There is one born every minute. -- Tad McClellan SGML consulting [EMAIL PROTECTED] Perl programming Fort Worth, Texas -- http://mail.python.org/mailman/listinfo/python-list
Re: Responding to trollish postings.
John Machin wrote: Indeed. Let's just nominate XL to the "Full Canvas Jacket" website (http://www.ratbags.com/ranters/) and move on. I'm not sure how reliable that site could be. After all, it contains no articles with the words "autocoding", "threeseas", or "rue" (other than as the French "street"). Sad, really. ;-) (Neither has it been updated in the last two years. :-( ) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: python memory blow out
[Simon Wittber] >> According to the above post: >>a) If the allocation is > 256 bytes, call the system malloc. >>b) If the allocation is < 256, use its own malloc implementation, which >> allocates memory in 256 kB chunks and never releases it. >> >> I imagine this means that large memory allocations are eventually >> released back to the operating system. However, in my case, this >> appears to be not happening. Large chunks are returned to the platform C when they become unreferenced. More below. [Stephen Thorne] > There was a recent patch posted to python-dev list which allows python > to release memory back to the operating system once the 256kb chunk is > no longer used. Nope, the patch may return such a 256KB chunk to the platform C library's free() function. That's never what someone actually means by the vague "released back to the operating system", and whether the latter might happen is another platform-dependent (OS + C library + specific versions of each) can of worms. > I'm not saying running a bleeding edge CVS HEAD python plus untested > development patches is going to be a solution for you in the short > term, but I just wanted to mention it because I'm excited about this > limitation disappearing in python :). It's a necessary first step, anyway. Alas, there's no way to take a second step without messy platform-specific code (when does your favorite platform C free() "release memory back" to your favorite operating system? to "do something about that", exact knowledge of platform details is necessary). -- http://mail.python.org/mailman/listinfo/python-list
python memory blow out
I have written some software which proxy's SQL Server database services across a network. It uses Pyro, without multiuthreading. It creates and closes a new connection and cursor object for each request. Unfortunately, the memory consumption blows out (consuming all available memory) when a large SQL query is run. This is not a problem in itself; the problem is that Python does not release this memory back to the operating system once it has finished with the result set. I've noticed others have been frustrated by this problem also: http://mail.python.org/pipermail/python-dev/2004-October/049483.html According to the above post: > a) If the allocation is > 256 bytes, call the system malloc. > b) If the allocation is < 256, use its own malloc implementation, which > allocates memory in 256 kB chunks and never releases it. I imagine this means that large memory allocations are eventually released back to the operating system. However, in my case, this appears to be not happening. Does anyone have ideas on why this is occuring, or how I might otherwise prevent memory blow out? Sw. -- http://mail.python.org/mailman/listinfo/python-list
Re: python memory blow out
On Thu, 27 Jan 2005 09:08:59 +0800, Simon Wittber <[EMAIL PROTECTED]> wrote: > According to the above post: > > a) If the allocation is > 256 bytes, call the system malloc. > > b) If the allocation is < 256, use its own malloc implementation, which > > allocates memory in 256 kB chunks and never releases it. > > I imagine this means that large memory allocations are eventually > released back to the operating system. However, in my case, this > appears to be not happening. There was a recent patch posted to python-dev list which allows python to release memory back to the operating system once the 256kb chunk is no longer used. I'm not saying running a bleeding edge CVS HEAD python plus untested development patches is going to be a solution for you in the short term, but I just wanted to mention it because I'm excited about this limitation disappearing in python :). Regards, Stephen Thorne -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] 20050126 find replace strings in file
To follow up on Jurgen Exner's critique, I present Xah Lee's version, and then my rewritten version. "Xah Lee" <[EMAIL PROTECTED]> writes: > if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; > while ($line = ) { > chomp($line); > $line =~ s/$stext/$rtext/g; > print F2 "$line\n"; > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; #!/usr/bin/perl use warnings; use strict; if (@ARGV != 4) { die "Wrong arg! Unix BNF: $0" } my ($stext, $rtext, $infile, $outfile) = @ARGV; open my $infh, '<', $infile or die "Error opening input file [$infile]: $!"; open my $outfh, '>', $outfile or die "Error opening output file [$outfile]: $!"; while(<$infh>) { s/$stext/$rtext/g; print { $outfh } $_; } close($infh) or die "Error closing input file [$infile]: $!"; close($outfh) or die "Error closing output file [$outfile]: $!"; My version takes up more lines, but I don't count whitespace-- whitespace is not expensive, and when used properly adds greatly to the readability of your program. I've set followups to the only appropriate group for Mr. Lee's postings. -=Eric -- Come to think of it, there are already a million monkeys on a million typewriters, and Usenet is NOTHING like Shakespeare. -- Blair Houghton. -- http://mail.python.org/mailman/listinfo/python-list
Re: Browsing text ; Python the right tool?
John Machin wrote: Jeff Shannon wrote: [...] For ~10 or fewer types whose spec doesn't change, hand-coding the conversion would probably be quicker and/or more straightforward than writing a spec-parser as you suggest. I didn't suggest writing a "spec-parser". No (mechanical) parsing is involved. The specs that I'm used to dealing with set out the record layouts in a tabular fashion. The only hassle is extracting that from a MSWord document or a PDF. The "specs" I'm used to dealing with are inconsistent enough that it's more work to "massage" them into strict tabular format than it is to retype and verify them. Typically it's one or two file types, with one or two record types each, from each vendor -- and of course no vendor uses anything similar to any other, nor is there a standardized way for them to specify what they *do* use. Everything is almost completely ad-hoc. If, on the other hand, there are many record types, and/or those record types are subject to changes in specification, then yes, it'd be better to parse the specs from some sort of data file. "Parse"? No parsing, and not much code at all: The routine to "load" (not "parse") the layout from the layout.csv file into dicts of dicts is only 35 lines of Python code. The routine to take an input line and serve up an object instance is about the same. It does more than the OP's browsing requirement already. The routine to take an object and serve up a correctly formatted output line is only 50 lines of which 1/4 is comment or blank. There's a tradeoff between the effort involved in writing multiple custom record-type classes, and the effort necessary to write the generic loading routines plus the effort to massage coerce the specifications into a regular, machine-readable format. I suppose that "parsing" may not precisely be the correct term here, but I was using it in parallel to, say, ConfigParser and Optparse. Either you're writing code to translate some sort of received specification into a usable format, or you're manually pushing bytes around to get them into a format that your code *can* translate. I'd say that my creation of custom classes is just a bit further along a continuum than your massaging of specification data -- I'm just massaging it into Python code instead of CSV tables. I suspect that we're both assuming a case similar to our own personal experiences, which are different enough to lead to different preferred solutions. ;) Indeed. You seem to have lead a charmed life; may the wizards and the rangers ever continue to protect you from the dark riders! :-) Hardly charmed -- more that there's so little regularity in what I'm given that massaging it to a standard format is almost as much work as just buckling down and retyping it. My one saving grace is that I'm usually able to work with delimited files, rather than column-width-specified files. I'll spare you the rant about my many job-related frustrations, but trust me, there ain't no picnics here! Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: Responding to trollish postings.
Terry Reedy wrote: > > No offense taken. My personal strategy is to read only as much of trollish > threads as I find interesting or somehow instructive, almost never respond, > and then ignore the rest. I also mostly ignore discussions about such > threads. > Indeed. Let's just nominate XL to the "Full Canvas Jacket" website (http://www.ratbags.com/ranters/) and move on. -- http://mail.python.org/mailman/listinfo/python-list
Re: Browsing text ; Python the right tool?
Jeff Shannon wrote: > John Machin wrote: > > > Jeff Shannon wrote: > > > >> [...] If each record is CRLF terminated, then > >>you can get one record at a time simply by iterating over the file > >>("for line in open('myfile.dat'): ..."). You can have a dictionary > >>classes or factory functions, one for each record type, keyed off > >>of the 2-character identifier. Each class/factory would know the > >>layout of that record type, > > > > This is plausible only under the condition that Santa Claus is paying > > you $X per class/factory or per line of code, or you are so speed-crazy > > that you are machine-generating C code for the factories. > > I think that's overly pessimistic. I *was* presuming a case where the > number of record types was fairly small, and the definitions of those > records reasonably constant. For ~10 or fewer types whose spec > doesn't change, hand-coding the conversion would probably be quicker > and/or more straightforward than writing a spec-parser as you suggest. I didn't suggest writing a "spec-parser". No (mechanical) parsing is involved. The specs that I'm used to dealing with set out the record layouts in a tabular fashion. The only hassle is extracting that from a MSWord document or a PDF. > > If, on the other hand, there are many record types, and/or those > record types are subject to changes in specification, then yes, it'd > be better to parse the specs from some sort of data file. "Parse"? No parsing, and not much code at all: The routine to "load" (not "parse") the layout from the layout.csv file into dicts of dicts is only 35 lines of Python code. The routine to take an input line and serve up an object instance is about the same. It does more than the OP's browsing requirement already. The routine to take an object and serve up a correctly formatted output line is only 50 lines of which 1/4 is comment or blank. > > The O.P. didn't mention anything either way about how dynamic the > record specs are, nor the number of record types expected. My reasoning: He did mention A0 and C1 hence one could guess from that he maybe had 6 at least. Also, files used to "create printed pages by an external company" (especially by a company that had "leaseplan" in its e-mail address) would indicate "many" and "complicated" to me. > I suspect > that we're both assuming a case similar to our own personal > experiences, which are different enough to lead to different preferred > solutions. ;) Indeed. You seem to have lead a charmed life; may the wizards and the rangers ever continue to protect you from the dark riders! :-) My personal experiences and attitudes: (1) extreme aversion to having to type (correctly) lots of numbers (column positions and lengths), and to having to mentally translate start = 663, len = 13 to [662:675] or having ugliness like [663-1:663+13-1] (2) cases like 17 record types and 112 fields in one file, 8 record types and 86 fields in a second -- this being a new relatively clean simple exercise in exchanging files with a government department (3) Past history of this govt dept is that there are at least another 7 file types in regular use and they change the _major_ version number of each file type about once a year on average (3) These things tend to start out deceptively small and simple and turn into monsters. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
This guy has got to be a troll. No other way to understand. -- Timo Virkkala -- http://mail.python.org/mailman/listinfo/python-list
Re: Classical FP problem in python : Hamming problem
Francis Girard wrote: For the imerge function, what we really need to make the formulation clear is a way to look at the next element of an iteratable without consuming it. Or else, a way to put back "consumed" elements in the front an iteration flow, much like the list constructors in FP languages like Haskell. It is simple to encapsulate an iterator inside another iterator class that would do just that. Here's one. The additional "fst" method returns the next element to consume without consuming it and the "isBottom" checks if there is something left to consume from the iteration flow, without actually consuming anything. I named the class "IteratorDeiterator" for lack of imagination : [snip] Another implementation is my peekable class: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 It allows you to peek several elements ahead if that's necessary. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] 20050126 find replace strings in file
Xah Lee wrote: [...] > In perl, similar code can be achieved. > the following code illustrates. > > if (scalar @ARGV != 4) Why scalar()? The comparison already creates a scalar context, no need to enforce it twice. > {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; Ouch, how ugly. What's wrong with a simple my ($one, $two, $three, $four) = @ARGV; or the standard way using shift for ($one, $two, $three, $four) { $_ = shift; } > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; Really? Usually it's either the OS or the user (disk full, no write permissions, wrong file name, ...) > while ($line = ) { Why $line? It doesn't serve any useful purpose here. > chomp($line); Why chomp()? It doesn't serve any useful purpose here. > $line =~ s/$stext/$rtext/g; If you would not have used $line above then you would not need the binding here. > print F2 "$line\n"; If you would not have chomped the line above then you would not need to add the newline back here. A simpler print F2 $_; would have sufficed > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; I find this highly unlikely. If at all then the OS failed to complete the close. jue -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
Nick Coghlan wrote: > Davor wrote: > > thanks for the link > > > > > >>know what's funny: in the Lua mailing list there is currently a > >>discussion about adding OO to Lua. > > > > > > I guess most of these newer languages have no choice but to support OO > > if they want to attract a larger user base :-(... > > Tell me, have you ever defined a C structure, and then written various functions > to operate on that structure (i.e. taking a pointer to the structure as their > first argument)? > > Have you then put both the structure definition and the function prototypes into > a single header file and used that header file from other code? > > That's OO programming: associating several pieces of information as an 'object', > and associating various methods to operate on instances of those objects. Then why was C++ invented? What you have described can be done in C, Pascal, and Fortran 90, all of which are generally classified as procedural programming languages. As Lutz and Ascher say in "Learning Python", in object-based programming one can pass objects around, use them in expressions, and call their methods. "To qualify as being truly object-oriented (OO), though, objects need to also participate in something called an inheritance hierarchy." Whether true OOP is a Good Thing is arguable and depends on the situation. -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
On 2005-01-26, Larry Bates <[EMAIL PROTECTED]> wrote: > There's no definitive way of telling a file is "non-ascii". > Bytes in a binary file define perfectly good ascii characters. As long as bit 7 is a 0. Traditional ASCII only allows/defines the values 0x00 through 0x7f. If that's what is meant by "ASCII", then a file containting bytes greater than 0x7F is not ASCII. If all bytes are 0x7F or below, the file _may_ be ASCII, but there's now way to tell if it _is_ ASCII unless you ask the creator of the file. It could be Baudot or some other encoding that doesn't use bit 7. Or, it could just be binary data that happens to have bit 7 == 0. > We could be of more help, if you would take the time to > explain a little about what you are trying to do. Yup. -- Grant Edwards grante Yow! Now, let's SEND OUT at for QUICHE!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
"rbt" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Is there an easy way to exclude binary files (I'm working on Windows XP) > from the file list returned by os.walk()? > > Also, when reading files and you're unsure as to whether or not they are > ascii or binary, I've always thought it safer to 'rb' on the read, is this > correct... and if so, what's the reasoning behind this? Again all of this > pertains to files on Windows XP and Python 2.4 Please clarify: is your question about identifying binary (non-ascii) files or about using os.walk? -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
you might want to look up the 'isascii' function... i.e. - can be represented using just 7-bits. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classical FP problem in python : Hamming problem
Le mardi 25 Janvier 2005 19:52, Steven Bethard a écrit : Thank you Nick and Steven for the idea of a more generic imerge. To work with the Hamming problem, the imerge function _must_not_ allow duplicates and we can assume all of the specified iteratables are of the same size, i.e. infinite ! Therefore, Nick's solution fulfills the need. But it is admittedly confusing to call the function "imerge" when it doesn't merge everything (including duplicates). Anyway both solution sheds new light and brings us a bit farther. That's the beauty of many brains from all over the world collabarating. Really, it makes me emotive thinking about it. For the imerge function, what we really need to make the formulation clear is a way to look at the next element of an iteratable without consuming it. Or else, a way to put back "consumed" elements in the front an iteration flow, much like the list constructors in FP languages like Haskell. It is simple to encapsulate an iterator inside another iterator class that would do just that. Here's one. The additional "fst" method returns the next element to consume without consuming it and the "isBottom" checks if there is something left to consume from the iteration flow, without actually consuming anything. I named the class "IteratorDeiterator" for lack of imagination : -- BEGIN SNAP class IteratorDeiterator: def __init__(self, iterator): self._iterator = iterator.__iter__() self._firstVal = None ## Avoid consuming if not requested from outside ## Works only if iterator itself can't return None def __iter__(self): return self def next(self): valReturn = self._firstVal if valReturn is None: valReturn = self._iterator.next() self._firstVal = None return valReturn def fst(self): if self._firstVal is None: self._firstVal = self._iterator.next() return self._firstVal def isBottom(self): if self._firstVal is None: try: self._firstVal = self._iterator.next() except StopIteration: return True return False -- END SNAP Now the imerge_infinite which merges infinite lists, while allowing duplicates, is quite straightforward : -- BEGIN SNAP def imerge_infinite(*iterators): vItTopable = [IteratorDeiterator(it) for it in iterators] while vItTopable: yield reduce(lambda itSmallest, it: itSmallest.fst() > it.fst() and it or itSmallest, vItTopable).next() -- END SNAP To merge finite lists of possibly different lengths is a bit more work as you have to eliminate iterators that reached the bottom before the others. This is quite easily done by simply filtering them out. The imerge_finite function below merges "lists" of possibly different sizes. -- BEGIN SNAP def imerge_finite(*iterators): vItDeit = [IteratorDeiterator(it) for it in iterators] vItDeit = filter(lambda it: not it.isBottom(), vItDeit) while vItDeit: yield reduce(lambda itSmallest, it: itSmallest.fst() > it.fst() and it or itSmallest, vItDeit).next() vItDeit = filter(lambda it: not it.isBottom(), vItDeit) -- END SNAP Now, we want versions of these two merge functions that do not allow duplicates. Building upon what we've already done in a semi FP way, we just filter out the duplicates from the iteration streams returned by the above functions. The job is the same for the infinite and finite versions, hence the imerge_nodup generic function. -- BEGIN SNAP def imerge_nodup(fImerge, *iterators): it = fImerge(*iterators) el = it.next() yield el while True: el = dropwhile(lambda _next: _next == el, it).next() yield el imerge_inf_nodup = \ lambda *iterators: imerge_nodup(imerge_infinite, *iterators) imerge_finite_nodup = \ lambda *iterators: imerge_nodup(imerge_finite, *iterators) -- END SNAP I used the lambda notation for imerge_inf_nodup and imerge_finite_nodup to avoid another useless for-yield loop. Here the notation really just express function equivalence with a bounded argument (it would be great to have a notation for this in Python, i.e. binding a function argument to yield a new function). The merge function to use with hamming() is imerge_inf_nodup. Regards, Francis Girard FRANCE > Nick Craig-Wood wrote: > > Steven Bethard <[EMAIL PROTECTED]> wrote: > >> Nick Craig-Wood wrote: > >>>Thinking about this some more leads me to believe a general purpose > >>>imerge taking any number of arguments will look neater, eg > >>> > >>>def imerge(*generators): > >>>values = [ g.next() for g in generators ] > >>>while True: > >>>x = min(values) > >>>yield x > >>>for i in range(len(values)): > >>>if values[i] == x: > >>>values[i] = generators[i].next() > >> > >> This kinda looks like it dies after the first generator is exhausted, > >> but I'm not certain. > > > > Yes it will stop iterating then (rather like zip() o
Re: Classical FP problem in python : Hamming problem
Le mardi 25 Janvier 2005 09:01, Michael Spencer a ÃcritÂ: > Francis Girard wrote: > > The following implementation is even more speaking as it makes > > self-evident and almost mechanical how to translate algorithms that run > > after their tail from recursion to "tee" usage : > > Thanks, Francis and Jeff for raising a fascinating topic. I've enjoyed > trying to get my head around both the algorithm and your non-recursive > implementation. > Yes, it's been fun. > Here's a version of your implementation that uses a helper class to make > the algorithm itself prettier. > > from itertools import tee, imap > > def hamming(): > def _hamming(): > yield 1 > for n in imerge(2 * hamming, imerge(3 * hamming, 5 * hamming)): > yield n > > hamming = Tee(_hamming()) > return iter(hamming) > > > class Tee(object): > """Provides an indepent iterator (using tee) on every iteration > request Also implements lazy iterator arithmetic""" > def __init__(self, iterator): > self.iter = tee(iterator,1)[0] > def __iter__(self): > return self.iter.__copy__() > def __mul__(self, number): > return imap(lambda x: x * number,self.__iter__()) > > def imerge(xs, ys): >x = xs.next() >y = ys.next() >while True: > if x == y: >yield x >x = xs.next() >y = ys.next() > elif x < y: >yield x >x = xs.next() > else: # if y < x: >yield y >y = ys.next() > > >>> hg = hamming() > >>> for i in range(1): > > ... n = hg.next() > ... if i % 1000 == 0: print i, n > ... > 0 1 > 1000 5184 > 2000 81 > 3000 27993600 > 4000 4707158941350 > 5000 5096079360 > 6000 4096000 > 7000 2638827906662400 > 8000 143327232 > 9000 680244480 > > Interesting idea. > Regards > > Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Question Regarding SocketServer
I am glad you were able to figure it out. It's strange that the pyc file didn't get updated... it should have automatically fixed itself. *shrug* that's one of those problems that aggrivate you to death... -- http://mail.python.org/mailman/listinfo/python-list
Re: inherit without calling parent class constructor?
Christian Dieterich wrote: Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does somebody have any ideas how to inherit the data attributes and the methods of a class without calling it's constructor over and over again? You could try making D a container for B instead of a subclass: class D(object): def __init__(self, ...): self._B = None def __getattr__(self, attr): if self._B is None: self._B = B() return getattr(self._B, attr) Include something similar for __setattr__(), and you should be in business. If it will work for numerous D instances to share a single B instance (as one of your workarounds suggests), then you can give D's __init__() a B parameter that defaults to None. Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: inherit without calling parent class constructor?
Christian Dieterich wrote: On Dé Céadaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard wrote: Note that: @deco def func(...): ... is basically just syntactic sugar for: def func(...): ... func = deco(func) Oh, I learned something new today :-) Nice thing to know, these descriptors. Just a note of clarification: The @deco syntax is called *decorator* syntax. Classes with a __get__ method are called *descriptors*. But yes, they're both nice things to know. ;) Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: MMTK Install Problem
Justin Lemkul <[EMAIL PROTECTED]> writes: > Hello All, > > I am hoping that someone out there will be able to help me. During the > "build" phase of MMTK installation, I receive the following series of errors: > > $ python setup.py build > running build > running build_py > running build_ext > building 'lapack_mmtk' extension > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd > -fno-common > -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DLIBM_HAS_ERFC > -DEXTENDED_TYPES -IInclude > -I/System/Library/Frameworks/Python.framework/Versions/ > 2.3/include/python2.3 -c Src/lapack_mmtk.c -o > build/temp.darwin-7.7.0-Power_Macintosh > -2.3/Src/lapack_mmtk.o > Src/lapack_mmtk.c:2:33: Numeric/arrayobject.h: No such file or directory Always look at the first error :-) GCC is awful for, when it can't find an include file, saying it can't, then spewing millions of error messages afterwards that are a direct result of not having stuff declared. In this case, it's obvious that you don't have Numeric installed correctly; the header files should be picked from one of the directories specified by the -I flags in the gcc invocation above. > I am attempting the install on a Mac OS X v10.3 with Python v2.3, NumPy > v23.1, > and SciPy v2.4.3 (You mean ScientificPython, not SciPy, right? Scipy is at 0.3.2) How did you install Numeric? The newest version is 23.7. It should be real easy to upgrade to that, as that version picks up Apple's vecLib framework for the linear algebra routines. Just do the usual 'python setup.py build', 'sudo python setup.py install'. That should put the header files where the MMTK installation expects them. -- |>|\/|< /--\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca -- http://mail.python.org/mailman/listinfo/python-list
Responding to trollish postings.
[New subject line] In response to my response to a trollish posting... > There isn't any doubt that these 'tutorials' are generally unwelcome and > unhelpful. Numerous people have kindly taken the time to flag some of the > problems. So much so that any competent google of the archives would > quickly reveal the group consensus on their instructional merit. Yes, having advised many people to use Google, I thought it appropriate to flag one particular section that I thought dangerous. > I submit that continued corrections and advice of this sort are > counter-productive. I agree that 'correcting' Xah's writing is useless, and so I refrained. If asked 'What's wrong with the part you flagged?', I would stick with my original advice: "Ignore it". > Could we try to ignore them in the hopes that without the light of > attention they will wither, meanwhile trusting the many extant reviews > and google to do their work? I only read that particular post because it lacked the [Perl-Python] flag and because I was interested in the subject. Sure, now that I have added my one and presumably only review, let's everyone stop ;-) > (In case it isn't obvious: none of this is intended as a criticism of > Terry or any of the others who have been 'fighting the good fight'; I > just think a change of strategy might be in order.) No offense taken. My personal strategy is to read only as much of trollish threads as I find interesting or somehow instructive, almost never respond, and then ignore the rest. I also mostly ignore discussions about such threads. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: 20050126 find replace strings in file
[EMAIL PROTECTED] wrote: Xah Lee wrote: close(F1) or die "Perl fucked up. Reason: $!"; close(F2) or die "Perl fucked up. Reason: $!"; Same here. Never seen Perl fuck up on closing a file. Usually something in the OS or file system that does it. In this case, I'm pretty sure it's the user. --Ala -- http://mail.python.org/mailman/listinfo/python-list
Re: 20050126 find replace strings in file
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I guess there is no way to check if the file opened fine? What if the > filesystem or file is locked for this user/session. Pretty puny > language if it cannot tell you that it cannot do what you tell it to. > .. > Same for the close. Is there no way check a good close? An exception (IOError) is raised when a file operation fails. The open() and and close() statements should be enclosed in a try-except statement. Please, take Xah Lee's postings with more than just a grain of salt. As a matter of fact, you are better off ignoring them than trying to learn from them. He is an egomaniac who is learning python and who thinks that he can already teach others. Personally I doubt he will ever learn python well enough to teach others. Just look at his English. He has a similar list with a-word-a-day just like the perl-python a-lesson-a-day and he seems indeed to know a lot of words. But his grammar is horrendous (there's a word for you, Xah Lee!). And according to his own website he's been living in North America for more than 15 years! English is a second language for me too but you won't see me writing something like "this groups is for Perlers who wants to learn Python". It may be unfair to pick on his English, but it is the best way I can make the point to someone who does not know python that Xah Lee does not know what he's talking about. I find Xah Lee annoying and I could just ignore him, but I am concerned that some people may actually take his statements seriously and learn from them. I can't imagine why or how, but there are actually 26 members in the perl-python Yahoo! group who have registered to get these bogus lessons sent to them daily! Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: access private field in python 2.4
thanks Steve pujo -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
There's no definitive way of telling a file is "non-ascii". Bytes in a binary file define perfectly good ascii characters. Windows depends on file extensions to try to keep track of the "type" of data in a file, but that isn't foolproof. I can rename a plain ascii file with a .EXE extension. We could be of more help, if you would take the time to explain a little about what you are trying to do. Larry Bates rbt wrote: Grant Edwards wrote: On 2005-01-26, rbt <[EMAIL PROTECTED]> wrote: Is there an easy way to exclude binary files (I'm working on Windows XP) from the file list returned by os.walk()? Sure, assuming you can provide a rigorous definition of 'binary files'. :) non-ascii -- http://mail.python.org/mailman/listinfo/python-list
Re: MSI Difficulties
brolewis wrote: I am trying to deploy Python onto a number of laptops and have been trying to take advantage of Python 2.4's MSI installer. I have tried using the following commands to install, but to no avail: msiexec /i python-2.4.msi /qb ALLUSERS=1 -- and -- msiexec /i python-2.4.msi /qb ALLUSERS=1 ADDLOCAL=ALL However both of these commands fail to update the Windows path to include C:\Python24 and as such creates problems for me when trying to actually use Python. How can I rectify this situation? Is there a command I am missing? Do I need to manually update the Path, and if so, is there a programatic way I can do this? Thanks in advance I've always manually updated the path... but I suppose there may be a way to do this automatically during install or programatically (bat file or py script afterwards). Perhaps someone more knowledgeable can answer these questions? Best of luck! -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
Grant Edwards wrote: On 2005-01-26, rbt <[EMAIL PROTECTED]> wrote: Is there an easy way to exclude binary files (I'm working on Windows XP) from the file list returned by os.walk()? Sure, assuming you can provide a rigorous definition of 'binary files'. :) non-ascii -- http://mail.python.org/mailman/listinfo/python-list
Re: inherit without calling parent class constructor?
On Dé Céadaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard wrote: Note that: @deco def func(...): ... is basically just syntactic sugar for: def func(...): ... func = deco(func) Oh, I learned something new today :-) Nice thing to know, these descriptors. Note that b.size and d.size are only calculated once each, and if d.size is never accessed, you'll never incur the costs of calculating it. That's exactly what I need. It works fine for Python 2.2 and 2.3. So, I'll try to implement that into my package. Thanks a bunch for your help, Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassed dict as globals
Evan Simpson <[EMAIL PROTECTED]> writes: > In Python 2.4 the following works: > > >>> class G(dict): > ... def __getitem__(self, k): > ... return 'K' + k > ... > >>> g = G() > >>> exec 'print x, y, z' in g > Kx Ky Kz > >>> > [snip] > [Is] there a way to do this (intercept global variable accesses) > in Python 2.3? > One can emulate it in a rather limited way in pre 2.4 releases: >>> cd = compile("print x, y, z", '', 'exec') >>> glbs = dict(globals()) >>> for id in cd.co_names: glbs[id] = 'K' + id >>> exec cd in glbs Kx Ky Kz Special names can be used only as constants. It is better suited for eval() than exec. Lenard Lindstrom <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
RE: On benchmarks, heaps, priority queues
[EMAIL PROTECTED] wrote: > PQPython23 - the Lib implementation > PQ0 - my insertion sort based variant > PQueue - my "heap" based variant > (like PQPython23, but different). First of all, you should be running these benchmarks using Python 2.4. heapq is considerably faster there ... (Raymond Hettinger rewrote it all in C). http://www.python.org/2.4/highlights.html Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassed dict as globals
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Evan Simpson wrote: > >> In Python 2.4 the following works: >> >> >>> class G(dict): >> ... def __getitem__(self, k): >> ... return 'K' + k >> ... >> >>> g = G() >> >>> exec 'print x, y, z' in g >> Kx Ky Kz >> >>> >> >> ...while in Python 2.3 it fails with NameError: name 'x' is not defined. > I don't think he added this purely by accident, As I remember, Raymond H. was responding to a request by someone who ran into that exception. In general, functions accepting a base class should at least accept subclasses of that baseclass. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb executemany
Daniel Bowett wrote: I seem to have found a bug/limitation of executemany in MySQLdb. I am inserting 3100 records into a database. It works fine and adds them in about 1 second. I went back to the program today and realised i'd missed a field so added it to the insert statement. This seems to break it if I try to add all the records in one go. Through trial and error I have realised the limit is 2786 records in one go. Any more than that I get two different errors on the executemany statement: "MySQL server has gone away" - This occurs if I try to add all 3100 records in one go. "Lost Connection to MySQL server during query" - This happens if I am near the 2786 threshold. Is there a known limit with this function??? UPDATE -- The maximum packet size in mysql by default is 1MB. Hence why I was hitting ths problem. http://dev.mysql.com/doc/mysql/en/packet-too-large.html -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
In <[EMAIL PROTECTED]>, Frank Bechmann (w) wrote: > know what's funny: in the Lua mailing list there is currently a > discussion about adding OO to Lua. >From my quick glance at the language last year I recall that one can access elements of tables (in Python: dict()) with this syntax: ``tbl.attr`` and it's also possible to put functions into those tables. So it's already a prototype based OO language. Remember: you need objects for an OO language -- classes are optional! Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
On 2005-01-26, rbt <[EMAIL PROTECTED]> wrote: > Is there an easy way to exclude binary files (I'm working on > Windows XP) from the file list returned by os.walk()? Sure, assuming you can provide a rigorous definition of 'binary files'. :) > Also, when reading files and you're unsure as to whether or > not they are ascii or binary, I've always thought it safer to > 'rb' on the read, is this correct... That depends on what you want. Adding a 'b' will disable the cr/lf handling. Not sure what else it does. > and if so, what's the reasoning behind this? Behind what? > Again all of this pertains to files on Windows XP and Python 2.4 -- Grant Edwards grante Yow! Now that I have my at "APPLE", I comprehend COST visi.comACCOUNTING!! -- http://mail.python.org/mailman/listinfo/python-list
exclude binary files from os.walk
Is there an easy way to exclude binary files (I'm working on Windows XP) from the file list returned by os.walk()? Also, when reading files and you're unsure as to whether or not they are ascii or binary, I've always thought it safer to 'rb' on the read, is this correct... and if so, what's the reasoning behind this? Again all of this pertains to files on Windows XP and Python 2.4 Many thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: short programming projects for kids
Thanks André, Adrian, Steve, Duncan, and zombiehunter for the excellent suggestions. Bob -- http://mail.python.org/mailman/listinfo/python-list
Re: Inherting from object. Or not.
On Wednesday 26 January 2005 21:24, M.E.Farmer wrote: > Hello Frans, > What you are seeing is a step on the path to unification of types and > classes. I changed all base classes in my project to inherit object. There appears to be no reason to not do it, AFAICT. Thanks, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: 20050126 find replace strings in file
Xah Lee wrote: > © # -*- coding: utf-8 -*- > © # Python > © > © import sys > © > © nn = len(sys.argv) > © > © if not nn==5: > © print "error: %s search_text replace_text in_file out_file" % > sys.argv[0] > © else: > © stext = sys.argv[1] > © rtext = sys.argv[2] > © input = open(sys.argv[3]) > © output = open(sys.argv[4],'w') I guess there is no way to check if the file opened fine? What if the filesystem or file is locked for this user/session. Pretty puny language if it cannot tell you that it cannot do what you tell it to. > © > © for s in input: > © output.write(s.replace(stext,rtext)) > © output.close() > © input.close() Same for the close. Is there no way check a good close? > > - > save this code as find_replace.py > run it like this: > python find_replace.py findtext replacetext in_file out_file > > the sys.argv is from sys. sys.argv[0] is the program's name itself. > > note the idiom > "for variable_name in file_object" > > note that since this code reads each > line in turn, so huge file is of no-problemo > > the code is based from Python > Cookbook of Alex Martelli & David > Ascher, page 121 > > in Python terminal, type help() then > 'FILES' and or 'sys' > for reference. > > try to modify this file for your > needs. > -- > In perl, similar code can be achieved. > the following code illustrates. > > if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; In 7 years of perl programming, I have never seen an open error that had anything to do with perl processing. Normally, if I get an error, the file does not exist, or has permissions set so that the current user/session is not allowed to open the file. > while ($line = ) { > chomp($line); > $line =~ s/$stext/$rtext/g; > print F2 "$line\n"; > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; Same here. Never seen Perl fuck up on closing a file. Usually something in the OS or file system that does it. > Xah > [EMAIL PROTECTED] > http://xahlee.org/PageTwo_dir/more.html -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen() redirecting to TKinter or WXPython textwidget???
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Ivo, my initial thought would be, you need to know how much text you > will get back from popen. My Python reference has the following > example: > > import os > dir = os.popen('ls -al', 'r') > while (1): > line = dir.readline() > if line: > print line, > else: > break > > that example shows how to capture the process output in a file-type > object, then bring it into a string with readline(). > >[ snip ] > cheers > S > Thanx for trying Stewart, but that is not what I need The output of mencoder is not readable with readlines (i tried it) because after the initial informational lines You don't get lines anymore (you get a linefeed but no newline) The prints are all on the same line (like a status line) something like Pos: 3,1s 96f ( 0%) 42fps Trem: 0min 0mb A-V:0,038 [171:63] which is coninually updated while the process runs... > in your app, you could create a Tkinter stringVar, say myOutput, for > the process output. In your Tkinter widget, you could then set a > textvariable=myOutput. also use the wait_variable and watch options How does this work? wait?? anyone? > (hope I recall these correctly, don't have my Tkinter ref. at hand) to > detect when there's been a change to the contents of the StringVar and > update the contents of the label. > Hope this helps, if not, write back. I really like to know how I can catch the output of a subproces.Popen() command and redirect it to something else (like a textwidget ) and I really like to use the subprocess module (standard in v2.4) to get to know it. Another reason to use the subprocess module is I can stop the process because I know the handle of the thread. The subprocess module knows all this. cheerz, Ivo. -- http://mail.python.org/mailman/listinfo/python-list
Re: wx.Image: Couldn't add an image to the image list.
Laszlo, If you are using PIL just for scaling, you can do away with PIL. Even if you do other things with PIL, you can use the Rescale method of the wx.Image instance to resize. Here is the code (adapted from the Demo): data = open('C:/TEMP/test.bmp'), "rb").read() stream = cStringIO.StringIO(data) img = wx.ImageFromStream( stream ) img.Rescale(32, 32) # Resize your image to 32x32 bmp = wx.BitmapFromImage( img ) # Convert Image to Bitmap # Now display Bitmap in Panel wx.StaticBitmap(self, -1, bmp, (bmp.GetWidth(), bmp.GetHeight())) Try this and see if this works for you. Thank you, --Kartic -- http://mail.python.org/mailman/listinfo/python-list
Re: XOR on string
> lrc == Linear Redundancy Check? or Longitudinal? Note that > such terms are not precisely defined... generally just acronyms > people make up and stick in their user manuals for stuff. :-) > Longitudinal > import operator > lrc = reduce(operator.xor, [ord(c) for c in string]) That's better than what I had, which as it turned out was working I was just calculating the lrc on one extra digit that I should have been. Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: "pickle" vs. f.write()
For basic builtin objects, repr(ob) generally produces a string that when eval()ed will recreate the object. IE eval(repr(ob) == ob # sometimes For writing and reading class instances, pickle is the way to go. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
MSI Difficulties
I am trying to deploy Python onto a number of laptops, all running Windows XP, and have been trying to take advantage of Python 2.4's MSI installer. I have tried using the following commands to install, but to no avail: msiexec /i python-2.4.msi /qb ALLUSERS=1 -- and -- msiexec /i python-2.4.msi /qb ALLUSERS=1 ADDLOCAL=ALL However both of these commands fail to update the Windows path to include C:\Python24 and as such creates problems for me when trying to actually use Python. How can I rectify this situation? Is there a command I am missing? Do I need to manually update the Path, and if so, is there a programatic way I can do this? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
MSI Difficulties
I am trying to deploy Python onto a number of laptops and have been trying to take advantage of Python 2.4's MSI installer. I have tried using the following commands to install, but to no avail: msiexec /i python-2.4.msi /qb ALLUSERS=1 -- and -- msiexec /i python-2.4.msi /qb ALLUSERS=1 ADDLOCAL=ALL However both of these commands fail to update the Windows path to include C:\Python24 and as such creates problems for me when trying to actually use Python. How can I rectify this situation? Is there a command I am missing? Do I need to manually update the Path, and if so, is there a programatic way I can do this? Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen() redirecting to TKinter or WXPython textwidget???
Ivo, my initial thought would be, you need to know how much text you will get back from popen. My Python reference has the following example: import os dir = os.popen('ls -al', 'r') while (1): line = dir.readline() if line: print line, else: break that example shows how to capture the process output in a file-type object, then bring it into a string with readline(). in your app, you could create a Tkinter stringVar, say myOutput, for the process output. In your Tkinter widget, you could then set a textvariable=myOutput. also use the wait_variable and watch options (hope I recall these correctly, don't have my Tkinter ref. at hand) to detect when there's been a change to the contents of the StringVar and update the contents of the label. Hope this helps, if not, write back. cheers S -- http://mail.python.org/mailman/listinfo/python-list
Re: Help With Python
Nick Vargish wrote: > Here's my Monty Pythonic answer: > > ## cut here > class Viking(): > > def __init__(): > pass > > def order(): > return 'Spam' > > # this is one viking making one order repeated 511 times. if you want > # 511 vikings making seperate orders, you'll have to write a loop. > v = Viking() > orders = [ v.order() ] * 511 > > print ', '.join(orders) > ## cut here > > With no apologies to Eric Idle, > > Nick > > > -- > # sigmask || 0.2 || 20030107 || public domain || feed this to a python > print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') Not to be nit-picky, but you got some issues here ;-). Never forget the importance of "self"! ### class Viking: . def __init__(self): . pass . def sing(self): . return 'Spam' v = Viking() spam_song = [ v.sing() ] * 511 print ', '.join(spam_song) -- http://mail.python.org/mailman/listinfo/python-list
Re: Inherting from object. Or not.
Frans Englich wrote: What is the difference between inherting form object, and not doing it? Although this doesn't provide a description of all the implications, it does give you the basic answer to the question and you can easily do further research to learn more: http://www.python.org/doc/2.2.1/whatsnew/sect-rellinks.html#SECTION00031 (Summary: inheriting from object gives you a "new-style" class, not doing so gives you a classic class, and there are a variety of differences resulting from that.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
subprocess.Popen() redirecting to TKinter or WXPython textwidget???
Hi Pythoneers, I am trying to make my own gui for mencoder.exe (windows port of the terrific linux mencoder/mplayer) to convert divx to Pocket_PC size. My current app creates a batch script to run the mencoder with the needed params, but now I want to integrate mencoder as a subprocess in my app. What already works: the starting of the subprocess.Popen and the subsequent killing of the process if I want it to. My gui does not freeze up as it did in my first tries. What I want to know (what does not yet work ;-)): - Redirecting the output of the subprocess to a textwidget in my GUI Any example or help is much appreceated. I tried the subprocess.PIPE but I think I don't really understand how it is suppost to work The redirecting to a file does work but this not my objective... So I'm stuck. HELP The started processes are long and I want to be able to show some kind of progress-status. Thanx, Ivo Woltring -- http://mail.python.org/mailman/listinfo/python-list
Re: Inherting from object. Or not.
> What is the difference between inherting form object, and not doing it? E.g, > what's the difference between the two following classes? > > class foo: > pass > > class bar(object): > pass > > Sometimes people inherit from it, and sometimes not. I don't see a pattern in > their choices. > > I think this is the best source: http://www.python.org/2.2.3/descrintro.html Subclassing object gets you a "new style" class and some additional capabilities. Maybe eventually it will not matter. -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib bug with Windows XP
it works! you da man! At the same time as my desktop was upgraded to Windows XP, the IT people switched virus checker products to McAfee Enterprise. And indeed, as soon as I disabled that 'mass worm sending' option, my Python scripts is once again able to send mail. thanks so much for this tip! 247 karma points for you. S -- http://mail.python.org/mailman/listinfo/python-list
Re: Help With Python
Nick Vargish wrote: Here's my Monty Pythonic answer: ## cut here class Viking(): def __init__(): pass def order(): return 'Spam' # this is one viking making one order repeated 511 times. if you want # 511 vikings making seperate orders, you'll have to write a loop. v = Viking() orders = [ v.order() ] * 511 print ', '.join(orders) No need to write a loop: py> class Viking(object): ... def order(self): ... return 'Spam' ... py> v = Viking() py> orders = [v.order()] * 7 py> ', '.join(orders) 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' py> orders = [Viking().order()] * 7 py> ', '.join(orders) 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Inherting from object. Or not.
Hello Frans, What you are seeing is a step on the path to unification of types and classes. Now we have that clear ;) Classes that inherit from object are 'new style classes'. They were introduced in 2.2 and they have different internal methods. The ones that have no declaration is an 'old style class'. http://www.python.org/doc/newstyle.html That link may be help. It is not required to write a class as 'class myclass(object)' yet, so many don't. In some cases it will matter which you use. In others cases it won't. Be sure to try this an an interpreter promt: Py> class NewKlass(object): ... pass Py> class OldKlass: ... pass Py> new = NewKlass() Py> old = OldKlass() Py> print dir(new) Py> print dir(old) Also new style classes are faster. Hth, M.E.Farmer Frans Englich wrote: > (Picking up a side track of the "python without OO" thread.) > > On Wednesday 26 January 2005 11:01, Neil Benn wrote: > > > I say this because you do need to be aware of the > > 'mythical python wand' which will turn you from a bad programmer into a > > good programmer simply by typing 'class Klass(object):'. > > What is the difference between inherting form object, and not doing it? E.g, > what's the difference between the two following classes? > > class foo: > pass > > class bar(object): > pass > > Sometimes people inherit from it, and sometimes not. I don't see a pattern in > their choices. > > > Cheers, > > Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
Le mercredi 26 Janvier 2005 21:44, PA a écrit : > On Jan 26, 2005, at 21:35, Francis Girard wrote: > >> Project fails for many reasons but seldomly because one language is > >> "better" or "worst" than another one. > > > > I think you're right. But you have to choose the right tools that fit > > your > > needs. But I think that's what you meant anyway. > > Yes. But even with the "best" tool and the "best" intents, projects > still fail. In fact, most IT projects are considered failures: > > http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 Well, let's go back home for some gardening. My wife will be happy. > > Cheers > > -- > PA > http://alt.textdrive.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: XOR on string
snacktime wrote: I need to calculate the lrc of a string using an exclusive or on each byte in the string. How would I do this in python? lrc == Linear Redundancy Check? or Longitudinal? Note that such terms are not precisely defined... generally just acronyms people make up and stick in their user manuals for stuff. :-) import operator lrc = reduce(operator.xor, [ord(c) for c in string]) Note that this returns an integer, so if you plan to send this as a byte or compare it to a character received, use chr(lrc) on it first. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Inherting from object. Or not.
(Picking up a side track of the "python without OO" thread.) On Wednesday 26 January 2005 11:01, Neil Benn wrote: > I say this because you do need to be aware of the > 'mythical python wand' which will turn you from a bad programmer into a > good programmer simply by typing 'class Klass(object):'. What is the difference between inherting form object, and not doing it? E.g, what's the difference between the two following classes? class foo: pass class bar(object): pass Sometimes people inherit from it, and sometimes not. I don't see a pattern in their choices. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Set parity of a string
snacktime wrote: Correction on this, ETX is ok, it seems to be just STX with the data I am using. On Wed, 26 Jan 2005 11:50:46 -0800, snacktime <[EMAIL PROTECTED]> wrote: I'm trying to figure out why the following code transforms ascii STX (control-b) into "\x82". The perl module I use returns a value of "^B", and that is also what the application I am communicating with expects to see. Some ascii characters such as FS and GS come through fine, but STX and ETX get transformed incorrectly (at least for what I need they do). I didn't see the first post, which you quoted above... more newsfeed or python-list misalignment I guess. :-( Anyway, since STX '\x02' has only one bit set, if you are setting the parity bit for "even" parity, then naturally it will be set (in order to make the total number of "on" bits an even number), so you get '\x82' (which has two bits set). ETX, on the other hand '\x03' already has two bits set, so the high bit is left alone. It sounds as though you need to examine the specification for the receiving system in more detail, or perhaps seek clarification from the other party involved in this system you're working with. If you have examples that show STX and ETX both being transmitted, around other data which itself has had the parity bit set for even parity, then clearly (a) the folks involved in designing that system are idiots <0.5 wink> and (b) you'll have to modify the way you are forming the transmission packet. It appears they may want the STX/ETX pair to be sent without being affected by the parity process... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Set parity of a string
Argh, never mind my mistake. I wasn't logging the data correctly the parity conversion works fine. Chris -- http://mail.python.org/mailman/listinfo/python-list
XOR on string
I need to calculate the lrc of a string using an exclusive or on each byte in the string. How would I do this in python? Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] 20050126 find replace strings in file
OK. But please don't die throwing that string, or this post will lose its educational purpose as it was meant to be. -- http://mail.python.org/mailman/listinfo/python-list
Re: can not use __methods__
[EMAIL PROTECTED] wrote: I try to use __methods__ in python 2.4 and 2.2 it always fail. Can some one tell me if I want to itterate the methods in a class and print it in a string format ( it is possible using __methods__ ). Is there any replacement? py> class C(object): ... a = 1 ... b = 2 ... def f(self): ... pass ... def g(self): ... pass ... py> import inspect py> for attr, value in C.__dict__.iteritems(): ... if inspect.isroutine(value): ... print attr, value ... g f or: py> for attr, value in vars(C).iteritems(): ... if inspect.isroutine(value): ... print attr, value ... g f or if you want to include special methods: py> for attr in dir(C): ... value = getattr(C, attr) ... if inspect.isroutine(value): ... print attr, value ... __delattr__ __getattribute__ __hash__ __init__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __str__ f g This is probably useful for introspection at the Python prompt, but if you're planning on doing this in your code somewhere, you might present the problem you're trying to solve to the list, because this is likely not the best way to approach it... Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
On Jan 26, 2005, at 21:35, Francis Girard wrote: Project fails for many reasons but seldomly because one language is "better" or "worst" than another one. I think you're right. But you have to choose the right tools that fit your needs. But I think that's what you meant anyway. Yes. But even with the "best" tool and the "best" intents, projects still fail. In fact, most IT projects are considered failures: http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 Cheers -- PA http://alt.textdrive.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
On Wednesday 26 January 2005 18:55, Terry Reedy wrote: > Your Four Steps to Python Object Oriented Programming - vars, lists, dicts, > and finally classes is great. It makes this thread worthwhile. I saved it > and perhaps will use it sometime (with credit to you) to explain same to > others. I think so too. M.E. Farmer's reflections on management was also a shining piece of gold in this thread. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Help With Python
Here's my Monty Pythonic answer: ## cut here class Viking(): def __init__(): pass def order(): return 'Spam' # this is one viking making one order repeated 511 times. if you want # 511 vikings making seperate orders, you'll have to write a loop. v = Viking() orders = [ v.order() ] * 511 print ', '.join(orders) ## cut here With no apologies to Eric Idle, Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
Le mercredi 26 Janvier 2005 20:47, PA a écrit : > Project fails for many reasons but seldomly because one language is > "better" or "worst" than another one. I think you're right. But you have to choose the right tools that fit your needs. But I think that's what you meant anyway. > > Cheers > Cheers too, Francis Girard FRANCE > -- > PA > http://alt.textdrive.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: access private field in python 2.4
[EMAIL PROTECTED] wrote: Hello, if we want to access the private member of object we use the classname, it doesn't make sense. For example: I have class A: class A: def __init__(self, i): self.__i = i; pass __i = 0 a = A(22); b = A(33); How can I get field i in object a and how can I get field i in object b? py> class A: ... def __init__(self, i): ... self.__i = i; ... py> a = A(22) py> a._A__i 22 Beside I try to call: print _A__i #fail this create error Looks like you're confused about the difference between instances and modules. The code: print _A__i asks Python to print the attribute _A__i of the given module. But you want the attribute _A__i of the instance 'a'. As you can see in my code, if you want the attribute of the instance, you need to specify it as such. As an additional reminder, you generally *shouldn't* be accessing "private" variables of a class. There's a reason they're declared private. ;) Steve -- http://mail.python.org/mailman/listinfo/python-list