ANN: new python-porting mailing list
Hi all, to facilitate discussion about porting Python code between different versions (mainly of course from 2.x to 3.x), we've created a new mailing list [EMAIL PROTECTED] It is a public mailing list open to everyone. We expect active participation of many people porting their libraries/programs, and hope that the list can be a help to all wanting to go this (not always smooth :-) way. regards, Georg signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
lockfile 0.6 supports Python 2.x and 3.x
I've just released lockfile 0.6. This version supports Python 2.4, 2.5, 2.6 and 3.0. It also expands the unit tests a bit. What is lockfile? The lockfile module exports a FileLock class which provides a simple API for locking files. Unlike the Windows msvcrt.locking function, the Unix fcntl.flock, fcntl.lockf and the deprecated posixfile module, the API is identical across both Unix (including Linux and Mac) and Windows platforms. The lock mechanism relies on the atomic nature of the link (on Unix) and mkdir (On Windows) system calls. Where can I get lockfile? The lockfile module is available from the Python Package Index: http://pypi.python.org/pypi/lockfile Please send feedback, questions and bug reports to me. -- Skip Montanaro - [EMAIL PROTECTED] - http://smontanaro.dyndns.org/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Guido's new method definition idea
Steven D'Aprano wrote: On Fri, 05 Dec 2008 20:35:07 -0800, James Stroud wrote: Daniel Fetchinson wrote: I'd like this new way of defining methods, what do you guys think? Consider the maverick who insists on class C: def me.method(arg): self.value = arg Replace self with me. Yes, I corrected myself one minute after I made the typo. which should be equivalent to class C: def method(me, arg): me.value = arg What's the interpreter going to do with our maverick's code? I don't see why you think this is a problem. The behavior was unspecified as far as I could tell and I was curious as to whether me would still be allowed as a reference to self. Allowing alternatives to self would maintain backwards compatibility as the use of self has been a convention and not enforced by the language. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
try this: import this and look at the 15th line... I agree that for newcomers to Python, the class method definition might seem strange. I certainly had problems with it when starting with Python, coming from Java. But in the meantime it feels right. I don't know if it is because I'm used to the old way, but I find the proposed alternative way slightly less readable. Altough these are no technical considerations, I'm -1 on this. Daniel Fetchinson wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic design patterns
Hallo, users in this forum has been kind enough to point out. Only my implementations are often not that clean, and I may call things something different than the normal convention, which is a source of confusion for myself and others trying to communicate with me. I think, you should start with the classical books of Design Patterns to get a solid understanding and especially vocabulary to communicate with your coworkers. Its easier and better to say, that you will use a strategy pattern than to describe the architecture in many sentences to your partner in a ambigious way. Thats in my opinion the first and the key benefit of Design Patterns. Speaking in the same language. The next step should be to apply your knowledge to your programming language. So I will recommend the classical GOF Books and the serie Pattern Oriented Software Architecture. Greetings Rainer -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Allowing $ as a substitute for self wouldn't require this new syntax. class C: def method($, arg): $.value = arg I'm strongly against this. This looks ugly and reminds me of Perl and Ruby. (I don't have anything against these languages, but there's a reason I use Python). Russ P. wrote: On Dec 5, 6:21 pm, Daniel Fetchinson [EMAIL PROTECTED] wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- Psss, psss, put it down! -http://www.cafepress.com/putitdown I like it. I'll even go a step further and suggest that $ be allowed as a substitute for self. It looks like a capital S (for Self), and it stands out clearly. It also makes code more succinct with no loss of readability. Think of the line wraps that could be avoided. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: try this: import this and look at the 15th line... The reason why I'm against that change too. It adds a second, alternative way to express something that is already in the language. I agree that for newcomers to Python, the class method definition might seem strange. And after the change it continues to because they will run into *both* variants in tutorials, code, and books, so it might be even more confusing. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Running Python 2 and Python 3 on the same machine
Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make altinstll'. It created an executable /usr/local/bin/python3.0 file. Nothing was touched in /usr/bin. Ah, then you missed the fun part. Take a look at the install: target in the Makefile. I need to start writing some code with Python 3. I want to write the code in such a way that it can be easily shared with others with the least difficulty and overhead as possible. How should I write the code to enable this? What, if anything, should I assume about another system's configuration? I don't quite understand the problem. Sharing code is very easy over the internet. You can upload it on PyPI (say), or mail it. So you must be asking for something else. As someone suggested before, naming the files as '.py3' is probably a bad idea in the long run. It also does not really solve the problem. I could use a shebang. But, what should it specify? If I use 'python3.0', then that will soon be quite old. If I make up a link for python3 - python3.0, that would work, but then every other system that is to run the code must that link also. However, I am thinking that this would be the best long term answer. Well, this will be rejected. It might be a good medium-term answer, but it is a *bad* long-term answer. In the long term, Python 2 will disappear, and we are stuck with calling the interpreter python3. If I write scripts for Python 3, another developer writes scripts for Python 2, and a common customer wants to install both of our packages onto a single machine, then what is the best plan for everyone to make that happen with as little difficulty as possible? My recommendation is to use distutils, for a long-term answer. People will run python3.0 setup.py install, and distutils' install_scripts will replace the shebang line with the actual path to Python 3.0. This has not only the advantage of continuing to work for 3.1; it has also the advantage that scripts installed into a private location will be run by the correct interpreter (rather than relying on the interpreter being in /usr/bin, or on PATH). For quick sharing, the shebang line #!/usr/bin/env python3.0 will be enough. When Python 3.1 gets released, you may find yourself writing scripts that run only on Python 3.x for x=1 (i.e. won't run on 3.0, because you use a new feature in 3.1). In that case, presence of a python3 executable won't help, either. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't you just love writing this sort of thing :)
Lawrence D'Oliveiro [EMAIL PROTECTED] writes: In message [EMAIL PROTECTED], Aaron Brady wrote: On Dec 5, 4:32 am, Lawrence D'Oliveiro [EMAIL PROTECTED] central.gen.new_zealand wrote: The code people write is probably a direct reflection of their thinking processes: For example, slow, plodding, one step at a time, incapable of imaginative leaps, versus those who operate directly on larger patterns at once... That distinction operates indirectly on smaller patterns. Do you find this (open, gzip.GzipFile)[Entry.endswith(.gz)](os.path.join(PatchesDir, Entry), r) complicated or hard to understand? (aside: it's funny that someone asks Aaron this quesion as he is the one who used to post code that almost nobody understood! (although I had a feeling there was often something interesting in it)). in Python it is a convention only to capitalize classes, so unless Entry and PatchesDir are classes it would be better to write them as entry and patches_dir for example. Why use (open, gzp.GzipFile)[Entry.endswith(.gz)] when we have had contitional expressions for a few years now? Instead, you can write (gzip.GzipFile if entry.endswidth(.gz) else open). I think it will be faster (as it doesn't require the construction of a tuple and then the retrieval of one of its elements) and clearer. It's good to be able to understand (and I guess, to write) such code. But to assume that others dislike it because they don't understand it sends several wrong signals: * you give the impression of being arrogant; * many people will understand this code snippet perfectly easily but they won't like it because they think that Python offers much better ways to express the same thing. * you seem to disregard the fact that in 'programming language' there is the word 'language'. A language is a way to _communicate_ information, in the case of a programming language you communicate it to the computer but also to other human beings. To come back to your code, you could define a function like the one below (untested). It'll allow you to add support for different compression formats easily in the future. This is a 'pattern' which can be useful to keep in mind and requires *some* imagination. open_methods = { 'gz': gzip.GzipFile, 'bz2': bz2.BZ2File } def open_by_ext(path, *args): ext = os.path.splitext(path)[1] return open_methods.get(ext, open)(path, *args) Then your code snippet becomes: open_by_ext(os.path.join(patches_dir, entry), r) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't you just love writing this sort of thing :)
On Sat, 06 Dec 2008 20:28:17 +1300 Lawrence D'Oliveiro [EMAIL PROTECTED] wrote: Does that make any sense to you, or should I start drawing simple diagrams? People, please! Is some civility too much to ask? /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On 6 Dec 2008 09:18:20 GMT Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: [snip reference to preferably only one way to do it] The reason why I'm against that change too. It adds a second, alternative way to express something that is already in the language. I agree that for newcomers to Python, the class method definition might seem strange. And after the change it continues to because they will run into *both* variants in tutorials, code, and books, so it might be even more confusing. I agree with that view. Not much to add to it, just increasing the weight. /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python and files directory
On Dec 6, 1:52 am, mete bilgin [EMAIL PROTECTED] wrote: Hi all, I try to make a websevice with python and mod_python. İ try to make a po files, but i can not reach them in the page. When i ask the page like os.listdir('.') but i want to get files directory, what can i do? sorry for my bad describe of that. Thanks a lot... The current working directory in Apache can be anything. You must supply an absolute path to all directories/files you are trying to access/use. Graham -- http://mail.python.org/mailman/listinfo/python-list
Netbeans Early Access and Python3
Hi, have anyone using this release of NetBeans (6.5 with Python support) with Python 3 without any problems ? I mean, does it work with Python3 or only with 2.x ? -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python and files directory
but i want to take it somewhere else...i want to it work some other path in other system. On Saturday 06 December 2008 12:34:07 Graham Dumpleton wrote: On Dec 6, 1:52 am, mete bilgin [EMAIL PROTECTED] wrote: Hi all, I try to make a websevice with python and mod_python. İ try to make a po files, but i can not reach them in the page. When i ask the page like os.listdir('.') but i want to get files directory, what can i do? sorry for my bad describe of that. Thanks a lot... The current working directory in Apache can be anything. You must supply an absolute path to all directories/files you are trying to access/use. Graham -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP!...Google SketchUp needs a Python API
On Dec 3, 10:06 am, r [EMAIL PROTECTED] wrote: If we can laugh what else would we do I'd like to touch also on some comments by ajaksu: [ajaksu] I'd like to try hacking some form of Python to work in SketchUp (on top of Ruby, that is). Now, why won't I try to? I'm a Linux user and we don't get a SU version. So much for FREEDOM. BTW, some things in SU have encrypted Ruby code behind them :) [/ajaksu] You CAN use SketchUp on Linux...ajaksu...thru Wine, but I know this is not good enough. I would love to see FULL SketchUp support for linux and I HAVE made my voice heard. I urge you brother to make make your voice heard also. Go to this thread and let your voice be heard:http://groups.google.com/group/sketchupsuggestions/browse_thread/thre... This is the reason...amoung many others...that Linux has yet to take any noticable market from MS. Linux could...If the Linux devolpers would ban together and unite to make package managment and portability between all *nix's universal, OR one great linux distro that the average dummy can use(ubuntu looks promising, but still has a long way to go)...compete with microsoft on a grand level. We have to steal the idiots from under microsoft's feet, and they will come crumbling down. But as long as a poor n00b installs his shiny new *nix system and can't even connect to the network to see the latest janet jackson wardrobe malfunction, or fiqure out how to mount a flash drive, Linux will be nothing more than our beloved oddessy. There will NEVER be good support on linux for most applications, games, etc... Until people start to get behind linux and support it. Now you say, well i don't have time to support this, my life is too busy, my back hurts. I say stop making excuses. You DON'T have to invest your life, just simply make your voice heard.(myself and other dedicated people will tow the load). But at least get off your bum and do something. It's time to change the world, the hour is upon us, Microsoft is asleep at the wheel, the time for revolution is NOW! Action speaks louder than words. Not that I have done anything than talking lately though. For Google to implement a huge feature like python scripting, they would want to calculate its business feasibility (though Google is one of the rare companies that is extremely lax on this side). Sketchup's target users is not power users but those who need quick sketches, so scripting isn't an extremely important feature in Sketchup. Moreover, if they implement python scripting because someone wants it, other languages would demand the same. So, it does have to start from you creating a python-extension and getting enough users to make Google think: There are much more python programmers than Ruby programmers in Sketchup, implementing python scripting would be a sound decision. -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't you just love writing this sort of thing :)
On Dec 5, 7:20 pm, Lawrence D'Oliveiro [EMAIL PROTECTED] central.gen.new_zealand wrote: In message [EMAIL PROTECTED], Aaron Brady wrote: On Dec 5, 4:32 am, Lawrence D'Oliveiro [EMAIL PROTECTED] central.gen.new_zealand wrote: The code people write is probably a direct reflection of their thinking processes: For example, slow, plodding, one step at a time, incapable of imaginative leaps, versus those who operate directly on larger patterns at once... That distinction operates indirectly on smaller patterns. Well, I was trying to be funny. But sarcasm is defined as something said in jest that someone else would say seriously; so perhaps it's not the most reliable tone for text. Chalk it up to a failed communication, even though a successful expression. I agree that programming takes imaginative leaps and operates on large patterns. You implied that people's thinking processes vary by pattern size, which I thought was interesting. But 'leaps' implies carelessness (wrong word, possibly). Is it possible to tackle a large pattern one step at a time? Say, writing a quick sort in assembly? Do you find this (open, gzip.GzipFile)[Entry.endswith(.gz)](os.path.join(PatchesDir, Entry), r) complicated or hard to understand? It's not easy. I can't understand it at a glance, if that is your question. But it's not obfuscated, that is true. If I can compare programming to chess: I look at a board and you tell me, 'white to play, mate in 5 moves.' If the board is busy (not just Rook and King), it could take a long time to find the mate. It's complicated, but not hard to understand. It requires holding (introducing a term) several things in mind at once: first expose the Bishop, then capture the Pawn, etc. But it is not easy in the same way that a 'mate in one' board is, even though the pieces are the same. It's made up of very simple pieces, combined according to very simple rules, viz:- A tuple of candidate functions: (open, gzip.GzipFile) A choice from that tuple according to a condition: [Entry.endswith(.gz)] And finally, arguments to pass to the chosen function: (os.path.join(PatchesDir, Entry), r) As you explain, your program (taking the fragment to be an entire program) is composed of three very simple pieces. I would say, write them as three very simple pieces. Here's a possible compromise between yours and Arnaud's: if Entry.endswith(.gz): opener= gzip.GzipFile else: opener= open opener( os.path.join(PatchesDir, Entry), r ) It's kind of swampy, I concede. About the same number of characters, 5x the lines. Maybe something in between: opener= (open, gzip.GzipFile)[Entry.endswith(.gz)] path= os.path.join(PatchesDir, Entry) opener( path, r ) See, it's so simple, a child could understand it. A child who isn't burdened with the preconceptions that seem to afflict some participants in this noisegroup... 'No preconceptions' is a pretty tall order. The most basic facts about the natural numbers weren't formalized until the 1880s, but people used them successfully for thousands of years before, evidently on preconception alone. To be plodding and slow (as well as meticulous and deliberate, by the way), the child would need 'preconceptions' about tuples, functions, Boolean variables, etc. You might call those plain 'conceptions', and use the other definition, 'bias' for noisegroup participants. Emotions are biased, as are small sample sizes (small-sized samples). I think it's also a tall order to ask a group of people to keep objective for any length of time. Thus, since we're people, and we're interacting, and we can't keep objective forever, we'll be non- objective sometimes, and therefore won't all understand your program. Perhaps you are wanting to write a 'preconception-tolerant' program: a program that is tolerant of (can be read by) readers with preconceptions. But I'll bite: what preconceptions? Favoritism? -- http://mail.python.org/mailman/listinfo/python-list
Re: slow Python 3.0 write performance?
Istvan Albert wrote: A previous poster suggested that in this case the slowdown is caused by the new io code being written in python rather than C. For text mode Python 3's write() method is slower than Python 2.x's method because all text is encoded. The slowdown is mostly caused by additional code for line ending detection and decoding/encoding. The new io library does more than the old file object So far the new io library hasn't been optimized yet, too. Please give it some time and report speed issues at http://bugs.python.org/. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Antoine De Groote: Allowing $ as a substitute for self wouldn't require this new syntax. class C: def method($, arg): $.value = arg I think this (that is just sugar) may be a little better: class C: def method($, arg): $value = arg Or even this, combined with the idea suggested in the post by Guido: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Insert Multiple Records Using One Insert Statemen with MySQLdb module
Hi, I'd like to insert Multiple Records Using One Insert Statement inserting one record using one insert statement works this is the example: import MySQLdb conn = MySQLdb.connect(host=localhost,.) cursore = conn.cursor() cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10) ) but when I try to insert Multiple Records Using One Insert Statement in this way: cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10), ('Pompelmi', 10), ('Pompelmi', 10) ) it doesn't work! Antonella -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 5, 8:21 pm, Daniel Fetchinson [EMAIL PROTECTED] wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. ... Would it be valid outside class definitions too? (As follows...) def sequence.shuffle( ): x= sequence[ 0 ] sequence[ 0 ]= sequence[ -1 ] ...etc. shuffle( listA ) Can you still call it by class membership? (As follows...) C.method( inst, arg ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] wrote: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... But that is not the way Python is meant to work. There are several tennets in the Zen of Python that don't chime well with this approach. self is a speaking identifier, $ isn't. we've-been-through-this-ingly yours /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Sat, 6 Dec 2008 13:32:58 +0100 Andreas Waldenburger [EMAIL PROTECTED] wrote: On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] suggested: class C: def $method(arg): $value = arg [snip] [snip] self is a speaking identifier, $ isn't. Also, nothing prevents you from replacing self with s if you really want it short. Same effect as your s suggestion (OK, plus one .). /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: Insert Multiple Records Using One Insert Statemen with MySQLdb module
On Sat, 2008-12-06 at 04:03 -0800, [EMAIL PROTECTED] wrote: Hi, I'd like to insert Multiple Records Using One Insert Statement inserting one record using one insert statement works this is the example: import MySQLdb conn = MySQLdb.connect(host=localhost,.) cursore = conn.cursor() cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10) ) but when I try to insert Multiple Records Using One Insert Statement in this way: cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10), ('Pompelmi', 10), ('Pompelmi', 10) ) it doesn't work! You want to use the cursor's .executemany() method. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get exclusive file lock when safely renaming a file
Steven D'Aprano wrote: cut import os, fcntl oldname = ham.txt newname = spam.txt def lock_destination(name): fileno = os.open(name, os.O_CREAT | os.O_EXCL) fcntl.flock(fileno, fcntl.LOCK_EX) # POSIX systems only return fileno # Create a test file to be renamed. f = open(oldname, 'w') f.write('this is my file\n') f.close() fileno = lock_destination(newname) # At this point, I can see ham.txt plus an empty file # spam.txt in my file browser os.rename(oldname, newname) The rename works, but here is my problem: after getting what I thought was an exclusive lock on the new file, but before calling os.rename(), I can still over-write it from another process: $ echo this comes from another process spam.txt $ cat spam.txt this comes from another process cut This is weird, you would indeed expect it to be locked, I tried it on FreeBSD and it behaves the same. I guess the behavior of os.rename should be changed so it raises an exception when the source destination exists independent on the below platform. I tried searching for another way to do it but the closest I came was to popen mv and raise an exception if it asks to overwrite the existing file. Sorry I can't be of more help. -- mph -- http://mail.python.org/mailman/listinfo/python-list
Learning Python now coming from Perl
I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, but I now Perl pretty well. I'm also well experienced with JavaScript. Any pointers and tips how I should go about getting into Python? -- Bertilo Wennergren http://bertilow.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple Versions of Python on Windows XP
Glenn Linderman wrote: On approximately 12/1/2008 11:29 PM, came the following characters from the keyboard of Martin v. Löwis: It would be nice if the ftypes were version specific as created by the installer; IIRC, I created the above three from the ftype Python.File as I installed each version. That's a good idea; please submit a wish list item to bugs.python.org. There may be issues (such as people relying on this being Python.File), but I can't see any problems off-hand. Regards, Martin OK, Issue 4485 created. My first one, so let me know if I goofed. I elaborated a bit from the original email, upon reflection. Seemed useful, but also seemed complex by the time I got done. I don't really have a clue what the uninstaller should do with these; nor have I fiddled to know if it presently removes Python.File. I suppose it should delete them, if and only if the ftype and assoc have the same content as was created by the corresponding version installation. Here's another approach to handling multiple versions of Python, thanks to the PyScripter List. It does not address the need to access different versions of the Python Interpreter. Here is the full story. There are two types of Python installation a) For all users Python creates registry entries at HKEY_LOCAL_MACHINE\SOFTWARE\Python \PythonCore\2.x with installation info and puts the dll in c:\Windows \System32. b) For a single user Python creates registry entries at HKEY_CURRENT_USER\SOFTWARE\Python \PythonCore\2.x with installation info and does not put the dll in c: \Windows\System32. PyScripter without any command line flags looks at the registry to find the latest version of Python and then for an all user installation tries to load the relevant Python dll from the system path. For a single user installation tries to load the DLL from the Install path that is in the registry. When PyScripter is used with a --PYTHONxx flag then it does the above but searching only for the specific version. The Registry lookup does not take place when Python is used with the -- PYTHONDLLPATH. Instead PyScripter tries to load the Python dll from the specified path. The --PYTHONDLLPATH flag should be used with the --PYTHONxx flag. See http://pyscripter.googlepages.com/portablepython for an example of using PyScripter with portable Python. The %PYTHONHOME% variable is not used by PyScripter directly but by Python to find the installed libraries. See the Python documentation for its use. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
python book for non technical absolute beginner
Hi, One of my 'non technical' friends complained about knowing nothing at all about programming (though using computers regularly for mails / web browsing / googling and downloading / cropping photos ) He wants to play a little with programming to stimulate parts of his otehrwise idle brain cells. ;-) Normally it's more the social science / linguistic parts being exercised, I thought python might be a nice language for this No my question does anybody know a nice beginners book (or a learning CD or on line tutorial)? Ideally it shouldn't be too serious and have a lot of small nice mini-examples thanks in advance for any suggestions hints bye N -- http://mail.python.org/mailman/listinfo/python-list
Re: To Troll or Not To Troll (aka: as keyword woes)
On Dec 6, 2:22 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: I see your wink, but, please, did you read that thread started by r about the Ruby API for some piece of Google software? That was so offensively fanboyish that I almost removed Python from my computer. The one wjere I was accused of wanting to hold back the evolution of Python amongst suggestions that I needed to get laid? Oh yeah, I saw it... I'm also not convinced it wasn't faux advocacy for the sake of trolling. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
[EMAIL PROTECTED] wrote: Antoine De Groote: Allowing $ as a substitute for self wouldn't require this new syntax. class C: def method($, arg): $.value = arg I think this (that is just sugar) may be a little better: class C: def method($, arg): $value = arg Well, in this case there would be no need to have the $ in the arguments list, as it would be like a keyword, or a keysymbol in this case, like the this keyword in Java for instance. I dislike this even more than the dotted version. Or even this, combined with the idea suggested in the post by Guido: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple Versions of Python on Windows XP
SciTE doesn't do that, in the default configuration it just uses whatever is called pythonw on the path, for running files having a .py or .pyw suffix. I see. By default, Python does not put itself onto PATH. Does that mean that SciTE cannot run Python scripts in the default installation? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
In article [EMAIL PROTECTED], Bertilo Wennergren [EMAIL PROTECTED] wrote: I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, but I now Perl pretty well. I'm also well experienced with JavaScript. Any pointers and tips how I should go about getting into Python? I assume you use Perl to solve real problems in whatever job you do. My recommendation would be the next time some problem comes up that you would normally solve with Perl, try doing it in Python. Having a real task that you need to accomplish is a great way to focus the mind. For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. One of the very first things you'll probably discover that's different between Perl and Python is how they handle string pattern matching. In Perl, it's a built in part of the language syntax. In Python, you use the re module. The regular expressions themselves are the same, but the mechanism you use to apply them to input text is quite different. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Aaron Brady wrote: On Dec 5, 8:21 pm, Daniel Fetchinson [EMAIL PROTECTED] wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. ... Would it be valid outside class definitions too? (As follows...) def sequence.shuffle( ): x= sequence[ 0 ] sequence[ 0 ]= sequence[ -1 ] ...etc. shuffle( listA ) This is not what was intended. The discussion was explicitly only about class methods. What you are describing is weird and not generalizable. What if your method takes more than one parameter? You might argue that sequence would be the first argument in the list, like def sequence.shuffle(a, b): a, b: dummy arguments, just for the sake of the example x = sequence[0] sequence[0] = sequence[-1 ...etc. shuffle(listA, 1, 1) I can't think of any good reason to do this. What's more, the whole discussion was partly due to error messages like Traceback (most recent call last): File classes.py, line 9, in obj.m2(1) TypeError: m2() takes exactly 3 arguments (2 given) Your proposition (well actually it is only a question) would result in error messages exactly like this one when one would not carefully read the method signature for example. Can you still call it by class membership? (As follows...) C.method( inst, arg ) That should not change at all, as the alternative syntax would actually be only syntactic sugar. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
James Stroud jst...bi.ucla.edu wrote: Consider the maverick who insists on 8example with me instead of self What's the interpreter going to do with our maverick's code? Took me a while, but after I remembered that a maverick is an unmarked, wild member of the bovine species that is effectively res nullius, I suppose the answer should be that he or she be brought back into the fold by being branded in the normal fashion - the application of a hot iron, in the shape of the standard python logo, to the buttocks. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 3.0 final
Ben Finney [EMAIL PROTECTED] wrote: I hereby recommend “pish and tosh” for use by anyone who wants to counter someone's point. It beats by a country furlong the invective that has become regrettably common here in recent months. I second the motion to use pish and tosh for a first level of disagreement. I recommend the rather archaic Balderdash as the next step in the escalation of disagreement... - hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
Roy Smith wrote: Bertilo Wennergren [EMAIL PROTECTED] wrote: I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, but I now Perl pretty well. I'm also well experienced with JavaScript. Any pointers and tips how I should go about getting into Python? I assume you use Perl to solve real problems in whatever job you do. My recommendation would be the next time some problem comes up that you would normally solve with Perl, try doing it in Python. Having a real task that you need to accomplish is a great way to focus the mind. For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. Good advice. One of the very first things you'll probably discover that's different between Perl and Python is how they handle string pattern matching. In Perl, it's a built in part of the language syntax. In Python, you use the re module. The regular expressions themselves are the same, but the mechanism you use to apply them to input text is quite different. Thanks. I don't suppose there is any introductory material out there that is based on Python 3000 and that is also geared at people with a Perl background? Too early for that I guess.. -- Bertilo Wennergren http://bertilow.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Daniel Fetchinson wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel The quoted blogspot is not available. I like the idea but I don't see how explicit and implicit can co-exist. Version 3.0 is the time to introduce the enhancement. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
__import__ problem
Hi all, When I try to import a module via __import__, I am facing ImportError. But, when I tried to import it via usual 'import', it worked fine. Please see below: try: import exact except: logging.exception('Error during importing') try: code = __import__('exact') except: logging.exception('Is it still happening?') The error is as: 2008-12-06 20:06:59,328 ERROR Is it still happening? Traceback (most recent call last): File C:\django\test\..\test\basic\views.py, line 166, in getValue code = __import__('exact') ImportError: No module named exact Could you please let me know why this is happening? I tried to __import__ 'sys etc, and it worked fine. Is it due to some issue in the path? Regards K -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 5, 7:21 pm, Daniel Fetchinson [EMAIL PROTECTED] wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- Psss, psss, put it down! -http://www.cafepress.com/putitdown Sigh. If you make --both-- self and cls keywords, then 90% of the problems that Guido mentions in the blogspot post just vanish because whether it's an instance method, a class method or a static method can be inferred from the method body. In particular, the decorator problem goes away (the decorators are irrelevant, and can be ignored) and so does the problem with injecting a method into an object. It is, of course, harder to implement, and it would not be backwards compatible because all the internal wrappers vanish as well. That makes problems for anyone who is looking through __dict__ to find particular kinds of method. John Roth -- http://mail.python.org/mailman/listinfo/python-list
How you can save fuel and the environment
Driving and Car Maintenance Transportation accounts for 66% of U.S. oil use -mainly in the form of gasoline. Luckily, there are plenty of ways to improve gas mileage. Driving Tips:- Idling gets you 0 miles per gallon. The best way to warm up a vehicle is to drive it. No more than 30 seconds of idling on winter days is needed. Anything more simply wastes fuel and increases emissions.- Aggressive driving (speeding, rapid acceleration, and hard braking) wastes gas. It can lower your highway gas mileage 33% and city mileage 5%. Drive at lowest and constant rpms; 2000 rpm are enough; you can save up to 30%. Even a Porsche can be driven at the 4th gear at 20 mph and at the 6th gear at 50 mph with 2.5 times less fuel consumption.- Avoid high speeds. Driving 75 mph, rather than 65 mph, could cut your fuel economy by 15%.- When you use overdrive gearing, your cars engine speed goes down. This saves gas and reduces wear.- Use air conditioning only when necessary.- Clear out your car; extra weight decreases gas mileage. Each 60 pounds increases fuel consumption by 10%. - Reduce drag by placing items inside the car or trunk rather than on roof racks. A roof rack or carrier provides additional cargo space and may allow you to buy a smaller car. However, a loaded roof rack can decrease your fuel economy by 5%.- Check into carpooling and public transit to cut mileage and car maintenance costs. Car Maintenance Tips:- Use the grade of motor oil recommended by your cars manufacturer. Using a different motor oil can lower your gasoline mileage by 1% to 2%.- Keep tires properly inflated and aligned to improve your gasoline mileage by around 3.3%.- Get regular engine tune- ups and car maintenance checks to avoid fuel economy problems due to worn spark plugs, dragging brakes, low transmission fluid, or transmission problems.- Replace clogged air filters to improve gas mileage by as much as 10% and protect your engine.- Combine errands into one trip. Several short trips, each one taken from a cold start, can use twice as much fuel as one trip covering the same distance when the engine is warm. Do not forget that in the first mile your car uses 8 times more fuel, in the second mile 4 times and only after the fourth mile it becomes normal.Long-Term Savings Tip- Consider buying a highly fuel-efficient vehicle. A fuelefficient vehicle, a hybrid vehicle, or an alternative fuel vehicle could save you a lot at the gas pump and help the environment.See the Fuel Economy Guide (www.fueleconomy.gov) for more on buying a new fuel-efficient car or truck. Source: www.eere.energy.gov and http://www.vcd.org/155.html -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 3.0 final
2008/12/5 Hendrik van Rooyen [EMAIL PROTECTED]: I second the motion to use pish and tosh for a first level of disagreement. I recommend the rather archaic Balderdash as the next step in the escalation of disagreement... http://bash.org/?23396 -- Dotan Cohen http://what-is-what.com http://gibberish.co.il א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه-و-ي А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я ä-ö-ü-ß-Ä-Ö-Ü -- http://mail.python.org/mailman/listinfo/python-list
Detaching e-mail attachments?
Hi, all. I've done some poking around, and can find roughly two million different ways to attach attachments to an e-mail... but darn few to detach them. Any suggestions? I'm assuming I'm just missing looking in The Right Place, but thus-far, my Googling has been for naught. Thanks! -Ken -- http://mail.python.org/mailman/listinfo/python-list
Re: python book for non technical absolute beginner
Yes, there is an excellent book for absolute beginners call Python Programming, for the absolute beginner (second edition by Michael Dawson. Here are the reasons why it is excellent for a beginner. It doesn't go beyong basic math as do most other computer books when giving examples, exercises or programs illustrating any language including Python. It teaches the basic phython in 9 chapters and the goes on to teach some basic graphics using Python. But for me and many others the first 9 chapters are perfect and awesome to work through. Most books attempting to teach any subject start off with a few easy basic chapters and then jumpt into complex explanations and examples. Not so with this book. It gives consistent easy to understand examples/code often in the form of a simple game which fun. No book I have seen, read or own on Python teaches the very basic principles of writing code as easily understood as this book. There are many excellent web sites around the world in many languages that teach basic Python with free texts and examples, but for somone with little or no programming experience or a first timer at programming with modest math skills, it is perfect. News123 wrote: Hi, One of my 'non technical' friends complained about knowing nothing at all about programming (though using computers regularly for mails / web browsing / googling and downloading / cropping photos ) He wants to play a little with programming to stimulate parts of his otehrwise idle brain cells. ;-) Normally it's more the social science / linguistic parts being exercised, I thought python might be a nice language for this No my question does anybody know a nice beginners book (or a learning CD or on line tutorial)? Ideally it shouldn't be too serious and have a lot of small nice mini-examples thanks in advance for any suggestions hints bye N -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 1:02 am, Antoine De Groote [EMAIL PROTECTED] wrote: Allowing $ as a substitute for self wouldn't require this new syntax. class C: def method($, arg): $.value = arg I'm strongly against this. This looks ugly and reminds me of Perl and Ruby. (I don't have anything against these languages, but there's a reason I use Python). Russ P. wrote: On Dec 5, 6:21 pm, Daniel Fetchinson [EMAIL PROTECTED] wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- Psss, psss, put it down! -http://www.cafepress.com/putitdown I like it. I'll even go a step further and suggest that $ be allowed as a substitute for self. It looks like a capital S (for Self), and it stands out clearly. It also makes code more succinct with no loss of readability. Think of the line wraps that could be avoided. It looks ugly simply because it is new to you. Once you get used to it, I'll bet it will look fine. And resemblance to another language is not a very good reason to reject it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
Bertilo Wennergren wrote: Roy Smith wrote: Bertilo Wennergren [EMAIL PROTECTED] wrote: I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, but I now Perl pretty well. I'm also well experienced with JavaScript. Any pointers and tips how I should go about getting into Python? I assume you use Perl to solve real problems in whatever job you do. My recommendation would be the next time some problem comes up that you would normally solve with Perl, try doing it in Python. Having a real task that you need to accomplish is a great way to focus the mind. For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. Good advice. One of the very first things you'll probably discover that's different between Perl and Python is how they handle string pattern matching. In Perl, it's a built in part of the language syntax. In Python, you use the re module. The regular expressions themselves are the same, but the mechanism you use to apply them to input text is quite different. Thanks. I don't suppose there is any introductory material out there that is based on Python 3000 and that is also geared at people with a Perl background? Too early for that I guess.. This is from a post within the last few days: http://www.qtrac.eu/pyqtbook.html Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 4:32 am, Andreas Waldenburger [EMAIL PROTECTED] wrote: On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] wrote: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... But that is not the way Python is meant to work. There are several tennets in the Zen of Python that don't chime well with this approach. self is a speaking identifier, $ isn't. Is @ a speaking identifier? How about # and !=? Last I heard, they were all part of Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 4:37 am, Andreas Waldenburger [EMAIL PROTECTED] wrote: On Sat, 6 Dec 2008 13:32:58 +0100 Andreas Waldenburger [EMAIL PROTECTED] wrote: On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] suggested: class C: def $method(arg): $value = arg [snip] [snip] self is a speaking identifier, $ isn't. Also, nothing prevents you from replacing self with s if you really want it short. Same effect as your s suggestion (OK, plus one .). Yes, you can always use s. But single-letter identifiers are not usually a good idea, because they are hard to search on. A slightly better option is S, which is a little better for searching but not as good as $. I have considered using S extensively in my code, but I hesitate because it is not recognized in official Python coding standards. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Sat, 06 Dec 2008 07:15:27 -0800, Russ P. wrote: On Dec 6, 4:32 am, Andreas Waldenburger [EMAIL PROTECTED] wrote: On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] wrote: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). If -- and that's a HUGE if -- the compiler is changed to allow $method, it could certainly be changed to allow $.method. Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... If a line of code uses too many instance attributes to fit comfortably on a line, spread it over two lines. There is no newline shortage, they are a renewable resource. But that is not the way Python is meant to work. There are several tennets in the Zen of Python that don't chime well with this approach. self is a speaking identifier, $ isn't. Is @ a speaking identifier? How about # and !=? Last I heard, they were all part of Python. Yes they are. @f is pronounced at f or decorate f. # comment is pronounced hash comment or even not pronounced at all. x != y is pronounced x not equal to y The proposed def $method(arg): would be pronounced def dollar method arg or def method self arg. The first is ugly to my ears, the second confusing. -2 on this proposal. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. Is there anything which *can't* be written in under 50 lines of Perl? :-) One of the very first things you'll probably discover that's different between Perl and Python is how they handle string pattern matching. In Perl, it's a built in part of the language syntax. In Python, you use the re module. The regular expressions themselves are the same, but the mechanism you use to apply them to input text is quite different. Also, Perl REs are faster than Python REs, or so I'm told. Between the speed and the convenience, Perl programmers tend to use RE's for everything they can. Python programmers tend to use REs only for problems that *should* be solved with REs rather than *can* be solved with a RE. Well, I say tend, but in truth we get our fair share of questions like Hi, how do I factorize a 20 digit number with a regular expression? too. Probably the biggest difference is that in Python, you always refer to objects the same way, regardless of what sort of data they contain. Regardless of whether x is a scalar or a vector, you always call it just plain x. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Daniel Fetchinson a écrit : Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value (snip) I'd like this new way of defining methods, what do you guys think? -1 As far as I'm concerned, it doesn't add anything to the language, nor doesn't save any typing, so I just don't see the point. And having it co-existing with the normal syntax will only add more confusion. NB : FWIW, I would eventually have voted -0 if it had been proposed for Python 3, and as a _replacement_ (not _alternative_) to the current syntax. But Python 3 is now released, so... -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Russ P. wrote: On Dec 6, 1:02 am, Antoine De Groote [EMAIL PROTECTED] wrote: Allowing $ as a substitute for self wouldn't require this new syntax. class C: def method($, arg): $.value = arg I'm strongly against this. This looks ugly and reminds me of Perl and Ruby. (I don't have anything against these languages, but there's a reason I use Python). It looks ugly simply because it is new to you. Once you get used to it, I'll bet it will look fine. And resemblance to another language is not a very good reason to reject it. I would not say that ugly and new (or unused for that matter) are the same. There are going to be a number of things in Python 3 that are new and to which one is not used, but they certainly are not ugly. Ugly is of course a matter of taste, I'll give you that, but to me it's still ugly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 7:34 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sat, 06 Dec 2008 07:15:27 -0800, Russ P. wrote: On Dec 6, 4:32 am, Andreas Waldenburger [EMAIL PROTECTED] wrote: On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] wrote: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). If -- and that's a HUGE if -- the compiler is changed to allow $method, it could certainly be changed to allow $.method. Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... If a line of code uses too many instance attributes to fit comfortably on a line, spread it over two lines. There is no newline shortage, they are a renewable resource. But that is not the way Python is meant to work. There are several tennets in the Zen of Python that don't chime well with this approach. self is a speaking identifier, $ isn't. Is @ a speaking identifier? How about # and !=? Last I heard, they were all part of Python. Yes they are. @f is pronounced at f or decorate f. # comment is pronounced hash comment or even not pronounced at all. x != y is pronounced x not equal to y The proposed def $method(arg): would be pronounced def dollar method arg or def method self arg. The first is ugly to my ears, the second confusing. Regarding $ as a stand-in for self is less of a stretch than the examples you gave. -2 on this proposal. Did you get two votes in the Presidential election too? 8^) -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic design patterns
[EMAIL PROTECTED] a écrit : Hallo, users in this forum has been kind enough to point out. Only my implementations are often not that clean, and I may call things something different than the normal convention, which is a source of confusion for myself and others trying to communicate with me. I think, you should start with the classical books of Design Patterns to get a solid understanding and especially vocabulary to communicate with your coworkers. Its easier and better to say, that you will use a strategy pattern than to describe the architecture in many sentences to your partner in a ambigious way. Indeed. But now there's the risk that coworkers implement this as: class AbstractFooStrategy(object): def run(self, yadda): raise NotImplementedError class SimpleFooStrategy(AbstractFooStrategy): def run(self, yadda): # code here class Bar(object): def __init__(self, foo_strategy): if not isinstance(foo_strategy, AbstractFooStrategy): raise ValueError(yadda yadda) self.foo_strategy = foo_strategy def do_this(self, yadda): return self.foo_strategy.run(yadda) b = Bar(SimpleFooStrategy()) instead of: class Bar(object): def __init__(self, foo_strategy): self.foo_strategy = foo_strategy def do_this(self, yadda): return self.foo_strategy(yadda) def baaz(yadda): # code here b = Bar(baaz) Thats in my opinion the first and the key benefit of Design Patterns. Totally agree - at least as long as coworkers clearly understand the difference between design and implementation. Speaking in the same language. The next step should be to apply your knowledge to your programming language. Indeed !-) So I will recommend the classical GOF Books aol / While most implementation example are way over the top in the context of a hi-level dynamic language like Python, the GOF is one of the best book on OO design I've ever read - if not the only that was worth reading (disclaimer : I didn't read much dead-tree stuff on OO). -- http://mail.python.org/mailman/listinfo/python-list
CVS Folders/Contents to Automatic Website - Program suggestions
Hello all, I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public webserver also, I was thinking that I should convert the cvs folders automatically to website. 1) cvs2web is not what i mean. 2) doxygen may not be suitable. I tried with rest2web, it is requires that I write /restweb headers and files to be .txt files. An approach I have thought is: 1) run source-hightlight and create .html pages for all the scripts. 2) now write a script to index those script .htmls and create webpage. 3) Create the website of those pages. before proceeding, I thought I shall discuss here, if the members have any suggestion. What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for notes. Thanks, Senthil -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 automatic decoding of UTF16
[EMAIL PROTECTED] schrieb: 2 problems: endianness and trailing zer byte. This works for me: This is very strange - when using utf16, endianness should be detected automatically. When I simply truncate the trailing zero byte, I receive: Traceback (most recent call last): File ./modify.py, line 12, in module a = AddressBook(2008_11_05_Handy_Backup.txt) File ./modify.py, line 7, in __init__ line = f.readline() File /usr/local/lib/python3.0/io.py, line 1807, in readline while self._read_chunk(): File /usr/local/lib/python3.0/io.py, line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File /usr/local/lib/python3.0/io.py, line 1293, in decode output = self.decoder.decode(input, final=final) File /usr/local/lib/python3.0/codecs.py, line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File /usr/local/lib/python3.0/encodings/utf_16.py, line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data But I suppose something *is* indeed weird because the file I uploaded and which did not yield the truncated data error ia 1559 bytes, which just cannot be. Regards, Johannes -- Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verlästerung von Gott, Bibel und mir und bewusster Blasphemie. -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Running Python 2 and Python 3 on the same machine
On Sat, 2008-12-06 at 10:57 +0100, Martin v. Löwis wrote: Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make altinstll'. It created an executable /usr/local/bin/python3.0 file. Nothing was touched in /usr/bin. Ah, then you missed the fun part. Take a look at the install: target in the Makefile. I need to start writing some code with Python 3. I want to write the code in such a way that it can be easily shared with others with the least difficulty and overhead as possible. How should I write the code to enable this? What, if anything, should I assume about another system's configuration? I don't quite understand the problem. Sharing code is very easy over the internet. You can upload it on PyPI (say), or mail it. So you must be asking for something else. As someone suggested before, naming the files as '.py3' is probably a bad idea in the long run. It also does not really solve the problem. I could use a shebang. But, what should it specify? If I use 'python3.0', then that will soon be quite old. If I make up a link for python3 - python3.0, that would work, but then every other system that is to run the code must that link also. However, I am thinking that this would be the best long term answer. Well, this will be rejected. It might be a good medium-term answer, but it is a *bad* long-term answer. In the long term, Python 2 will disappear, and we are stuck with calling the interpreter python3. If I write scripts for Python 3, another developer writes scripts for Python 2, and a common customer wants to install both of our packages onto a single machine, then what is the best plan for everyone to make that happen with as little difficulty as possible? My recommendation is to use distutils, for a long-term answer. People will run python3.0 setup.py install, and distutils' install_scripts will replace the shebang line with the actual path to Python 3.0. This has not only the advantage of continuing to work for 3.1; it has also the advantage that scripts installed into a private location will be run by the correct interpreter (rather than relying on the interpreter being in /usr/bin, or on PATH). For quick sharing, the shebang line #!/usr/bin/env python3.0 will be enough. When Python 3.1 gets released, you may find yourself writing scripts that run only on Python 3.x for x=1 (i.e. won't run on 3.0, because you use a new feature in 3.1). In that case, presence of a python3 executable won't help, either. Regards, Martin Yes! Finally we are getting somewhere. I can see how this can work for distributed packages. I still have two questions. I do not mean to take your individual time for this. If there is documentation I should read, please suggest it. First, let's say that the package has been installed using distutils and the shebang line is set to '#!/usr/local/bin/python3.0'. Now, Python 3.1 is released with a number of speed performance improvements and several security fixes. The existing application is hardcoded to use Python3.0 directly. Does distutils include any mechanism to update this setting so that the package will use a different interpreter? Must the application be installed again in order to update the shebang lines? Second, we frequently have a number of standalone utilities written in Python. When the task requires excessive effort to write in a shell script, Python is a great answer. What is your recommendation for the shebang line on one-off, single .py file utility scripts? -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Steven D'Aprano: If a line of code uses too many instance attributes to fit comfortably on a line, spread it over two lines. There is no newline shortage, they are a renewable resource. Splitting lines is generally possible, but sometimes it's not I want, for example to keep a formula whole. And splitting lines increases line count. Increasing line count may reduce the amount of code you can see in a screenshot, and this may decrease a little the programmer's ability to understand code. (I am not suggesting to cram everything into one or few lines, like in K language: regarding code size there's an optimal middle point between K/APL and Ada/certain Java. Still, typing self. very often requires time, and even if you are lucky to have an IDE that helps you write that faster, the code uses lot of space anyway). That's why I say that the following code, while looking a little ugly, may be a little better anyway (and maybe even more readable): class ThisIsAClass: def $some_method(arg1, arg2): $value = arg1 + $foo + $bar + $baz * arg2 ... Than the current syntax: class ThisIsAClass: def some_method(self, arg1, arg2): self.value = arg1 + self.foo + self.bar + self.baz * arg2 ... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 automatic decoding of UTF16
John Machin schrieb: On Dec 6, 5:36 am, Johannes Bauer [EMAIL PROTECTED] wrote: So UTF-16 has an explicit EOF marker within the text? I cannot find one in original file, only some kind of starting sequence I suppose (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, simple \r\n line ending. Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes long, an ODD number, which shouldn't happen with utf16. The file is stuffed. Python 3.0 has a bug; it should give a meaningful error message. Yes, you are right. I fixed the file, yet another error pops up (http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.txt.html): Traceback (most recent call last): File ./modify.py, line 12, in module a = AddressBook(2008_12_05_Handy_Backup.txt) File ./modify.py, line 7, in __init__ line = f.readline() File /usr/local/lib/python3.0/io.py, line 1807, in readline while self._read_chunk(): File /usr/local/lib/python3.0/io.py, line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File /usr/local/lib/python3.0/io.py, line 1293, in decode output = self.decoder.decode(input, final=final) File /usr/local/lib/python3.0/codecs.py, line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File /usr/local/lib/python3.0/encodings/utf_16.py, line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data File size is 1630 bytes - so this clearly cannot be. Regards, Johannes -- Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verlästerung von Gott, Bibel und mir und bewusster Blasphemie. -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 automatic decoding of UTF16
Johannes Bauer wrote: [EMAIL PROTECTED] schrieb: 2 problems: endianness and trailing zer byte. This works for me: This is very strange - when using utf16, endianness should be detected automatically. When I simply truncate the trailing zero byte, I receive: Traceback (most recent call last): File ./modify.py, line 12, in module a = AddressBook(2008_11_05_Handy_Backup.txt) File ./modify.py, line 7, in __init__ line = f.readline() File /usr/local/lib/python3.0/io.py, line 1807, in readline while self._read_chunk(): File /usr/local/lib/python3.0/io.py, line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File /usr/local/lib/python3.0/io.py, line 1293, in decode output = self.decoder.decode(input, final=final) File /usr/local/lib/python3.0/codecs.py, line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File /usr/local/lib/python3.0/encodings/utf_16.py, line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data But I suppose something *is* indeed weird because the file I uploaded and which did not yield the truncated data error ia 1559 bytes, which just cannot be. It might be that the EOF marker (b'\x1A' or u'\u001A') was written or is being read as a single byte instead of 2 bytes for UTF-16 text. -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP!...Google SketchUp needs a Python API
[Lie] Sketchup's target users is not power users but those who need quick sketches, so scripting isn't an extremely important feature in Sketchup.[/Lie] Your Wrong, SketchUp PRO is marketed at ACAD users and other high profile CAD and CAM applications. SketchUp models can be exported to ACAD and ACAD models can be imported to SketckUp. Anyone who would say scripting is not important to a modeler has never spent much time modeling. Scripting is of upmost importance to the usefulness of SketchUP(or any CAD/CAM app), without it more advanced modeler types would not be interested. As far as Google earth goes...that is more a marketing ploy, and that Google is a cool company, rather than the primary use for SketchUP...and it has worked well! Your Right, creating a Python extension and getting people interested, is the gateway to convincing SketchUp DEV to include Python alongside Ruby.(and even if they don't it won't matter once the wrapping is there). I hang out a lot in the SketchUp Ruby Group, and a lots of people are turned off by Ruby. I think Python could help them get going. This is the reason for my crusade. Not just for me...but because there is a real void python can fill in SketchUp. Once there is a python wrapping of Ruby API I will take over, writing tutorials, writing example code, fielding Python related questions...This is my commitment to this project. I AM willing to work extremely hard to make this happen. If just ONE other person would get on board this will happen. No...I DO NOT know how to wrap the Ruby API myself...but once the Python wrapping is there i will take over and bring this to life. From that point on, i will not need any help. I will maintain the code, And i will be happy to let this person(s) take ALL the credit for bringing Python to SketchUp...I do not want the credit. -- http://mail.python.org/mailman/listinfo/python-list
Rich Comparisons Gotcha
Dear All, For the first time I have come across a Python feature that seems completely wrong. After the introduction of rich comparisons, equality comparison does not have to return a truth value, and may indeed return nothing at all and throw an error instead. As a result, code like if foo == bar: or foo in alist cannot be relied on to work. This is clearly no accident. According to the documentation all comparison operators are allowed to return non-booleans, or to throw errors. There is explicitly no guarantee that x == x is True. Personally I would like to get these [EMAIL PROTECTED]* misfeatures removed, and constrain the __eq__ function to always return a truth value. That is clearly not likely to happen. Unless I have misunderstood something, could somebody explain to me 1) Why was this introduced? I can understand relaxing the restrictions on '', '=' etc. - after all you cannot define an ordering for all types of object. But surely you can define an equal/unequal classification for all types of object, if you want to? Is it just the numpy people wanting to type 'a == b' instead of 'equals(a,b)', or is there a better reason? 2) If I want to write generic code, can I somehow work around the fact that if foo == bar: or foo in alist does not work for arbitrary objects? Yours, Rasmus Some details: CCPN has a table display class that maintains a list of arbitrary objects, one per line in the table. The table class is completely generic, and subclassed for individual cases. It contains the code: if foo in tbllist: ... else: ... tbllist.append(foo) ... One day the 'if' statement gave this rather obscure error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() A subclass had used objects passed in from some third party code, and as it turned out foo happened to be a tuple containing a tuple containing a numpy array. Some more precise tests gave the following: # Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) # [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 # set up import numpy a = float('NaN') b = float('NaN') ll = [a,b] c = numpy.zeros((2,3)) d = numpy.zeros((2,3)) mm = [c,d] # try NaN print (a == a)# gives False print (a is a)# gives True print (a == b)# gives False print (a is b)# gives False print (a in ll) # gives True print (b in ll) # gives True print (ll.index(a)) # gives 0 print (ll.index(b)) # gives 1 # try numpy array print (c is c) # gives True print (c is d) # gives False print (c in mm) # gives True print (mm.index(c)) # 0 print (c == c) # gives [[ True True True][ True True True]] print (c == d) # gives [[ True True True][ True True True]] print (bool(1 == c)) # raises error - see below print (d in mm) # raises error - see below print (mm.index(d)) # raises error - see below print (c in ll) # raises error - see below print (ll.index(c)) # raises error - see below The error was the same in each case: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() --- Dr. Rasmus H. Fogh Email: [EMAIL PROTECTED] Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get exclusive file lock when safely renaming a file
On Dec 6, 12:25 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: The rename works, but here is my problem: after getting what I thought was an exclusive lock on the new file, but before calling os.rename(), I can still over-write it from another process: $ echo this comes from another process spam.txt $ cat spam.txt this comes from another process What happens if you try to delete spam.txt at this point instead of over-write it? -- http://mail.python.org/mailman/listinfo/python-list
Re: as keyword woes
On Dec 6, 8:16�am, Wolfgang Strobl [EMAIL PROTECTED] wrote: Dennis Lee Bieber [EMAIL PROTECTED]: On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano [EMAIL PROTECTED] declaimed the following in comp.lang.python: On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: The point was that there is that new releases don't _break_ anything. But that's clearly not true, because the OP is pointing out that the new release from 2.5 to 2.6 *does* break his code. � �One now has to ask what break really meant... For this example, the change did not break Python SYNTAX -- just a complaint about using what is now a reserved word as an object name. Of course it does: C:\Python26python Python 2.6 (r26:66721, Oct �2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win 32 Type help, copyright, credits or license for more information. as=2 � File stdin, line 1 � � as=2 � � �^ SyntaxError: invalid syntax I disagree. Broken is something you can't work around. In this case, simply saying as_=2 works fine. A better example of broken was when the gmpy module wouldn't solve a certain linear congruence problem because the problem was not invertible. But mathematically, solving a linear congruence does NOT depend on the problem being invertible. It was the ALGORITHM that depended on the problem being invertible and there was nothing the user could do to make the algorithm behave properly. The algorithm had to be altered to fix the special case of a solvable linear congruence not being invertible. Making a former syntactically valid �two letter name a reserved word in 2.6 was a mistake, IMHO. I think you're in the minority there. What's next? What about making i,j,k, x and y reserved words in 2.7? =:-/ Yeah, right. That'll happen. You ought to be more concerned about real problems. -- Thank you for observing all safety precautions -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Bad idea having two ways to do this. Pick one or the other! -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 3.0 final
On Dec 5, 12:29 pm, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Ben Finney [EMAIL PROTECTED] wrote: I hereby recommend “pish and tosh” for use by anyone who wants to counter someone's point. It beats by a country furlong the invective that has become regrettably common here in recent months. I second the motion to use pish and tosh for a first level of disagreement. I recommend the rather archaic Balderdash as the next step in the escalation of disagreement... As a W.C. Fields fan, I love his non-swearing vocabulary: - Drat - Dag nab it - Holy Mother of Pearl! etc. - hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 2008, at 11:42 AM, [EMAIL PROTECTED] wrote: class ThisIsAClass: def $some_method(arg1, arg2): $value = arg1 + $foo + $bar + $baz * arg2 ... I think my biggest problem with this is what got me off Perl. Add $, together with already used @ and maybe some other identifiers and I start loosing track of what each of the character means. It is fine when you are used to the language, but learning it becomes a harder proposition. self.foo is self-explanatory (no pun intended) to me, $foo is not. Cheers Tommy -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
In article [EMAIL PROTECTED], Bertilo Wennergren [EMAIL PROTECTED] wrote: I don't suppose there is any introductory material out there that is based on Python 3000 and that is also geared at people with a Perl background? Too early for that I guess.. Honestly, the differences between 2.x and 3.0 are small enough that it doesn't much matter, as long as you're not the kind of person who gets put off by little problems. Because so much material is for 2.x, you may be better off just learning 2.x first and then moving to 3.x. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ It is easier to optimize correct code than to correct optimized code. --Bill Harlan -- http://mail.python.org/mailman/listinfo/python-list
operators as variables
Hi, just starting programming and have an elementary question after playing around with lists but cannot find the answer with googling. I have a list of variables and I would like some of those variables to be integers and some to be operators so the list would look something like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get 10). How do you make the interpreter see the operator as that instead of a string and just echo the list back to me. thanks, Andy (and suggestions for a decent Python book would be appreciated) -- http://mail.python.org/mailman/listinfo/python-list
Re: as keyword woes
Mensanator wrote: On Dec 6, 8:16�am, Wolfgang Strobl [EMAIL PROTECTED] wrote: Dennis Lee Bieber [EMAIL PROTECTED]: On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano [EMAIL PROTECTED] declaimed the following in comp.lang.python: On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: The point was that there is that new releases don't _break_ anything. But that's clearly not true, because the OP is pointing out that the new release from 2.5 to 2.6 *does* break his code. � �One now has to ask what break really meant... For this example, the change did not break Python SYNTAX -- just a complaint about using what is now a reserved word as an object name. Of course it does: C:\Python26python Python 2.6 (r26:66721, Oct �2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win 32 Type help, copyright, credits or license for more information. as=2 � File stdin, line 1 � � as=2 � � �^ SyntaxError: invalid syntax I disagree. Broken is something you can't work around. In this case, simply saying as_=2 works fine. A better example of broken was when the gmpy module wouldn't solve a certain linear congruence problem because the problem was not invertible. But mathematically, solving a linear congruence does NOT depend on the problem being invertible. It was the ALGORITHM that depended on the problem being invertible and there was nothing the user could do to make the algorithm behave properly. The algorithm had to be altered to fix the special case of a solvable linear congruence not being invertible. Making a former syntactically valid �two letter name a reserved word in 2.6 was a mistake, IMHO. I think you're in the minority there. I think that its special use is clear from the syntax, so IMHO it could've been left for Python 3, but I'm not going to lose any sleep over it. What's next? What about making i,j,k, x and y reserved words in 2.7? =:-/ Yeah, right. That'll happen. You ought to be more concerned about real problems. -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 3.0 final
Mensanator wrote: On Dec 5, 12:29 pm, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Ben Finney [EMAIL PROTECTED] wrote: I hereby recommend “pish and tosh” for use by anyone who wants to counter someone's point. It beats by a country furlong the invective that has become regrettably common here in recent months. I second the motion to use pish and tosh for a first level of disagreement. I recommend the rather archaic Balderdash as the next step in the escalation of disagreement... As a W.C. Fields fan, I love his non-swearing vocabulary: - Drat - Dag nab it - Holy Mother of Pearl! etc. Holy Zarquon's Singing Fish! (Hitch-hiker's Guide to the Galaxy) But don't say B*m. :-) http://www.bbc.co.uk/cult/hitchhikers/guide/belgium.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Daniel Fetchinson wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? What's the advantage? If there is not a good reason, I would strongly opposed polluting the language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Daniel Fetchinson wrote: The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value Hmm, I'd give the proposal a -1. Perhaps I'm missing something though. Does this really justify an enhancement? Whether the implicit parameter is prepended with a dot or whether it's the first parameter with the parantheses doesn't save me any typing and the benefit of 'visualizing' how the function should be called seems minor to me. What would be interesting would be some syntactical sugar to get rid of the 'self' (at least in the code body). example: class C: class_elements a,b,c,d def method(self,arg): global d a,b,c = arg[0..3] d = a + b self.e = a + d instead of class C: def method(self,arg): self.a,self.b,self.c,self.d = arg[0..4] self.e = self.a + self.b As far as I understood (I never really followed any of these threads), getting rid of self has already been discussed and rejected many times. bye N -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
Neal Becker wrote: Daniel Fetchinson wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? What's the advantage? If there is not a good reason, I would strongly opposed polluting the language. I wouldn't want to see $ for self. and ¢ (cent) for cls. either... -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
I fully agree with Roy's answer. COding small tasks is a good starting point. For quite some time you'll be of course less efficient than with your previous language, but that's part of the learning curve, isn't it. I guess you'll learn the syntax rather quickly. What's more painful is to learn which functianilty is in which library and which library exists. There's of course a lot of online documentation, but often you find answers to trivial python questions fastest with Google: for example: search for something like python string reverse example And there's of course this newsgroup whenever you're stuck with a 'missing' feature, (though mostly the features aren't missing, but just a little different) bye N Roy Smith wrote: In article [EMAIL PROTECTED], Bertilo Wennergren [EMAIL PROTECTED] wrote: I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, . . . I assume you use Perl to solve real problems in whatever job you do. My recommendation would be the next time some problem comes up that you would normally solve with Perl, try doing it in Python. Having a real task that you need to accomplish is a great way to focus the mind. For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. One of the very first things you'll probably discover that's different between Perl and Python is how they handle string pattern matching. In Perl, it's a built in part of the language syntax. In Python, you use the re module. The regular expressions themselves are the same, but the mechanism you use to apply them to input text is quite different. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
In article [EMAIL PROTECTED], [EMAIL PROTECTED] (Aahz) wrote: In article [EMAIL PROTECTED], Bertilo Wennergren [EMAIL PROTECTED] wrote: I don't suppose there is any introductory material out there that is based on Python 3000 and that is also geared at people with a Perl background? Too early for that I guess.. Honestly, the differences between 2.x and 3.0 are small enough that it doesn't much matter, as long as you're not the kind of person who gets put off by little problems. Because so much material is for 2.x, you may be better off just learning 2.x first and then moving to 3.x. I'm not sure I agree. If you're starting out, you might as well learn the new stuff. Then there's no need to unlearn the old way. Using material meant for 2.x is likely to lead to confusion. If you don't know either, you'll never know if something isn't working as described because you're doing it wrong or if it's just not the same as it used to be. When everything is new, what seem like little stumbling blocks to experts become total blockers to people starting from zero. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python calling COM compliant .dll
En Wed, 03 Dec 2008 16:20:27 -0200, David Shi [EMAIL PROTECTED] escribió: I am looking for a concise working example of Python script calling COM compliant .dll. The best source of information is Mark Hammond's book Python Programming in Win32. The sample chapters available are about using COM objects, AFAIR. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: operators as variables
macc_200 wrote: Hi, just starting programming and have an elementary question after playing around with lists but cannot find the answer with googling. I have a list of variables and I would like some of those variables to be integers and some to be operators so the list would look something like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get 10). How do you make the interpreter see the operator as that instead of a string and just echo the list back to me. I am not sure what you actually want to do, but the following may help: 1. Strings can be evaluated. 2. Operators are syntax sugar for functions. The functions are available in the operator module. IDLE 3.0 eval('5 * 4 - 4 + 6') 22 import operator as op op.add(2,3) 5 tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
News123 wrote: What's more painful is to learn which functianilty is in which library and which library exists. cut Yes and one mistake I still often find myself doing is, when confronted with a particular problem, that I write some helper code to deal with it. Of course later on I discover that there is a standard module or built-in that does exactly what I want and better. :-) Somehow in the heat of the moment my mind is not thinking 'there must be something out there which does what I want' but rather 'hmmm I think I can do it this way, clicker-di-click'. In my opinion it is a positive attribute to the language that it makes solving problems so easy that you forget about searching for solutions. Maybe python should prompt every 10 lines of code a message saying 'Are you sure this can not be done with a built-in?' Most of the time it will be right anyway :-) -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
In article [EMAIL PROTECTED], Steven D'Aprano [EMAIL PROTECTED] wrote: On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. Is there anything which *can't* be written in under 50 lines of Perl? [...] Also, Perl REs are faster than Python REs, or so I'm told. Between the speed and the convenience, Perl programmers tend to use RE's for everything they can. Python programmers tend to use REs only for problems that *should* be solved with REs rather than *can* be solved with a RE. Well, as an old-time unix hacker (who learned REs long before Perl existed), my question to you would be, Is there any problem which *shouldn't* be solved with an RE? :-) It's easy to go nuts with REs, and create write-only code. On the other hand, they are an extremely powerful tool. If you are wise in the ways of RE-fu, they can not only be the most compact way to write something, but also the most efficient and even the most comprehensible. Unfortunately, REs seem to be regarded as some kind of monster these days and few people take the time to master them fully. Which is a shame. One really nice feature of REs in Python is the VERBOSE flag. It lets you write some way-complicated REs in a way which is still easy for somebody to read and understand. Python's raw strings, and triple-quoted strings, also help reduce the sea of backslashes which often make REs seem much worse than they really are. One of the reasons REs don't get used in Python as much as in Perl is because strings have useful methods like startswith(), endswith(), and split(), and also the in operator. These combine to give you easy ways to do many things you might otherwise do with REs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 automatic decoding of UTF16
Johannes Bauer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] John Machin schrieb: On Dec 6, 5:36 am, Johannes Bauer [EMAIL PROTECTED] wrote: So UTF-16 has an explicit EOF marker within the text? I cannot find one in original file, only some kind of starting sequence I suppose (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, simple \r\n line ending. Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes long, an ODD number, which shouldn't happen with utf16. The file is stuffed. Python 3.0 has a bug; it should give a meaningful error message. Yes, you are right. I fixed the file, yet another error pops up (http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.txt.html): Traceback (most recent call last): File ./modify.py, line 12, in module a = AddressBook(2008_12_05_Handy_Backup.txt) File ./modify.py, line 7, in __init__ line = f.readline() File /usr/local/lib/python3.0/io.py, line 1807, in readline while self._read_chunk(): File /usr/local/lib/python3.0/io.py, line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File /usr/local/lib/python3.0/io.py, line 1293, in decode output = self.decoder.decode(input, final=final) File /usr/local/lib/python3.0/codecs.py, line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File /usr/local/lib/python3.0/encodings/utf_16.py, line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data File size is 1630 bytes - so this clearly cannot be. How about posting your code? The first file is incorrect. It contains an extra 0x00 byte at the end of the file, but is otherwise correctly encoded with a big-endian UTF16 BOM and data. The second file is a correct UTF16-BE file as well. This code (Python 2.6) decodes the first file, removing the trailing extra byte: raw = open('2008_11_05_Handy_Backup.txt').read() data = raw[:-1].decode('utf16') and this code (Python 2.6) decodes the second: raw = open('2008_12_05_Handy_Backup.txt').read() data = raw.decode('utf16') Python 3.0 also has no problems with decoding or accurate error messages: data = open('2008_12_05_Handy_Backup.txt',encoding='utf16').read() data = open('2008_11_05_Handy_Backup.txt',encoding='utf16').read() Traceback (most recent call last): File stdin, line 1, in module File C:\dev\python30\lib\io.py, line 1724, in read decoder.decode(self.buffer.read(), final=True)) File C:\dev\python30\lib\io.py, line 1295, in decode output = self.decoder.decode(input, final=final) File C:\dev\python30\lib\codecs.py, line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File c:\dev\python30\lib\encodings\utf_16.py, line 61, in _buffer_decode codecs.utf_16_ex_decode(input, errors, 0, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x00 in position 1558: trunc ated data -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Profiling Python
[EMAIL PROTECTED] writes on Wed, 3 Dec 2008 07:13:14 -0800 (PST): To clarify again, Is there some function like profile.PrintStats() which dynamically shows the stats before stopping the Profiler? Try to (deep) copy the profiler instance and than call PrintStats() on the copy. Of course, you will then profile also the PrintStats in the running profiler. Dieter -- http://mail.python.org/mailman/listinfo/python-list
Re: as keyword woes
Date: Fri, 05 Dec 2008 22:22:38 -0800 From: Dennis Lee Bieber [EMAIL PROTECTED] Subject: Re: as keyword woes To: python-list@python.org Message-ID: [EMAIL PROTECTED] I'm still in the dark as to what type of data could even inspire the use of as as an object name... A collection of a objects? In which case, what are the as? G Please let me clarify. It is not as as a standalone object that we specifically miss in 2.6/3, but rather, the ability to use .as used as a method or attribute name. In other words we have lost the ability to refer to as as the generalized OOP-compliant/syntax-independent method name for casting: new_object = old_object.as(class_hint) # For example: float_obj = int_obj.as(float) # or float_obj = int_obj.as(float_class) # as opposed to something like float_obj = int_obj.asFloat() # which requires a separate method for each cast, or float_obj = (float)int_obj # which required syntax-dependent casting [language-based rather than object-based]. Of course, use of explicit casting syntax (float) is fine if you're restricting yourself to Python and other languages which support casting, but that solution is unavailable inside of a pure OOP message-passing paradigm where object.method(argument) invocations are all you have to work with. Please note that use of object.asClassname(...) is a ubiqitous convention for casting objects to specific classes (seen in ObjectiveC, Java, SmallTalk, etc.). There, I assert that 'object.as(class_reference)' is the simplest and most elegant generalization of this widely-used convention. Indeed, it is the only obvious concise answer, if you are limited to using methods for casting. Although there are other valid domain-specific uses for as as either a local variable or attribute names (e.g. systematic naming: as, bs, cs), those aren't nearly as important compared to as being available as the name of a generalized casting method -- one that is now strictly denied to users of Python 2.6 and 3. As someone somewhat knowledgable of how parsers work, I do not understand why a method/attribute name object_name.as(...) must necessarily conflict with a standalone keyword as . It seems to me that it should be possible to unambiguously separate the two without ambiguity or undue complication of the parser. So, assuming I now wish to propose a corrective PEP to remedy this situation for Python 3.1 and beyond, what is the best way to get started on such a proposal? Cheers, Warren -- http://mail.python.org/mailman/listinfo/python-list
Re: python book for non technical absolute beginner
2008/12/6 News123 [EMAIL PROTECTED]: No my question does anybody know a nice beginners book (or a learning CD or on line tutorial)? Ideally it shouldn't be too serious and have a lot of small nice mini-examples How to Think Like a Computer Scientist - Learning with Python is a good book for beginners and it is available for free under the GNU license. http://www.greenteapress.com/thinkpython/thinkCSpy/ Cheers, .peke -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
Rasmus Fogh wrote: Dear All, For the first time I have come across a Python feature that seems completely wrong. After the introduction of rich comparisons, equality comparison does not have to return a truth value, and may indeed return nothing at all and throw an error instead. As a result, code like if foo == bar: or foo in alist cannot be relied on to work. This is clearly no accident. According to the documentation all comparison operators are allowed to return non-booleans, or to throw errors. There is explicitly no guarantee that x == x is True. You have touched on a real and known issue that accompanies dynamic typing and the design of Python. *Every* Python function can return any Python object and may raise any exception either actively, by design, or passively, by not catching exceptions raised in the functions *it* calls. Personally I would like to get these [EMAIL PROTECTED]* misfeatures removed, What you are calling a misfeature is an absence, not a presence that can be removed. and constrain the __eq__ function to always return a truth value. It is impossible to do that with certainty by any mechanical creation-time checking. So the implementation of operator.eq would have to check the return value of the ob.__eq__ function it calls *every time*. That would slow down the speed of the 99.xx% of cases where the check is not needed and would still not prevent exceptions. And if the return value was bad, all operator.eq could do is raise and exception anyway. That is clearly not likely to happen. Unless I have misunderstood something, could somebody explain to me. a. See above. b. Python programmers are allowed to define 'weird' but possibly useful-in-context behaviors, such as try out 3-value logic, or to operate on collections element by element (as with numpy). 1) Why was this introduced? The 6 comparisons were previously done with one __cmp__ function that was supposed to return -1, 0, or 1 and which worked with negative, 0, or positive response, but which could return anything or raise an exception. The compare functions could mask but not prevent weird returns. I can understand relaxing the restrictions on '', '=' etc. - after all you cannot define an ordering for all types of object. But surely you can define an equal/unequal classification for all types of object, if you want to? Is it just the numpy people wanting to type 'a == b' instead of 'equals(a,b)', or is there a better reason? 2) If I want to write generic code, can I somehow work around the fact that if foo == bar: or foo in alist does not work for arbitrary objects? Every Python function is 'generic' unless restrained by type tests. However, even 'generic' functions can only work as expected with objects that meet the assumptions embodied in the function. In my Python-based algorithm book-in-progess, I am stating this explicitly. In particular, I say taht the book only applies to objects for which '==' gives a boolean result that is reflexive, symmetric, and transitive. This exludes float('nan'), for instance (as I see you discovered), which follows the IEEE mandate to act otherwise. CCPN has a table display class that maintains a list of arbitrary objects, one per line in the table. The table class is completely generic, but only for the objects that meet the implied assumption. This is true for *all* Python code. If you want to apply the function to other objects, you must either adapt the function or adapt or wrap the objects to give them an interface that does meet the assumptions. and subclassed for individual cases. It contains the code: if foo in tbllist: ... else: ... tbllist.append(foo) ... One day the 'if' statement gave this rather obscure error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() A subclass had used objects passed in from some third party code, and as it turned out foo happened to be a tuple containing a tuple containing a numpy array. Right. 'in' calls '==' and assumes a boolean return. Assumption violated, exception raised. Completely normal. The error message even suggests a solution: wrap the offending objects in an adaptor class that gives them a normal interface with .all (or perhaps the all() builtin). Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Detaching e-mail attachments?
Ken D'Ambrosio wrote: Hi, all. I've done some poking around, and can find roughly two million different ways to attach attachments to an e-mail... but darn few to detach them. Any suggestions? I'm assuming I'm just missing looking in The Right Place, but thus-far, my Googling has been for naught. Try the email package doc in the Lib Manual. -- http://mail.python.org/mailman/listinfo/python-list
Re: as keyword woes
In my opinion, this thread is a crock of balony. Python *occasionally* adds keywords after giving a warning or requiring a future import in previous versions. In 2.2, one had to 'from __future__ import generators' to make a generator because doing so required the new 'yield' keyword. In 2.3, yield became a keyword without the import. In 2.5, one had to 'from __future__ import with_statement' to make a 'with' statement. In 2.6, with because a keyword without the import. And no one seems to have noticed. No 'with keyword woes. In 2.6, 'as' also because a full-time keyword after several releases of being an anomalous part-time contextual keyword. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: as keyword woes
On Dec 6, 1:38 pm, Warren DeLano [EMAIL PROTECTED] wrote: There, I assert that 'object.as(class_reference)' is the simplest and most elegant generalization of this widely-used convention. Indeed, it is the only obvious concise answer, if you are limited to using methods for casting. I don't agree with your assertion. object.as_type(class_reference) object.cast(class_reference) These are both concise and obvious. As someone somewhat knowledgable of how parsers work, I do not understand why a method/attribute name object_name.as(...) must necessarily conflict with a standalone keyword as . It seems to me that it should be possible to unambiguously separate the two without ambiguity or undue complication of the parser. It's possible, and they've been doing it for years, and they could have continued doing it if they wanted to. You'll notice that nowhere the Python grammar can two identifiers be separated by whitespace. So if you have two identifiers separated by whitespace, and the second one is as, you know it has to be keyword as. Well, they made it a keyword anyway. It was never a question of whether they could do it. So, assuming I now wish to propose a corrective PEP to remedy this situation for Python 3.1 and beyond, what is the best way to get started on such a proposal? I think you'd be wasting your time, but the general procedure is outlined in PEP 1. Basically, you write a pre-PEP (aka PEP XXX) according to the guidelines in PEP 1, which you would post here and request comments on it. Then, if you can muster some support for it, you would send it to PEP maintainer (the email is listed somewhere on the PEPs page, dig for it), and get a number assigned, upon which time Guido van Rossum will read it and any comments in python-dev, and make a pronouncement of some sort. If you write a PEP, I advise you to try to sound less whiny and than you have in this thread. Saying object.as(class_reference) is highly convenient because it mirrors textually the Java convention of object.asFloat will go over a lot better than object.as (class_reference) is the only obvious concise answer. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: as keyword woes
On Dec 7, 2:38 am, Warren DeLano [EMAIL PROTECTED] wrote: Date: Fri, 05 Dec 2008 22:22:38 -0800 From: Dennis Lee Bieber [EMAIL PROTECTED] Subject: Re: as keyword woes To: [EMAIL PROTECTED] Message-ID: [EMAIL PROTECTED] I'm still in the dark as to what type of data could even inspire the use of as as an object name... A collection of a objects? In which case, what are the as? G Please let me clarify. It is not as as a standalone object that we specifically miss in 2.6/3, but rather, the ability to use .as used as a method or attribute name. In other words we have lost the ability to refer to as as the generalized OOP-compliant/syntax-independent method name for casting: new_object = old_object.as(class_hint) # For example: float_obj = int_obj.as(float) # or float_obj = int_obj.as(float_class) # as opposed to something like float_obj = int_obj.asFloat() # which requires a separate method for each cast, or float_obj = (float)int_obj # which required syntax-dependent casting [language-based rather than object-based]. Of course, use of explicit casting syntax (float) is fine if you're restricting yourself to Python and other languages which support casting, but that solution is unavailable inside of a pure OOP message-passing paradigm where object.method(argument) invocations are all you have to work with. Please note that use of object.asClassname(...) is a ubiqitous convention for casting objects to specific classes (seen in ObjectiveC, Java, SmallTalk, etc.). There, I assert that 'object.as(class_reference)' is the simplest and most elegant generalization of this widely-used convention. Indeed, it is the only obvious concise answer, if you are limited to using methods for casting. Although there are other valid domain-specific uses for as as either a local variable or attribute names (e.g. systematic naming: as, bs, cs), those aren't nearly as important compared to as being available as the name of a generalized casting method -- one that is now strictly denied to users of Python 2.6 and 3. As someone somewhat knowledgable of how parsers work, I do not understand why a method/attribute name object_name.as(...) must necessarily conflict with a standalone keyword as . It seems to me that it should be possible to unambiguously separate the two without ambiguity or undue complication of the parser. So, assuming I now wish to propose a corrective PEP to remedy this situation for Python 3.1 and beyond, what is the best way to get started on such a proposal? Cheers, Warren And let things like: filelike.print('lpt') # python 2.6 zipper.with('7z') failure.try(alternative) executecodeobject.if(True) onfailure.break() ? -- http://mail.python.org/mailman/listinfo/python-list
Re: python book for non technical absolute beginner
News123 wrote: One of my 'non technical' friends complained about knowing nothing at all about programming (though using computers regularly for mails / web browsing / googling and downloading / cropping photos ) He wants to play a little with programming to stimulate parts of his otehrwise idle brain cells. ;-) Normally it's more the social science / linguistic parts being exercised, I thought python might be a nice language for this No my question does anybody know a nice beginners book (or a learning CD or on line tutorial)? Ideally it shouldn't be too serious and have a lot of small nice mini-examples thanks in advance for any suggestions hints I started with the 1.3 version of http://docs.python.org/tutorial/index.html (but had lots of previous experience). -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] as keyword woes
On Sat, Dec 6, 2008 at 11:38 AM, Warren DeLano [EMAIL PROTECTED] wrote: [...] There, I assert that 'object.as(class_reference)' is the simplest and most elegant generalization of this widely-used convention. Indeed, it is the only obvious concise answer, if you are limited to using methods for casting. Well, that's too bad, as 'as' is now a reserved word. Although there are other valid domain-specific uses for as as either a local variable or attribute names (e.g. systematic naming: as, bs, cs), those aren't nearly as important compared to as being available as the name of a generalized casting method -- one that is now strictly denied to users of Python 2.6 and 3. If you had brought this up 5-10 years ago when we first introduced 'as' as a semi-keyword (in the import statement) we might have been able to avert this disaster. As it was, nobody ever brought this up AFICR, so I don't think it's *that* obvious. As someone somewhat knowledgable of how parsers work, I do not understand why a method/attribute name object_name.as(...) must necessarily conflict with a standalone keyword as . It seems to me that it should be possible to unambiguously separate the two without ambiguity or undue complication of the parser. That's possible with sufficiently powerful parser technology, but that's not how the Python parser (and most parsers, in my experience) treat reserved words. Reserved words are reserved in all contexts, regardless of whether ambiguity could arise. Otherwise *every* reserved word would have to be allowed right after a '.', and many keywords would have to be allowed as identifiers in other contexts. That way lies PL/1... Furthermore, how would you define the 'as' method? Would you also want to be allowed to write def as(self, target): ... ??? Trust me, it's a slippery slope, and you don't want to start going down there. So, assuming I now wish to propose a corrective PEP to remedy this situation for Python 3.1 and beyond, what is the best way to get started on such a proposal? Don't bother writing a PEP to make 'as' available as an attribute again. It has no chance of being accepted. Instead, think of a different word you could use. -- --Guido van Rossum (home page: http://www.python.org/~guido/) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
On Dec 6, 5:00 am, Bertilo Wennergren [EMAIL PROTECTED] wrote: I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, but I now Perl pretty well. I'm also well experienced with JavaScript. Any pointers and tips how I should go about getting into Python? -- Bertilo Wennergren http://bertilow.com There's a lot of hoopla about Py3k being different, incompatible with Py2.x. However, you have to keep in mind that this matters most of all to old, large programs, which will need to be changed if one would like to run them on Py3k. For learning the differences don't matter much. If you learn to code in py2.x for half a year, you will be able to pick up on most of the differences and transfer to py3k in a few days. If you find good docs on py2.x go ahead and use them and don't worry. -- http://mail.python.org/mailman/listinfo/python-list
Select, interrupted system call, log rotation?
I got an interrupted system call exception in select and I don't know what could have caused it. Here's the error: select.select(inputs, [], [], 9) error: (4, 'Interrupted system call') Caught an exception, shutting down... It's py2.3, on mach architecture. I'm trying to figure out what caused it, and the only idea I have so far is that it could be that I have python's logging system log rotation thing running and I think I've seen a reference somewhere that it uses SIGALRM when log file reaches set size to stop and switch the files. The program was running for about a week without any problem and then I got this exception and after I restarted it it's been running for a few days and I only got the exception once in all that time. Am I going in a completely wrong direction here? I'm thinking of just putting select in try: except: , is that a good idea here? I don't understand signals all that well. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python now coming from Perl
On Dec 6, 12:30 pm, Roy Smith [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] (Aahz) wrote: In article [EMAIL PROTECTED], Bertilo Wennergren [EMAIL PROTECTED] wrote: I don't suppose there is any introductory material out there that is based on Python 3000 and that is also geared at people with a Perl background? Too early for that I guess.. Honestly, the differences between 2.x and 3.0 are small enough that it doesn't much matter, as long as you're not the kind of person who gets put off by little problems. Because so much material is for 2.x, you may be better off just learning 2.x first and then moving to 3.x. I'm not sure I agree. If you're starting out, you might as well learn the new stuff. Then there's no need to unlearn the old way. One disadvantage of learning Python 3 first is the availability of third-party libraries (especially extension libraries), most of which will not be updated for Python 3.x for quite a while. Also, I don't think it's really advisable to be completely ignorant of the 2.x difference even if one intends to start with 3.0. There is a lot of code and material out there for 2.x, and until these start to be widely available for 3.x, people will sometimes have to make do with the 2.x stuff. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: slow Python 3.0 write performance?
Christian Heimes wrote: Istvan Albert wrote: A previous poster suggested that in this case the slowdown is caused by the new io code being written in python rather than C. For text mode Python 3's write() method is slower than Python 2.x's method because all text is encoded. The slowdown is mostly caused by additional code for line ending detection and decoding/encoding. The new io library does more than the old file object So far the new io library hasn't been optimized yet, too. Please give it some time and report speed issues at http://bugs.python.org/. On WinXP, tests 3 times each --- 3.0 --- import time line = 'a'*99 + '\n' text = line*50 start=time.time() open('wtest', 'w').write(text) print(time.time()-start) # 3.4 to 4.0 import time line = 'a'*99 + '\n' text = line*50 start=time.time() text = bytes(line,'ascii')*50 print(time.time()-start) # 1.1 to 1.25 start=time.time() open('wtest', 'wb').write(text) # note wb print(time.time()-start) # 1.5 to 1.8 -- 2.5 --- import time line = 'a'*99 + '\n' text = line*50 start=time.time() open('wtest', 'w').write(text) print(time.time()-start) # 3.3 to 4.1 import time line = 'a'*99 + '\n' text = line*50 start=time.time() open('wtest', 'wb').write(text) # note wb print(time.time()-start) # 1.0 to 1.6 - Conclusion: 1. on WinXP, writing with 3.0 has no slowdown versus 2.5 2. on WinXP, binary mode writing is about 3 times faster that text mode writing with its line-ending expansion. If that is not needed, binary mode and explicit bytes-text conversion is about twice as fast. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 12:47 am, Patrick Mullen [EMAIL PROTECTED] wrote: Could I do something like this: def a.add(b): return a+b Outside of a class? Of course then that makes you think you could do 5.add(6) or something crzy like that. (I mean, you can do (5).__add__(6) but that's something else entirely) I'd be inclined to think that this defines an instancemethod on an existing object a. In other word, I'd read the following two lines as more or less equivalent. def a.add(b): return a+b a.add = lambda b: a+b Just as the following are equivalent: def foo(): return bar foo = lambda: bar I had been -0 on this, but now I think I'm -1. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 9:15 am, Russ P. [EMAIL PROTECTED] wrote: On Dec 6, 4:32 am, Andreas Waldenburger [EMAIL PROTECTED] wrote: On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] wrote: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... But that is not the way Python is meant to work. There are several tennets in the Zen of Python that don't chime well with this approach. self is a speaking identifier, $ isn't. Is @ a speaking identifier? How about # and !=? Last I heard, they were all part of Python. None of them are identifiers. $, used as proposed, would be. (Then again, _ is an identifier.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
first time in the internet history a huge collection of funny pictures and videos over 10000 funny pics and videos download free on mobile format www.funreality.com
first time in the internet history a huge collection of funny pictures and videos over 1 funny pics and videos download free on mobile format www.funreality.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 9:12 am, Russ P. [EMAIL PROTECTED] wrote: On Dec 6, 1:02 am, Antoine De Groote [EMAIL PROTECTED] wrote: Allowing $ as a substitute for self wouldn't require this new syntax. class C: def method($, arg): $.value = arg I'm strongly against this. This looks ugly and reminds me of Perl and Ruby. (I don't have anything against these languages, but there's a reason I use Python). Russ P. wrote: On Dec 5, 6:21 pm, Daniel Fetchinson [EMAIL PROTECTED] wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort. shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- Psss, psss, put it down! -http://www.cafepress.com/putitdown I like it. I'll even go a step further and suggest that $ be allowed as a substitute for self. It looks like a capital S (for Self), and it stands out clearly. It also makes code more succinct with no loss of readability. Think of the line wraps that could be avoided. It looks ugly simply because it is new to you. Once you get used to it, I'll bet it will look fine. And resemblance to another language is not a very good reason to reject it. Perl is not new to me and I am familiar with the syntax, such as it is. I find it unspeakably ugly. So, no, you would lose your bet if it were me. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 5, 8:21 pm, Daniel Fetchinson [EMAIL PROTECTED] wrote: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value -1 I explained why deep in the thread but I'll elaborate more here. When I see a def statement, I mentally equate that to an assigment to the thing being def'ed. So for instance, when I see this: def something(): I think of it like this: somthing = the defined function Thus, if I were to see a function definition like this def foo.bar(): return 1 I would think you were defining a function and assigning it to foo.bar. IOW, it would be mostly equivalent to this: foo.bar = lambda: 1 (Analogously, I would expect a definition like this: def baz[10](): return 1 to be equivalent to this: baz[10] = lambda: 1 ) So, if, inside a class definition, I were to see this: def self.method(): return 1 Well, I'd understand that is was a method assigment, of course, but it would conflict with what I would expect the natural meaning of something like def a.b() would be. The above statement is not equivalent to: self.method = lambda: 1 but I think that's what it ought to be, in general. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get exclusive file lock when safely renaming a file
Steven D'Aprano wrote: I'm trying to safely rename a file without over-writing any existing files, and I've run into a problem with file locks. Here's a naive way of renaming without over-writing By default on a Linux filesystem, flock() gives you an _advisory_ lock. Other processes can touch the file unless they explicitly check the lock. Try man mount (see under the -o mand) and man fcntl (see under file locking) Jeffrey Straszheim -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 automatic decoding of UTF16
On Dec 7, 6:20 am, Mark Tolonen [EMAIL PROTECTED] wrote: Johannes Bauer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] John Machin schrieb: On Dec 6, 5:36 am, Johannes Bauer [EMAIL PROTECTED] wrote: So UTF-16 has an explicit EOF marker within the text? I cannot find one in original file, only some kind of starting sequence I suppose (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, simple \r\n line ending. Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes long, an ODD number, which shouldn't happen with utf16. The file is stuffed. Python 3.0 has a bug; it should give a meaningful error message. Yes, you are right. I fixed the file, yet another error pops up (http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.t... Traceback (most recent call last): File ./modify.py, line 12, in module a = AddressBook(2008_12_05_Handy_Backup.txt) File ./modify.py, line 7, in __init__ line = f.readline() File /usr/local/lib/python3.0/io.py, line 1807, in readline while self._read_chunk(): File /usr/local/lib/python3.0/io.py, line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File /usr/local/lib/python3.0/io.py, line 1293, in decode output = self.decoder.decode(input, final=final) File /usr/local/lib/python3.0/codecs.py, line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File /usr/local/lib/python3.0/encodings/utf_16.py, line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data File size is 1630 bytes - so this clearly cannot be. How about posting your code? He did. Ugly stuff using readline() :-) Should still work, though. There are definite problems with readline() and readlines(), including: First file: silently ignores error *and* the last line returned is garbage [consists of multiple actual lines, and the trailing codepoints have been byte-swapped] Second file: as he has just reported. I've reproduced it with f.open ('second_file.txt', encoding='utf16') followed by each of: (1) f.readlines() (2) list(f) (3) for line in f: print(repr(line)) With the last one, the error happens after printing the last actual line in his file. -- http://mail.python.org/mailman/listinfo/python-list