ANN: CherryPy 3.1.0 beta3 Released
Announcing CherryPy 3.1.0 beta3. The first beta was released about 3 months ago. There was a beta2 release that went largely unannounced in between. Here is a list of some of the changes from beta1 to beta3. Bugfixes: * log.screen now sends error messages to stderr (http://www.cherrypy.org/ticket/747) * Logging thread-safety issue (http://www.cherrypy.org/ticket/751) * Exception when parsing Content-Type (http://www.cherrypy.org/ticket/763) * Session Tool cleanup frequency was too high (http://www.cherrypy.org/ticket/760) * Session identifier security fix (http://www.cherrypy.org/ticket/709) * cherrypy.checker false alarm (http://www.cherrypy.org/ticket/754) * Problem running behind mod_python (http://www.cherrypy.org/ticket/766) Changes: * Returned to a single-server model (http://www.cherrypy.org/ticket/752) * Bug/plugin improvements * Removed engine from restsrv Full details here: http://www.cherrypy.org/log/trunk?action=stop_on_copyrev=1861stop_rev=1810mode=stop_on_copy Get the beta release at the following link or via easy_install (easy_install CherryPy==3.1.0beta3): http://www.cherrypy.org/wiki/CherryPyDownload Instructions for upgrading from 3.0.x are here: http://www.cherrypy.org/wiki/UpgradeTo31 General information on new stuff in 3.1: http://www.cherrypy.org/wiki/WhatsNewIn31 Thanks to everyone who contributed bug reports and code for this release. Christian Wyglendowski CherryPy Team -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: CherryPy 3.0.3 Released
Announcing CherryPy 3.0.3. This release fixes two important bugs. 1) Security vulnerability when using file-based sessions (http://www.cherrypy.org/ticket/744). 2) A memory leak (http://www.cherrypy.org/ticket/718). A full log of the changes since 3.0.2 can be found here: http://www.cherrypy.org/log/branches/cherrypy-3.0.x?action=stop_on_copyrev=1845stop_rev=1702mode=stop_on_copy Get the release at the following link or via easy_install (easy_install CherryPy==3.0.3): http://www.cherrypy.org/wiki/CherryPyDownload Instructions for upgrading from 2.x are here: http://www.cherrypy.org/wiki/UpgradeTo30 General information on new stuff in 3.0.x: http://www.cherrypy.org/wiki/WhatsNewIn30 Thanks to everyone who contributed bug reports and code for this release. Christian Wyglendowski CherryPy Team -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: super, decorators and gettattribute
On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: However, I am very surprised to learn that super_object.__getattr__(name)(*args, **kwargs) getattr(super_object, name)(*args, **kwargs) are not equivalent. This is quite odd, at least when with len() and .__len__, str() and .__str__. Do you maybe know what's the rationale behind not following that convention by getattr? I think you are confusing `__getattr__` and `__getattribute__` here! `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's different. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Please keep discussion on the list.. I'm not sure if I understand your question correctly but maybe this will help: If you want code to be run upon creating an instance of your class you would use __init__. Most common examples include setting attributes on the instance and doing some checks, e.g. class Person: def __init__( self, first, last ): if len( first ) 50 or len( last ) 50: raise Exception( 'The names are too long.' ) self.first = first self.last = last And you would use your class like so, p1 = Person( 'John', 'Smith' ) p2 = Person( Some long fake name that you don't really want to except, I don't know if it's really longer than 50 but let's assume it is, Smith ) # This last one would raise an exception so you know that something is not okay HTH, Daniel Is not the code run when I create an instance by assignement somewhere else? I take the point that one might want to check for potential exceptions immediately, but most examples in the literature aren't doing that and don't seem to be doing anything that would not be done when creating an instance by assignment later somewhere. I'm missing something basic here. What do you mean by create an instance by asignment somewhere else? -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
It seems to me that filenames are like snapshots of the locales where they originated. On Unix, yes. On Windows, NTFS and VFAT represent file names as Unicode strings always, independent of locale. POSIX file names are byte strings, and there isn't any good support for recording what their encoding is. If there's a font file from India and I want to open it on my system in South Africa (and I have LANG=C) then it seems that it's impossible to do. If I access the filename it throws a unicodeDecodeError. If I use 'replace' or 'ignore' then I am mangling the filename and I won't be able to open it. Correct. Notice that there are two ways (currently) in Python to get a directory listing: with a Unicode directory name, which returns Unicode strings, and with a byte string directory name, which returns byte strings. If you think you may have file names with mixed locales, and the current locale might not match the file name's locale, you should be using the byte string variant on Unix (which it seems you are already doing). Then, if the locale's encoding cannot decode the file names, you have several options a) don't try to interpret the file names as character strings, i.e. don't decode them. Not sure why you need the file names - if it's only to open the files, and never to present the file name to the user, not decoding them might be feasible b) guess an encoding. For file names on Linux, UTF-8 is fairly common, so it might be a reasonable guess. c) accept lossy decoding, i.e. decode with some encoding, and use replace as the error handler. You'll have to preserve the original file names along with the decoded versions if you later also want to operate on the original file. My (admittedly uninformed) conception is that by forcing the app to always use utf8 I can access any filename in any encoding. That's not true. Try open(\xff,w), then try interpreting the file name as UTF-8. Some byte strings are not meaningful UTF-8, hence that approach cannot work. You *can* interpret all file names as ISO-8859-1, but then some file names will show moji-bake. The problem seems to be that I cannot know *what* encoding (and I get encode/decode mixed up still, very new to it all) that particular filename is in. That's correct, and there is no solution (not in Python, not in any other programming language). You have to made trade-offs. For that, you need to analyze precisely what your requirements are. I went through this exercise recently and had no joy. It seems the string I chose to use simply would not render - even under 'ignore' and 'replace'. I don't understand what would not render means. It's really frustrating because I don't speak a non-ascii language and so can't know if I am testing real-world strings or crazy Tolkein strings. I guess your choices are to either give up, or learn. Another aspect of this is wxPython. My app requires the unicode build so that strings have some hope of displaying on the widgets. If I access a font file and fetch the family name - that can be encoded in any way, again unknown, and I want to fetch it as 'unicode' and pass it to the widgets and not worry about what's really going on. Given that, I thought I'd extend the 'utf8' only concept to the app in general. I am sure I am wrong, but I feel cornered at the moment. Don't confuse utf8 only with unicode only. Having all strings as Unicode strings is a good thing. Assuming that all encoded text is encoded in UTF-8 (which is but one encoding for Unicode) is likely incorrect. As for font files - I don't know what encoding the family is in, but I would sure hope that the format specification of the font file format would also specify what the encoding for the family name is, or that there are at least established conventions. 3. I made the decision to check the locale and stop the app if the return from getlocale is (None,None). I would avoid locale.getlocale. It's a pointless function (IMO). Could you say why? It tries to emulate the C library, but does so incorrectly; this is inherently unfixable because behavior of the C library can vary across platforms, and Python can't possibly encode the behavior of all C libraries in existence on all platforms. In particular, it has a hard-coded list of what charsets are in use in what locale, and that list necessarily must be incomplete and may be incorrect. As a consequence, it will return None if it doesn't know better. If all you want is the charset of the locale, use locale.getpreferredencoding(). gettext.install( domain, localedir, unicode = True ) lang = gettext.translation(domain, localedir, languages = [loc] ) You could just leave out the languages parameter, and trust gettext to find some message catalog. So, I am using getlocale to get a tuple/list (easy, no?) to pass to the gettext.install function. Sure - but the parameter is optional. Your program definitely, absolutely must work in the
Re: Elementary string-formatting
In article [EMAIL PROTECTED], John Machin [EMAIL PROTECTED] wrote: snip You obviously haven't tried float(n / m), or you wouldn't be asking. True, it was a very silly idea. Most legible and slowest first: 1. float(n) / float(m) 2. n / float(m) 3. 1.0 * n / m Recommendation: go with (2) until you find you've got a program with a real speed problem (and then it probably won't be caused by this choice). I had actually used n / float(m) at one point; somehow the above struck me as an improvement while I was writing the message. Thanks for the reality check. -- Odysseus -- http://mail.python.org/mailman/listinfo/python-list
Re: Elementary string-formatting
In article [EMAIL PROTECTED], Roberto Bonvallet [EMAIL PROTECTED] wrote: Put this at the beginning of your program: from __future__ import division This forces all divisions to yield floating points values: Thanks for the tip. May I assume the div operator will still behave as usual? -- Odysseus -- http://mail.python.org/mailman/listinfo/python-list
Re: Elementary string-formatting
On Jan 13, 8:43 pm, Odysseus [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Roberto Bonvallet [EMAIL PROTECTED] wrote: Put this at the beginning of your program: from __future__ import division This forces all divisions to yield floating points values: Thanks for the tip. May I assume the div operator will still behave as usual? div operator? The integer division operator is // from __future__ import division 1 / 3 0.1 1 // 3 0 22 / 7 3.1428571428571428 22 // 7 3 22 div 7 File stdin, line 1 22 div 7 ^ SyntaxError: invalid syntax -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphics Module
On 11 ene, 22:51, Mike [EMAIL PROTECTED] wrote: On Jan 11, 3:31 pm, Gabriel [EMAIL PROTECTED] wrote: Hi all ! I'm developing a math program that shows graphics of functions. I would hear suggestions about the way of drawing 2D . Thanks a lot for your answers. - Gabriel - That's not a very descriptive question, however most people talk about matplotlib for graphing and 2D drawings. Here's a few links on graphing in Python: http://matplotlib.sourceforge.net/http://wiki.python.org/moin/PythonGraphApihttp://alpha-leonis.lids.mit.edu/nlp/pygraph/http://boost.org/libs/graph/doc/python.htmlhttp://www.python.org/doc/essays/graphs.html Some of these may have dependencies, such as numpy or scipy. Be sure to read the docs for full details either way. Mike Thanks ! Yes. This is what I was looking for.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Elementary string-formatting
In article [EMAIL PROTECTED], Gary Herron [EMAIL PROTECTED] wrote: Odysseus wrote: snip print '%2u %6u %4.2f' % \ (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0]) Using 4.2 is the problem. The first digit (your 4) give the total number of characters to use for the number. Thanks; I was thinking the numbers referred to digits before and after the decimal. The largest figures have five characters in all, so they were 'overflowing'. -- Odysseus -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Martin, Thanks, food for thought indeed. On Unix, yes. On Windows, NTFS and VFAT represent file names as Unicode strings always, independent of locale. POSIX file names are byte strings, and there isn't any good support for recording what their encoding is. I get my filenames from two sources: 1. A wxPython treeview control (unicode build) 2. os.listdir() with a unicode path passed to it I have found that os.listdir() does not always return unicode objects when passed a unicode path. Sometimes byte strings are returned in the list, mixed-in with unicodes. I will try the technique given on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding Perhaps that will help. Re os.listdir(): If you think you may have file names with mixed locales, and the current locale might not match the file name's locale, you should be using the byte string variant on Unix (which it seems you are already doing). I gather you mean that I should get a unicode path, encode it to a byte string and then pass that to os.listdir Then, I suppose, I will have to decode each resulting byte string (via the detect routines mentioned in the link above) back into unicode - passing those I simply cannot interpret. Then, if the locale's encoding cannot decode the file names, you have several options a) don't try to interpret the file names as character strings, i.e. don't decode them. Not sure why you need the file names - if it's only to open the files, and never to present the file name to the user, not decoding them might be feasible So, you reckon I should stick to byte-strings for the low-level file open stuff? It's a little complicated by my using Python Imaging to access the font files. It hands it all over to Freetype and really leaves my sphere of savvy. I'll do some testing with PIL and byte-string filenames. I wish my memory was better, I'm pretty sure I've been down that road and all my results kept pushing me to stick to unicode objects as far as possible. b) guess an encoding. For file names on Linux, UTF-8 is fairly common, so it might be a reasonable guess. c) accept lossy decoding, i.e. decode with some encoding, and use replace as the error handler. You'll have to preserve the original file names along with the decoded versions if you later also want to operate on the original file. Okay, I'm getting your drift. That's not true. Try open(\xff,w), then try interpreting the file name as UTF-8. Some byte strings are not meaningful UTF-8, hence that approach cannot work. Okay. That's correct, and there is no solution (not in Python, not in any other programming language). You have to made trade-offs. For that, you need to analyze precisely what your requirements are. I would say the requirements are: 1. To open font files from any source (locale.) 2. To display their filename on the gui and the console. 3. To fetch some text meta-info (family etc.) via PIL/Freetype and display same. 4. To write the path and filename to text files. 5. To make soft links (path + filename) to another path. So, there's a lot of unicode + unicode and os.path.join and so forth going on. I went through this exercise recently and had no joy. It seems the string I chose to use simply would not render - even under 'ignore' and 'replace'. I don't understand what would not render means. I meant it would not print the name, but constantly throws ascii related errors. I don't know if the character will survive this email, but the text I was trying to display (under LANG=C) in a python script (not the immediate-mode interpreter) was: MÖgul. The second character is a capital O with an umlaut (double-dots I think) above it. For some reason I could not get that to display as M?gul or Mgul. BTW, I just made that up - it means nothing (to me). I hope it's not a swear word in some other language :) As for font files - I don't know what encoding the family is in, but I would sure hope that the format specification of the font file format would also specify what the encoding for the family name is, or that there are at least established conventions. You'd think. It turns out that font file are anything but simple. I am doing my best to avoid being sucked-into the black hole of complexity they represent. I must stick to what PIL/Freetype can do. The internals of font-files are waay over my head. I would avoid locale.getlocale. It's a pointless function (IMO). As a consequence, it will return None if it doesn't know better. If all you want is the charset of the locale, use locale.getpreferredencoding(). Brilliant summary - thanks a lot for that. You could just leave out the languages parameter, and trust gettext to find some message catalog. Right - I'll give that a go. This would mean cutting-out a percentage of the external font files that can be used by the app. See above. There are other ways to trade-off.
Re: Elementary string-formatting
Odysseus wrote: Hello, group: I've just begun some introductory tutorials in Python. Taking off from the word play exercise at http://www.greenteapress.com/thinkpython/html/book010.html#toc96 I've written a mini-program to tabulate the number of characters in each word in a file. Once the data have been collected in a list, the output is produced by a while loop that steps through it by incrementing an index i, saying print '%2u %6u %4.2f' % \ (i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0]) This isn't very important, but instead of keeping track of the index yourself, you can use enumerate(): mylist = ['a', 'b', 'c'] for i, item in enumerate(mylist): ... print i, item ... 0 a 1 b 2 c Err, it doesn't look like you can make it start at 1 though. snip -- -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib question (cannot open data connection)
BUT: active FTP does not just send the data to the port that was in the random port that was sent to the server... it addresses to the port you sent, but it sends its data response FROM port 20. This means the response looks like a totally unsolicited connection attempt from the outside -- the firewall doesn't even have enough information to determine which machine (if multiple) inside the firewall should be receiving the data; since the server is sending the data stream on its port 20 and there is no active connection for server:20 to ANY client: Yes, I know. But it DOES work from inside my NAT network. I have no clue how. I'm sure that it is using active connections because this server cannot use passive mode. It might be a very clever firewall that does packet sniffing for ftp PORT commands. (?) Anyway, the problem is not with this computer, it was a counter-example. Even if you could tell the firewall to let in connections on the specified port, the NAT tables won't know what inside IP to translate the inbound server port 20... It does not need to. I can reconfigure the firewall to directly forward all incoming TCP connections from a specified port range to a given IP inside the internal network. But I do not even need to do that. The problem is with a computer that is NOT behind NAT. It is a single computer connected directly to the internet, but it has a firewall installed. So everything would be fine except one thing: I should tell ftplib which port(s) to open, and open those ports on my firewall. For example, I can open TCP ports between 5 and 6, and then tell ftplib to use ports between 5 and 6 in PORT and EPRT commands. How can I do that? If that is not possible, then what is the workaround? (Definitely I do not want to turn off the firewall completely on a production server.) Passive mode turns this around. Yep, but this ftp server cannot use passive mode and I cannot change this. And finally, if this cannot be done in ftplib, then I would like to suggest to add this method to Ftp objects. :-) Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: *** AMERICAN BASTARDS DESERVE TO BE RAPED ***
When did this list become a politics dialog? Please keep on topic Python! Thanks James On Jan 12, 2008 8:07 PM, Joe Riopel [EMAIL PROTECTED] wrote: On Jan 12, 2008 2:00 PM, radiosrfun [EMAIL PROTECTED] wrote: Whether we agree on tactics or not - if it come to a battlefield with the two of us - or any Americans there - we're still going to fight the same enemy - not each other. This is a good resource for starting Python http://diveintopython.org/ -- http://mail.python.org/mailman/listinfo/python-list -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -- http://mail.python.org/mailman/listinfo/python-list
paypal python library
I m trying to program the paypal for accepting payments Aret there python libraries for the same thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: [Kamaelia] TCPClient: How to sense connection failure?
Michael Sparks wrote: The behaviour you're seeing sounds odd (which is hopefully encouraging :-), but it's not clear from the description whether its a bug in your code or Kamaelia. One question I really have as a result is what version are you using? Oh sorry, it's the versions from MegaPack 1.4.0. In the meantime - whilst I check to see if there's a bug I didn't know about, the following 2 cookbook entries may be of use: * http://kamaelia.sourceforge.net/Cookbook/TCPSystems * http://kamaelia.sourceforge.net/Cookbook/Carousels - allows you to make something that exits reusable. It's a little awkward to get your head around, but is quite useful when you do. (I've heard of others using Carousel TCPClient to make a reconnecting TCPClient in the past) Thanks for all the information. All that said, I'm not going to rule out a bug and look into it. (if you have a simple example you find fails, please forward it to me :) Sure, here is my code (but see below ;) ): snip-- from Kamaelia.Internet.TCPClient import TCPClient from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer, ConsoleReader from Axon.Component import component from Axon.Ipc import shutdownMicroprocess, producerFinished class Listener(component): Inboxes = {inbox: Inbox, control: control signals received here, } Outboxes = {outbox: (not used), signal: (not used) } def main(self): while True: if self.dataReady(inbox): print data from Inbox:, repr(self.recv(inbox)) if self.dataReady(control): control_data = self.recv(control) print repr(control_data) if isinstance(control_data, shutdownMicroprocess): print Connection could not be established break elif isinstance(control_data, producerFinished): print Connection closed break yield 1 k = ConsoleReader( ) tcp_client = TCPClient(127.0.0.1, 1850) listener = Listener() Pipeline(tcp_client, listener).run() snip-- So I'm just using a client and a helper object to display all data behind it. I usually start the script in one VT, and nc -l -p 1850 in another. Using wireshark, the packet sequence is almost identical: Client closes connection: C: SYN S: SYN,ACK C: ACK [connection established] C: FIN,ACK S: FIN,ACK C: ACK Client closes connection: C: SYN S: SYN,ACK C: ACK [connection established] S: FIN,ACK C: ACK C: FIN,ACK S: ACK Looks like a perfectly normal handshake to me. The following code may also be useful when debugging: Cool, I've been looking for a code piece like that. :) Whoops, the TCP client does in fact quit if the server closes connection :) For some reason, my Listener doesn't quit. I thought it's sufficient to exit the main method in some way to quit a component? That's what I do using break in the 'if self.dataReady(control)' part of main. Regards, Björn -- BOFH excuse #265: The mouse escaped. -- http://mail.python.org/mailman/listinfo/python-list
Mailinglist/newsgroup gateway
-On [20080112 23:30], Dan Upton ([EMAIL PROTECTED]) wrote: Why was this ever on the Python list (I assume it started as spam), and why on earth has it continued? The Python mailinglist is a gateway to/from comp.lang.python for all I know. So anything idiotic getting posted there might make its way unto the mailing list. I wonder what the ratio of newsgroup posters versus mailinglist posters is nowadays. -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ Faith, it seems, is not without irony... -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
-On [20080113 01:41], Erik Lind ([EMAIL PROTECTED]) wrote: I'm new to Python, and OOP. I've read most of Mark Lutz's book and more online and can write simple modules, but I still don't get when __init__ needs to be used as opposed to creating a class instance by assignment. I personally tend to see __init__ or __new__ as equivalent to what other languages call a constructor. (And I am sure some people might disagree with that. ;)) -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ The riddle master himself lost the key to his own riddles one day, and found it again at the bottom of his heart. -- http://mail.python.org/mailman/listinfo/python-list
about sort a list with integer key
hi, if I want sort each line ,by the last part,of a file, below is the source. from operator import itemgetter content = (line.split() for line in file('foo.txt', 'rb')) for cursor, line in enumerate(sorted(content, key = itemgetter(-1), reverse = True)): print cursor, ' '.join(line) the content of foo.txt is 21 job 3 joke the result is 0 3 joke 1 21 job if i want sort each line by the first part,(it's a integer, in fact). don't know how to do it with itemgetter. key = int(itemgetter(0)) is wrong, key = lambda x:int(x[0]) works. but s.b. told me itemgetter execute more quickly . -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
I have found that os.listdir() does not always return unicode objects when passed a unicode path. Sometimes byte strings are returned in the list, mixed-in with unicodes. Yes. It does so when it fails to decode the byte string according to the file system encoding (which, in turn, bases on the locale). I will try the technique given on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding Perhaps that will help. I would advise against such a strategy. Instead, you should first understand what the encodings of the file names actually *are*, on a real system, and draw conclusions from that. I gather you mean that I should get a unicode path, encode it to a byte string and then pass that to os.listdir Then, I suppose, I will have to decode each resulting byte string (via the detect routines mentioned in the link above) back into unicode - passing those I simply cannot interpret. That's what I meant, yes. Again, you have a number of options - passing those that you cannot interpret is but one option. Another option is to accept moji-bake. Then, if the locale's encoding cannot decode the file names, you have several options a) don't try to interpret the file names as character strings, i.e. don't decode them. Not sure why you need the file names - if it's only to open the files, and never to present the file name to the user, not decoding them might be feasible So, you reckon I should stick to byte-strings for the low-level file open stuff? It's a little complicated by my using Python Imaging to access the font files. It hands it all over to Freetype and really leaves my sphere of savvy. I'll do some testing with PIL and byte-string filenames. I wish my memory was better, I'm pretty sure I've been down that road and all my results kept pushing me to stick to unicode objects as far as possible. I would be surprised if PIL/freetype would not support byte string file names if you read those directly from the disk. OTOH, if the user has selected/typed a string at a GUI, and you encode that - I can easily see how that might have failed. That's correct, and there is no solution (not in Python, not in any other programming language). You have to made trade-offs. For that, you need to analyze precisely what your requirements are. I would say the requirements are: 1. To open font files from any source (locale.) 2. To display their filename on the gui and the console. 3. To fetch some text meta-info (family etc.) via PIL/Freetype and display same. 4. To write the path and filename to text files. 5. To make soft links (path + filename) to another path. So, there's a lot of unicode + unicode and os.path.join and so forth going on. I notice that this doesn't include to allow the user to enter file names, so it seems there is no input of file names, only output. Then I suggest this technique of keeping bytestring/unicode string pairs. Use the Unicode string for display, and the byte string for accessing the disc. I went through this exercise recently and had no joy. It seems the string I chose to use simply would not render - even under 'ignore' and 'replace'. I don't understand what would not render means. I meant it would not print the name, but constantly throws ascii related errors. That cannot be. Both the ignore and the replace error handlers will silence all decoding errors. I don't know if the character will survive this email, but the text I was trying to display (under LANG=C) in a python script (not the immediate-mode interpreter) was: MÖgul. The second character is a capital O with an umlaut (double-dots I think) above it. For some reason I could not get that to display as M?gul or Mgul. I see no problem with that: uM\xd6gul.encode(ascii,ignore) 'Mgul' uM\xd6gul.encode(ascii,replace) 'M?gul' Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Martin, Yes. It does so when it fails to decode the byte string according to the file system encoding (which, in turn, bases on the locale). That's at least one way I can weed-out filenames that are going to give me trouble; if Python itself can't figure out how to decode it, then I can also fail with honour. I will try the technique given on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html #guessing-the-encoding Perhaps that will help. I would advise against such a strategy. Instead, you should first understand what the encodings of the file names actually *are*, on a real system, and draw conclusions from that. I don't follow you here. The encoding of file names *on* a real system are (for Linux) byte strings of potentially *any* encoding. os.listdir() may even fail to grok some of them. So, I will have a few elements in a list that are not unicode, I can't ask the O/S for any help and therefore I should be able to pass that byte string to a function as suggested in the article to at least take one last stab at identifying it. Or is that a waste of time because os.listdir() has already tried something similar (and prob. better)? I notice that this doesn't include to allow the user to enter file names, so it seems there is no input of file names, only output. I forgot to mention the command-line interface... I actually had trouble with that too. The user can start the app like this: fontypython /some/folder/ or fontypython SomeFileName And that introduces input in some kind of encoding. I hope that locale.getprefferedencoding() will be the right one to handle that. Is such input (passed-in via sys.argv) in byte-strings or unicode? I can find out with type() I guess. As to the rest, no, there's no other keyboard input for filenames. There *is* a 'filter' which is used as a regex to filter 'bold', 'italic' or whatever. I fully expect that to give me a hard time too. Then I suggest this technique of keeping bytestring/unicode string pairs. Use the Unicode string for display, and the byte string for accessing the disc. Thanks, that's a good idea - I think I'll implement a dictionary to keep both and work things that way. I see no problem with that: uM\xd6gul.encode(ascii,ignore) 'Mgul' uM\xd6gul.encode(ascii,replace) 'M?gul' Well, that was what I expected to see too. I must have been doing something stupid. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
So on *your* system, today: what encoding are the filenames encoded in? We are not talking about arbitrary files, right, but about font files? What *actual* file names do these font files have? On my system, all font files have ASCII-only file names, even if they are for non-ASCII characters. I guess I'm confused by that. I can ls them, so they appear and thus have characters displayed. I can open and cat them and thus the O/S can access them, but I don't know whether their characters are strictly in ascii-limits or drawn from a larger set like unicode. I mean, I have seen Japanese characters in filenames on my system, and that can't be ascii. You see, I have a large collection of fonts going back over 10 years and they came from usenet years ago and so have filenames mangled all to hell. I can't always *type* some of their names and have to use copy/paste to, for example, ls one of them. Again, it's working from ignorance (my own) : I assume filenames in different countries will be in character sets that I have never (nor will I ever) see. But I have to cover them somehow. Or is that a waste of time because os.listdir() has already tried something similar (and prob. better)? better is a difficult notion here. Is it better to produce some result, possibly incorrect, or is it better to give up? I think I see, combined with your previous advice - I will keep byte strings alongside unicode and where I can't get to the unicode for that string, I will keep an 'ignore' or 'replace' unicode, but I will still have the byte string and will access the file with that anyway. If the user has set up his machine correctly: yes. Meaning, I am led to assume, the LANG variable primarily? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: about sort a list with integer key
lotrpy wrote: key = int(itemgetter(0)) is wrong, key = lambda x:int(x[0]) works. but s.b. told me itemgetter execute more quickly . so you're more interested in speed than in correctness? ;-) operator.itemgetter is a function factory that creates a *function* that fetches the given item from a sequence. or in other words, typing func = itemgetter(0) is pretty much the same thing as typing def func(seq): return seq[0] given this, it should be fairly obvious what int(itemgetter(0)) does: it attemts to convert the *function* to an integer, which obviously doesn't work. I'd stick to the lambda form if I were you. It isn't only easier to understand for the Python layman, it also does the right thing. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
I would advise against such a strategy. Instead, you should first understand what the encodings of the file names actually *are*, on a real system, and draw conclusions from that. I don't follow you here. The encoding of file names *on* a real system are (for Linux) byte strings of potentially *any* encoding. No. On a real system, nothing is potential, but everything is actual. So on *your* system, today: what encoding are the filenames encoded in? We are not talking about arbitrary files, right, but about font files? What *actual* file names do these font files have? On my system, all font files have ASCII-only file names, even if they are for non-ASCII characters. os.listdir() may even fail to grok some of them. So, I will have a few elements in a list that are not unicode, I can't ask the O/S for any help and therefore I should be able to pass that byte string to a function as suggested in the article to at least take one last stab at identifying it. It won't identify it. It will just give you *some* Unicode string. Or is that a waste of time because os.listdir() has already tried something similar (and prob. better)? better is a difficult notion here. Is it better to produce some result, possibly incorrect, or is it better to give up? I forgot to mention the command-line interface... I actually had trouble with that too. The user can start the app like this: fontypython /some/folder/ or fontypython SomeFileName And that introduces input in some kind of encoding. I hope that locale.getprefferedencoding() will be the right one to handle that. If the user has set up his machine correctly: yes. I see no problem with that: uM\xd6gul.encode(ascii,ignore) 'Mgul' uM\xd6gul.encode(ascii,replace) 'M?gul' Well, that was what I expected to see too. I must have been doing something stupid. Most likely, you did not invoke .encode on a Unicode string. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
On Jan 12, 8:33 pm, Fredrik Lundh [EMAIL PROTECTED] wrote: marcstuart wrote: How do I divide a list into a set group of sublist's- if the list is not evenly dividable ? consider this example: x = [1,2,3,4,5,6,7,8,9,10] y = 3 # number of lists I want to break x into z = y/x what I would like to get is 3 sublists print z[0] = [1,2,3] print z[2] = [4,5,6] print z[3] = [7,8,9,10] obviously not even, one list will have 4 elements, the other 2 will have 3., here's one way to do it: # chop it up n = len(x) / y z = [x[i:i+n] for i in xrange(0, len(x), n)] # if the last piece is too short, add it to one before it if len(z[-1]) n and len(z) 1: z[-2].extend(z.pop(-1)) /F Eh... def chop(lst, length): n = len(lst) / length z = [lst[i:i+n] for i in xrange(0, len(lst), n)] if len(z[-1]) n and len(z) 1: z[-2].extend(z.pop(-1)) return z gives chop(range(1,9), 3) [[1, 2], [3, 4], [5, 6], [7, 8]] chop(range(1,8), 3) [[1, 2], [3, 4], [5, 6, 7]] chop(range(1,6), 3) [[1], [2], [3], [4], [5]] chop([1], 3) Traceback (most recent call last): File stdin, line 1, in module File beforemeth.py, line 9, in chop if len(z[-1]) n and len(z) 1: ValueError: xrange() arg 3 must not be zero Perhaps something like this? def chop(lst, length): from itertools import islice it = iter(lst) z = [list(islice(it, length)) for i in xrange(1 + len(lst) // length)] if len(z) 1: z[-2].extend(z.pop()) # the last item will be empty or contain overflow elements. return z -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 is it in the python default distro?
On Saturday 12 January 2008 21:34 Martin Marcher wrote: a) Is sqlite included in the python default distribution b) In real life can I consider (on linux) that an installation of python includes the sqlite stuff? forgive my that was pebcack. I wasn't reading the docs fully so I thought I need the python-sqlite or python-sqlite2 (which is in the 2.5 package on debian/ubuntu at least) -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: about sort a list with integer key
lotrpy [EMAIL PROTECTED] writes: if i want sort each line by the first part,(it's a integer, in fact). don't know how to do it with itemgetter. key = int(itemgetter(0)) is wrong, key = lambda x:int(x[0]) works. but s.b. told me itemgetter execute more quickly . Use lambda when it works better for you, the speed difference is marginal in practice anyway. itemgetter is not (and was never intended to be) a general substitute for functions, as you've discovered. The marginal speed difference between itemgetter and an explicit lambda that does the subscripts is a consequence of itemgetter being written in C, meaning it avoids the creation of a Python stack frame, etc. Combining int(...) with this operation requires coding the key function in Python, which removes itemgetter's advantage. In other words, you cannot retain itemgetter's speed advantage with more complex keys. If the sorting performance is a problem for you, please give more details about what you're doing -- there might be better ways to speed up the code. -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Erik Lind wrote: I'm new to Python, and OOP. I've read most of Mark Lutz's book and more online and can write simple modules, but I still don't get when __init__ needs to be used as opposed to creating a class instance by assignment. nothing is ever created by plain assignment in Python; to create a class instance in Python, you *call* the class object. an example: class MyClass: pass # create three separate instances obj1 = MyClass() obj2 = MyClass() obj3 = MyClass() (it's the () that creates the object, not the =) if you want to initialize the method's state (that is, set some attributes), you can do that from the outside: obj1.attrib = some value or in an initialization method in the class: class MyClass: def init(self): self.attrib = some value obj1 = MyClass() obj1.init() but in both cases, you'll end up with an inconsistent object state (in this case, no attribute named attrib) if you forget to do this. obj1 = MyClass() print obj1.attrib # this will fail to avoid such mistakes, you can use __init__ instead. this is just a initialization method that's automatically called by Python *after* the object is created, but *before* the call to the class object returns. class MyClass: def __init__(self): self.attrib = some value obj1 = MyClass() print obj1.attrib # this will succeed also, any arguments that you pass to the class object call are passed on to the initialization method. class MyClass: def __init__(self, value): self.attrib = value obj1 = MyClass(hello) print obj1.attrib # prints hello as Jeroen points out, this is pretty much the same thing as a constructor in other languages -- that is, a piece of code that's responsible for setting up an object's state. Python's a bit different; the object is in fact created before the call to __init__, but this doesn't matter much in practice; if construction fails, the assignment will fail, so the object will be lost, and is reclaimed by the GC later on. (unless you explicitly store a reference to the object somewhere else, of course: class MyClass: ... def __init__(self): ... global secret ... secret = self ... raise ValueError(oops! failed!) ... def method(self): ... print here I am! ... obj = MyClass() Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in __init__ ValueError: oops! failed! obj Traceback (most recent call last): File stdin, line 1, in module NameError: name 'obj' is not defined secret.method() here I am! ) finally, if you want full control also over the actual creation of the object, more recent Python versions support a __new__ method that can be used instead of __init__, or as a complement. but that's an advanced topic, and is nothing you need to worry about while trying to the hang of class basics. hope this helps! /F -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Jeroen Ruigrok van der Werven wrote: I personally tend to see __init__ or __new__ as equivalent to what other languages call a constructor. (And I am sure some people might disagree with that. ;)) given that they do different things, I'm not sure it's that helpful to describe them *both* as constructors. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: However, I am very surprised to learn that super_object.__getattr__(name)(*args, **kwargs) getattr(super_object, name)(*args, **kwargs) are not equivalent. This is quite odd, at least when with len() and .__len__, str() and .__str__. Do you maybe know what's the rationale behind not following that convention by getattr? I think you are confusing `__getattr__` and `__getattribute__` here! `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's different. Well, in my code calling super_object.__getattr__(name)(*args, **kwargs) and getattr(super_object, name)(*args, **kwargs) gives *different* effects (namely, the latter works, while the former doesn't). That kinda suggests that they don't map to each other :-). And that makes me feel confused. Cheers, -- Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: Magic function
Well as I understand your problem now, you would not like all instances of an specific object that are still alive, but all references to an object (created somewhere, sometimes) in an local context (stack frame), that are accessible from 'that' context ( but also from many others). However in python a stack frame does not 'contain' an object. It only contains a reference to an object. You may delete this reference whithin this frame, but the object may still be alive. So you can do following: def run(att): for k, v in att.iteritems(): if isinstance(v, dict): print k, v, id(v) def foo(bar): x = list() y = object() run(locals()) del bar run(locals()) bazz = dict() print bazz has id , id(bazz) foo(bazz) print bazz has id , id(bazz) pythonw -u console_play.py bazz has id 11068592 bar {} 11068592 bazz has id 11068592 Exit code: 0 Note that bar {} is printed only once, since the reference 'bar' defined in foo has been deleted. The object itself is still alive because the referece 'bazz' still exists. You should consider, that inspecting the stack will not tell you if an object is alive or not. It also doesn't tell you that an object can't be used by your users. If you come from an C++ background, then consider that python is different. Creating an object in an local context will not destroy this object if you leafe this context. There is no such thing like a 'destructor' in python. You should also consider, that frame objects are not destroyed if used by an generator or if there is still a reference to them. A frame object may life forever. Read the manual about the inspect module! Inspecting the stack may give you wrong and difficult to debug results. I just wouldn't do that. Keeping track of instances isn't that difficult. However if you need instances (not references to them!) that have been created within a specific stack frame you may use my example below. It will extend the weakref with the id of the stackframe that created it. However the instance may still live while the frame had been destroyed long ago! Remember: Inspecting the stack will not tell you weather a user can use an specific object nor will it tell you, if the object is alive or not. from weakref import ref from inspect import getouterframes, currentframe class ExtendedRef(ref): def __init__(self, ob, callback=None, **annotations): super(ExtendedRef, self).__init__(ob, callback) self.__id = 0 class WeakSet(set): def add(self, value, id=0): wr = ExtendedRef(value, self.remove) wr.__id = id set.add(self, wr) def get(self, id): return [ _() for _ in self if _.__id == id] class bigobject(WeakSet): def run(self): outer_frame = id(getouterframes( currentframe())[1][0]) for obj in self.get(outer_frame): # process object's print obj.value class foo(object): __instances__ = bigobject() def __init__(self, value): outer_frame = id(getouterframes( currentframe())[1][0]) foo.__instances__.add(self, outer_frame) self.value = value def main( depth ): obj1 = foo(obj1 at depth %s % depth) obj2 = foo(obj2 at depth %s % depth) foo.__instances__.run() print processed objects created at %s % id(currentframe()) if depth == 0: return else: main(depth-1) if __name__ == __main__: obj1 = foo(obj1 at depth root) main(3) foo.__instances__.run() print processed objects created at %s % id(currentframe()) pythonw -u test12.py obj1 at depth 3 obj2 at depth 3 processed objects created at 11519672 obj2 at depth 2 obj1 at depth 2 processed objects created at 11496496 obj2 at depth 1 obj1 at depth 1 processed objects created at 11813904 obj2 at depth 0 obj1 at depth 0 processed objects created at 11814272 obj1 at depth root processed objects created at 11443120 Exit code: 0 -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
I guess I'm confused by that. I can ls them, so they appear and thus have characters displayed. I can open and cat them and thus the O/S can access them, but I don't know whether their characters are strictly in ascii-limits or drawn from a larger set like unicode. I mean, I have seen Japanese characters in filenames on my system, and that can't be ascii. You see, I have a large collection of fonts going back over 10 years and they came from usenet years ago and so have filenames mangled all to hell. If you can all ls them, and if the file names come out right, then they'll have the same encoding. I can't always *type* some of their names and have to use copy/paste to, for example, ls one of them. Again, it's working from ignorance (my own) : I assume filenames in different countries will be in character sets that I have never (nor will I ever) see. I never heard before that font files use non-ASCII file names, and I don't see the point in doing so - isn't there typically a font name *inside* the font file as well, so that you'd rather use that for display than the file name? Of course, *other* files (text files, images etc) will often use non-ASCII file names. However, they won't normally have mixed encodings - most user-created files on a single system should typically have the same encoding (there are exceptions possible, of course). If the user has set up his machine correctly: yes. Meaning, I am led to assume, the LANG variable primarily? Yes. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
thebjorn wrote: Eh... oh, forgot that it was pulling requirements out of thin air week on c.l.python. def chop(lst, length): n = len(lst) / length z = [lst[i:i+n] for i in xrange(0, len(lst), n)] if len(z[-1]) n and len(z) 1: z[-2].extend(z.pop(-1)) return z gives chop([1], 3) Traceback (most recent call last): File stdin, line 1, in module File beforemeth.py, line 9, in chop if len(z[-1]) n and len(z) 1: ValueError: xrange() arg 3 must not be zero well, it doesn't. there's no xrange on that line. Perhaps something like this? from itertools import islice or just use an if-statement, or the max function. but I guess those tools are too old and boring for c.l.python these days... /F -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Jeroen Ruigrok van der Werven [EMAIL PROTECTED] writes: -On [20080113 01:41], Erik Lind ([EMAIL PROTECTED]) wrote: I'm new to Python, and OOP. I've read most of Mark Lutz's book and more online and can write simple modules, but I still don't get when __init__ needs to be used as opposed to creating a class instance by assignment. I personally tend to see __init__ or __new__ as equivalent to what other languages call a constructor. That's getting the two of them confused. __new__ is a constructor, __init__ is not. (And I am sure some people might disagree with that. ;)) It isn't really a matter for much debate. URL:http://www.python.org/doc/ref/customization.html __new__ is the constructor: it creates the instance and returns it. Along the way, it calls __init__ on the *already-created* instance, to ask it to initialise itself ready for use. So, __init__ is an initialiser for the instance. Python, unlike many other OO languages, fortunately has these two areas of functionality separate. It's far more common to need to customise instance initialisation than to customise creation of the instance. I override __init__ for just about every class I write; I can count the number of times I've needed to override __new__ on the fingers of one foot. -- \ Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force. -- Carol Reichel | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
On Jan 13, 1:05 pm, thebjorn [EMAIL PROTECTED] wrote: On Jan 12, 8:33 pm, Fredrik Lundh [EMAIL PROTECTED] wrote: marcstuart wrote: How do I divide a list into a set group of sublist's- if the list is not evenly dividable ? consider this example: x = [1,2,3,4,5,6,7,8,9,10] y = 3 # number of lists I want to break x into z = y/x what I would like to get is 3 sublists print z[0] = [1,2,3] print z[2] = [4,5,6] print z[3] = [7,8,9,10] obviously not even, one list will have 4 elements, the other 2 will have 3., here's one way to do it: # chop it up n = len(x) / y z = [x[i:i+n] for i in xrange(0, len(x), n)] # if the last piece is too short, add it to one before it if len(z[-1]) n and len(z) 1: z[-2].extend(z.pop(-1)) /F Eh... def chop(lst, length): n = len(lst) / length z = [lst[i:i+n] for i in xrange(0, len(lst), n)] if len(z[-1]) n and len(z) 1: z[-2].extend(z.pop(-1)) return z gives chop(range(1,9), 3) [[1, 2], [3, 4], [5, 6], [7, 8]] chop(range(1,8), 3) [[1, 2], [3, 4], [5, 6, 7]] chop(range(1,6), 3) [[1], [2], [3], [4], [5]] chop([1], 3) Traceback (most recent call last): File stdin, line 1, in module File beforemeth.py, line 9, in chop if len(z[-1]) n and len(z) 1: ValueError: xrange() arg 3 must not be zero Perhaps something like this? def chop(lst, length): from itertools import islice it = iter(lst) z = [list(islice(it, length)) for i in xrange(1 + len(lst) // length)] if len(z) 1: z[-2].extend(z.pop()) # the last item will be empty or contain overflow elements. return z -- bjorn Bad for to reply to myself, I know, but I just realized that the OP wanted to control the _number_ of chunks, not the size of the chunks... Building on the above would give something like from itertools import islice from operator import add def chop(lst, nchunks): chunksize, extra = divmod(len(lst), nchunks) if not chunksize: raise ValueError('More chunks than elements in list.') it = iter(lst) z = [list(islice(it, chunksize)) for i in xrange(nchunks + extra)] z, extra = z[:nchunks], z[nchunks:] z[-1].extend(reduce(add, extra, [])) # because sum ain't add :-( return z -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: about sort a list with integer key
On 1月13日, 下午8时32分, Hrvoje Niksic [EMAIL PROTECTED] wrote: Use lambda when it works better for you, the speed difference is marginal in practice anyway. itemgetter is not (and was never intended to be) a general substitute for functions, as you've discovered. The marginal speed difference between itemgetter and an explicit lambda that does the subscripts is a consequence of itemgetter being written in C, meaning it avoids the creation of a Python stack frame, etc. Combining int(...) with this operation requires coding the key function in Python, which removes itemgetter's advantage. In other words, you cannot retain itemgetter's speed advantage with more complex keys. If the sorting performance is a problem for you, please give more details about what you're doing -- there might be better ways to speed up the code. Fredrik and Hrvoje, thanks for the reply, here the sorting performance is not a big problem for me. the text file is just several hundred line, each line include several item separated by space. I'll run the script each week or month, just 1 second to get the result,so maybe stick to lambda here is just fine. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
thebjorn [EMAIL PROTECTED] writes: Perhaps something like this? def chop(lst, length): from itertools import islice it = iter(lst) z = [list(islice(it, length)) for i in xrange(1 + len(lst) // length)] if len(z) 1: z[-2].extend(z.pop()) # the last item will be empty or contain overflow elements. return z def chop(lst, length): def chop1(): t = len(lst) // length - 1 for i in xrange(t): yield lst[i*length: (i+1)*length] yield lst[t*length:] return list(chop1()) -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
On Jan 13, 2:02 pm, Fredrik Lundh [EMAIL PROTECTED] wrote: thebjorn wrote: Eh... oh, forgot that it was pulling requirements out of thin air week on c.l.python. Well, the OP requirements were to control the number of chunks, not the size of them, so I guess we both got it wrong initially. def chop(lst, length): n = len(lst) / length z = [lst[i:i+n] for i in xrange(0, len(lst), n)] if len(z[-1]) n and len(z) 1: z[-2].extend(z.pop(-1)) return z gives chop([1], 3) Traceback (most recent call last): File stdin, line 1, in module File beforemeth.py, line 9, in chop if len(z[-1]) n and len(z) 1: ValueError: xrange() arg 3 must not be zero well, it doesn't. there's no xrange on that line. It's from this line z = [lst[i:i+n] for i in xrange(0, len(lst), n)] (I executed the file with python -i beforemeth.py to get to an interactive prompt, I'm sure you're familiar with the technique. You could have just debugged your own program to find it though, or just looked at the code -- not that many xrange calls in there, eh?) Perhaps something like this? from itertools import islice or just use an if-statement, or the max function. but I guess those tools are too old and boring for c.l.python these days... I didn't realize correct code was too new-school. Perhaps you should publish a list of modules you don't like, or perhaps I should just use a sufficiently venerable version of Python? Ok, here you go: C:\Python22python 'import site' failed; use -v for traceback Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. def chop2(lst, nchunks): ... chunksize = len(lst) // nchunks ... if not chunksize: ... raise ValueError('More chunks than elements in list.') ... res = [] ... begin, end = 0, chunksize ... for i in range(nchunks-1): ... res.append(lst[begin:end]) ... begin, end = end, end+chunksize ... res.append(lst[begin:]) ... return res ... chop2(range(1,6), 2) [[1, 2], [3, 4, 5]] chop2(range(1,6), 3) [[1], [2], [3, 4, 5]] chop2(range(1,11), 3) [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] Sufficiently old-school (or do I need to take out the // division also?) /F Shall we perhaps drop some of the attitude? (you used to be so much nicer before you wrote sre ;-) -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
If you can all ls them, and if the file names come out right, then they'll have the same encoding. Could it not be that the app doing the output (say konsole) could be displaying a filename as best as it can (doing the ignore/replace) trick and using whatever fonts it can reach) and this would disguise the situation? I don't think one can call any string a plain ascii string anymore. I have been looking for somewhere online that I can download files obviously in a non-ascii set (like japan someplace) but can't find anything easy. I want to see exactly how my system (Kubuntu 7.10) handles things. I never heard before that font files use non-ASCII file names, They are files, named as any other file - those that are created by people get called whatever they want, under whatever locale they used. Still, I don't fully understand how this is all handled. don't see the point in doing so - isn't there typically a font name *inside* the font file as well, so that you'd rather use that for display than the file name? Yes, but sometimes I can't reach that - segfaults and so forth. I also need to write the filename to a text file for logging. Of course, *other* files (text files, images etc) will often use non-ASCII file names. Same as font files - I am talking mainly about TTF files here. Mainly Arrr, pass the rum, matey fonts ;) (Which I don't use in designs, but have kept over the years.) However, they won't normally have mixed encodings - most user-created files on a single system should typically have the same encoding (there are exceptions possible, of course). Well, if I am collecting fonts from all over the place then I get a mixed-bag. Meaning, I am led to assume, the LANG variable primarily? Yes. Thanks. Good to know I'm on the right track. \d -- http://mail.python.org/mailman/listinfo/python-list
Exceptions - How do you make it work like built-in exceptions?
A built-in exceptions, when raised, would print traceback that points out the offending code, like this: Traceback (most recent call last): File F:\dir\code.py, line 43, in module a = 1/0 --- ZeroDivisionError: integer division or modulo by zero a user-made exception, when raised, would print traceback that points out the code that raises the exception Traceback (most recent call last): File F:\dir\code.py, line 48, in module raise SomeException('Some Exception Message') --- SomeException: Some Exception Message which is generally of little use (yeah, it's possible to trace the code from the line number, but sometimes it might not be that easy, cause the line number is (again) the line number for the raising code instead of the offending code) The sample exception was generated from this code: class SomeException(Exception): pass try: a = 1/0 except: raise SomeException('Some Exception Message') Is it possible to make the user-made exception points out the offending code? -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 13, 1:51 pm, Richard Szopa [EMAIL PROTECTED] wrote: On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: However, I am very surprised to learn that super_object.__getattr__(name)(*args, **kwargs) getattr(super_object, name)(*args, **kwargs) are not equivalent. This is quite odd, at least when with len() and .__len__, str() and .__str__. Do you maybe know what's the rationale behind not following that convention by getattr? I think you are confusing `__getattr__` and `__getattribute__` here! `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's different. Well, in my code calling super_object.__getattr__(name)(*args, **kwargs) and getattr(super_object, name)(*args, **kwargs) gives *different* effects (namely, the latter works, while the former doesn't). That kinda suggests that they don't map to each other :-). And that makes me feel confused. Cheers, -- Richard They do, except for when it comes to what super(..) returns. It isn't really an object in the sense that they're presented in the tutorial, but rather a sort of proxy to the methods in the ancestor classes of the concrete object (self), relative to the current method's class. I can't imagine that sentence would ease any confusion however, suffice it to say that you have to call getattr(super(..), 'name') instead of super(..).__getattr__('name') and you have to call super(..).__len__() instead of len(super(..)) -- I can't imagine that lessens any confusion either :-/ super(..) is designed to handle situations like this correctly class Root(object): n = 1 class Left(Root): def foo(self): print 'n =', self.n print 'super n = ', super(Left, self).n class Right(Root): n = 2 class Leaf(Left,Right): n = 3 x = Leaf() x.foo() the correct output is n = 3 super n = 2 -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: Exceptions - How do you make it work like built-in exceptions?
On Jan 13, 4:14 pm, Lie [EMAIL PROTECTED] wrote: A built-in exceptions, when raised, would print traceback that points out the offending code, like this: Traceback (most recent call last): File F:\dir\code.py, line 43, in module a = 1/0 --- ZeroDivisionError: integer division or modulo by zero a user-made exception, when raised, would print traceback that points out the code that raises the exception Traceback (most recent call last): File F:\dir\code.py, line 48, in module raise SomeException('Some Exception Message') --- SomeException: Some Exception Message which is generally of little use (yeah, it's possible to trace the code from the line number, but sometimes it might not be that easy, cause the line number is (again) the line number for the raising code instead of the offending code) The sample exception was generated from this code: class SomeException(Exception): pass try: a = 1/0 except: raise SomeException('Some Exception Message') Is it possible to make the user-made exception points out the offending code? from sys import exc_info try: a = 1/0 except: type, value, traceback = exc_info() raise SomeException(type) -- http://mail.python.org/mailman/listinfo/python-list
i am new guy for this discussion group
i am new guy to learn python,also for this discussion group, i am chinese. nice to meet you, everyone. -- http://mail.python.org/mailman/listinfo/python-list
wxpython-wx.CheckListBox: changing item bacgkground color
Hi everyone! In my application (under windows) I'm using a wx.checklistbox. I would like the background color of an item to become red whenever an EVT_LISTBOX_DCLICK occurs. Is there any simple way to achieve it? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get user home directory on Windows
thebjorn wrote: On Jan 12, 6:50 pm, Giampaolo Rodola' [EMAIL PROTECTED] wrote: Update. I found a way for getting the home directory of the user but it requires to validate the user by providing username+password: def get_homedir(username, password): token = win32security.LogonUser( username, None, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT ) return win32profile.GetUserProfileDirectory(token) What I'd like to do is avoiding the requirement of the password, the same way as if I would on UNIX where it would be enough just using the pwd module: import pwd pwd.getpwnam('user').pw_dir '/home/user' Check out http://msdn2.microsoft.com/en-us/library/bb762181(VS.85).aspx for some of the complexities of special directories on Windows. Part of the problem here is that is the OP is asking for the home dir of a user, but there is no such thing under Windows. Or, rather, there are several such things. The code he posts above will get the path to what will be the user's %USERPROFILE% env var when he logs on. (Which is certainly one of the definitions of home dir). But he wants that path *without* having to log them in. The page you refer to (and other similar suggestions of using the os.expanduser function which essentially does the same thing for you) assume you're already logged in as the user in question. I've posted a (WMI-based) solution [1] on the python-win32 list where the OP copied his question. You could do the same just with win32security and _winreg. (Left as an exercise... etc.) Haven't yet heard back from the OP as to whether that's given him what he wants or not. TJG [1] http://mail.python.org/pipermail/python-win32/2008-January/006656.html -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get user home directory on Windows
On Jan 12, 6:50 pm, Giampaolo Rodola' [EMAIL PROTECTED] wrote: Update. I found a way for getting the home directory of the user but it requires to validate the user by providing username+password: def get_homedir(username, password): token = win32security.LogonUser( username, None, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT ) return win32profile.GetUserProfileDirectory(token) What I'd like to do is avoiding the requirement of the password, the same way as if I would on UNIX where it would be enough just using the pwd module: import pwd pwd.getpwnam('user').pw_dir '/home/user' Check out http://msdn2.microsoft.com/en-us/library/bb762181(VS.85).aspx for some of the complexities of special directories on Windows. If you give more details on what you need to get done, someone might come up with a better solution (my instinct tells me this might be a database problem, but then I'm a database person so that might not be terribly relevant ;-) -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Could it not be that the app doing the output (say konsole) could be displaying a filename as best as it can (doing the ignore/replace) trick and using whatever fonts it can reach) and this would disguise the situation? No. It may use replacement characters (i.e. a question mark, or an empty square box), but if you don't see such characters, then the terminal has successfully decoded the file names. Whether it also correctly decoded them is something for you to check (i.e. do they look right?) I have been looking for somewhere online that I can download files obviously in a non-ascii set (like japan someplace) but can't find anything easy. I want to see exactly how my system (Kubuntu 7.10) handles things. So what does sys.getfilesystemencoding() say what encoding is used for filenames? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
No. It may use replacement characters (i.e. a question mark, or an empty square box), but if you don't see such characters, then the terminal has successfully decoded the file names. Whether it also correctly decoded them is something for you to check (i.e. do they look right?) Okay. So, the picture I get is: *If* my locale *happens* to be the right one then the filename will appear properly. If it does not cover that file, then that filename will appear with ? marks in the name. Because I use en_ZA.utf8 it's doing a very good job of decoding a wide variety of filenames and therefore I rarely see ? characters. What happens if there is a filename that cannot be represented in it's entirety? i.e. every character is 'replaced'. Does it simply vanish, or does it appear as ? ? :) I spent an hour trying to find a single file on the web that did *not* have (what seemed like) ascii characters in it and failed. Even urls on Japanese websites use western characters ( a tcp/ip issue I suspect). I was hoping to find a filename in Kanji (?) ending in .jpg or something so that I could download it and see what my system (and Python) made of it. Thanks again, \d -- Life results from the non-random survival of randomly varying replicators. -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: where do my python files go in linux?
Jorgen Bodde [EMAIL PROTECTED] wrote: I am trying to make a debian package. I am following the tutorial by Horst Jens (http://showmedo.com/videos/video?name=linuxJensMakingDebfromSeriesID=37) and it is very informative. However one thing my app has and his doesn't, is multiple python files which need to be executed. For example {dir}/app app.py app.py calls a lot of modules in {dir}/app. Horst says the python file goes in /usr/bin/app.py which is ok with me, but I have multiple python files, and I decided to use an app.sh script to call my python files. In the /usr/bin I do not see subdirs so I assume that is not really desirable. Question 1. Where do I put the bulk of python scripts in a normal linux environment? Question 2. Should I use *.pyc rather then *.py files to speed up executing as the user cannot write to /usr/bin or any other dir in the system and everytime my app runs it will recompile it Thanks for any advice or maybe a good tutorial how to set up files in a linux environment Have look at the Debian Python Policy (should be in /usr/share/doc/python/python-policy.* on Debian systems) With regards, - Jorgen Florian -- http://www.florian-diesch.de/ --- ** Hi! I'm a signature virus! Copy me into your signature, please! ** --- -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
What happens if there is a filename that cannot be represented in it's entirety? i.e. every character is 'replaced'. Does it simply vanish, or does it appear as ? ? :) The latter. I did open(u\u20ac\u20ac,w) in an UTF-8 locale, then did LANG=C ls, and it gave me ?? (as the two characters use 6 bytes) I spent an hour trying to find a single file on the web that did *not* have (what seemed like) ascii characters in it and failed. Even urls on Japanese websites use western characters ( a tcp/ip issue I suspect). Actually, an HTTP and URL issue. Non-ASCII URLs aren't really supported in the web. I was hoping to find a filename in Kanji (?) ending in .jpg or something so that I could download it and see what my system (and Python) made of it. Use a text editor instead to create such a file. For example, create a new document, and save it as 活用事例.txt (which Google says means casestudies.txt) Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Martin, I want to thank you for your patience, you have been sterling. I have an overview this evening that I did not have this morning. I have started fixing my code and the repairs may not be that extreme after all. I'll hack-on and get it done. I *might* bug you again, but I'll resist at all costs :) Much appreciated. \d -- A computer without Windows is like chocolate cake without mustard. -- Anonymous Coward /. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: i am new guy for this discussion group
On Jan 13, 3:03 pm, bill.wu [EMAIL PROTECTED] wrote: i am new guy to learn python,also for this discussion group, i am chinese. nice to meet you, everyone. Hi and welcome onboard. If you're new to programming in general, you may want to join the tutor mailing-list. http://mail.python.org/mailman/listinfo/tutor If you're already a programmer, you may want to follow the offficial tutorial, then probably diveintopython: http://docs.python.org/tut/tut.html http://www.diveintopython.org/ HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Well, that didn't take me long... Can you help with this situation? I have a file named MÖgul.pog in this directory: /home/donn/.fontypython/ I set my LANG=C Now, I want to open that file from Python, and I create a path with os.path.join() and an os.listdir() which results in this byte string: paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] I *think* that the situation is impossible because the system cannot resolve the correct filename (due the locale being ANSI and the filename being other) but I am not 100% sure. So, I have been trying combinations of open: 1. f = codecs.open( paf, r, utf8 ) I had hopes for this one. 2. f = codecs.open( paf, r, locale.getpreferredencoding()) 3. f = open( paf, r) But none will open it - all get a UnicodeDecodeError. This aligns with my suspicions, but I wanted to bounce it off you to be sure. It does not really mesh with our previous words about opening all files as bytestrings, and admits failure to open this file. Also, this codecs.open(filename, r, encoding) function: 1. Does it imply that the filename will be opened (with the name as it's type : i.e. bytestring or unicode ) and written *into* as encoding 2. Imply that filename will be encoded via encoding and written into as encoding It's fuzzy, how is the filename handled? \d -- He has Van Gogh's ear for music. -- Billy Wilder Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Exceptions - How do you make it work like built-in exceptions?
Lie [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] A built-in exceptions, when raised, would print traceback that points out the offending code, like this: Traceback (most recent call last): File F:\dir\code.py, line 43, in module a = 1/0 --- ZeroDivisionError: integer division or modulo by zero a user-made exception, when raised, would print traceback that points out the code that raises the exception Traceback (most recent call last): File F:\dir\code.py, line 48, in module raise SomeException('Some Exception Message') --- SomeException: Some Exception Message which is generally of little use (yeah, it's possible to trace the code from the line number, but sometimes it might not be that easy, cause the line number is (again) the line number for the raising code instead of the offending code) The sample exception was generated from this code: class SomeException(Exception): pass try: a = 1/0 except: raise SomeException('Some Exception Message') Is it possible to make the user-made exception points out the offending code? The raise statement *was* the offending (unhandled exception) code. The ZeroDivisionError was handled by your except clause. You can override the traceback your exception will use with the three-expression form of the raise statement (See Section 6.9 The raise statement in the Python Reference Manual) by passing the traceback of the original exception: ## CODE # import sys class SomeException(Exception): pass try: a=1/0 except: org_type,org_value,org_traceback = sys.exc_info() raise SomeException,'had some problems with this code',org_traceback ## OUTPUT ## Traceback (most recent call last): File exc.py, line 7, in module a=1/0 SomeException: had some problems with this code --Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: *SPAM*: 06.2/6.0 - Re: Manually installing PIL
Dear Fredik, I have tried to copy PIL folder into my application folder. I am using Tkinter also, and when I want to put an image as label I do: photo1 = Image.open(rMyimage.gif) photo = ImageTk.PhotoImage(photo1) llogo =Label(root, image=photo,bg=white,height=60) And I receive an error message, telling me that imaging C library is not installed. As I have read, PIL is composed of PIL library and a PIL binary module called _imaging.pyd or _imaging.so or something like this. I have download Imaging-1.1.6 source code, and I found PIL folder, but not binary file. If I download windows exe installer, it works great, but I want to install manually for installing it on my PDA SOS :-S :-( Best Regards, Naxo -Original Message- From: Fredrik Lundh [EMAIL PROTECTED] To: python-list@python.org Date: Thu, 03 Jan 2008 09:53:57 +0100 Subject: *SPAM*: 06.2/6.0 - Re: Manually installing PIL Jose Ignacio Gisbert wrote: Does somebody install PIL manually??, I mean, copy directories manually without executing setup.py. I saw an identical message from Guirai, but I didn’t see any response. Thanks in advance! PIL's just a bunch of modules in a single PIL directory; you can put that directory (or the modules themselves) wherever you want. (if you're on windows, unzip the EXE installer to get the files) /F -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
time.time or time.clock
I'm having some cross platform issues with timing loops. It seems time.time is better for some computers/platforms and time.clock others, but it's not always clear which, so I came up with the following to try to determine which. import time # Determine if time.time is better than time.clock # The one with better resolution should be lower. if time.clock() - time.clock() time.time() - time.time(): clock = time.clock else: clock = time.time Will this work most of the time, or is there something better? Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: Manually installing PIL
j igisbert.etra-id wrote: this. I have download Imaging-1.1.6 source code, and I found PIL folder, but not binary file. If I download windows exe installer, it works great, but I want to install manually for installing it on my PDA as the name implies, the source code distribution contains source code only. to turn that into a binary component, you need a working compiler for your target platform. what OS does your PDA run? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Great Python books for the beginner
On Jan 12, 9:03 am, Landon [EMAIL PROTECTED] wrote: Hi, I'm a freshman in college and I'm going to be taking an intro to programming course next semester which mainly uses Python, so I thought it might be a good time to pick up Python beyond the scope of the class as well. The text book for this class is Python for the Absolute Beginner or something similar to that name. I was wondering if anyone had any opinions on what other titles I could look into since this one seems from a glance at reviews to be teaching mainly through game programming (a topic I'm not too interested in) or if this one is a quality book by itself. I found CORE PYTHON PROGRAMMING by Wesley Chun to be a great book with help on both novice and advanced topics. http://starship.python.net/crew/wesc/cpp/ The tuts and library reference on www.python.org are also really well written and layed out and you will find yourself frequenting them. -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Now, I want to open that file from Python, and I create a path with os.path.join() and an os.listdir() which results in this byte string: paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] I *think* that the situation is impossible because the system cannot resolve the correct filename (due the locale being ANSI and the filename being other) but I am not 100% sure. Not at all. The string you pass is a *byte* string, not a character string. You may think that the first letter of it is an aitch, but that's just your interpretation - it really is the byte 104. The operating system does not interpret the file names as characters at all, with the exception of treating byte 47 as the path separator (typically interpreted by people as slash). Your locale becomes only relevant when displaying file names, and having to chose what glyphs to use. So, I have been trying combinations of open: 1. f = codecs.open( paf, r, utf8 ) I had hopes for this one. 2. f = codecs.open( paf, r, locale.getpreferredencoding()) 3. f = open( paf, r) Now you are mixing two important concepts - the *contents* of the file with the *name* of the file. These are entirely independent, and the file name may be in one encoding and the file contents in another, or the file contents may not represent character data at all. All these three APIs try to get to the *contents* of the file, by opening it. The name is already a byte string (as a character string, it would have started with u'...'), so there is no need to encode it. What the content of a .pog file is, I don't know, so I can't tell you what encoding it is encoded it. But none will open it - all get a UnicodeDecodeError. This aligns with my suspicions, but I wanted to bounce it off you to be sure. Option three should have worked if paf was a string, but above, I see it as a *list* of strings. So try f = open(paf[0], r)# where paf[0] should be '/home/donn/.fontypython/M\xc3\x96gul.pog', as paf is ['/home/donn/.fontypython/M\xc3\x96gul.pog'] Still, I question that you *really* got a UnicodeDecodeError for three: I get TypeError: coercing to Unicode: need string or buffer, list found Can you please type paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] f = open(paf, r) at the interactive prompt, and report the *complete* shell output? Also, this codecs.open(filename, r, encoding) function: 1. Does it imply that the filename will be opened (with the name as it's type : i.e. bytestring or unicode ) and written *into* as encoding 2. Imply that filename will be encoded via encoding and written into as encoding It's fuzzy, how is the filename handled? See above. The encoding in codecs.open has no effect at all on the file name; it only talks about the file content. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Now you are mixing two important concepts - the *contents* of the file with the *name* of the file. Then I suspect the error may be due to the contents having been written in utf8 from previous runs. Phew! It's bedtime on my end, so I'll try it again when I get a chance during the week. Thanks muchly. \d -- snappy repartee: What you'd say if you had another chance. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: *SPAM*: 04.6/4.0 - Re: Manually installing PIL
My PDA runs with Windows Mobile 2003 SE could you or someone please explain me what to do? Thanks a lot for your effort. -Original Message- From: Fredrik Lundh [EMAIL PROTECTED] To: python-list@python.org Date: Sun, 13 Jan 2008 21:18:37 +0100 Subject: *SPAM*: 04.6/4.0 - Re: Manually installing PIL j igisbert.etra-id wrote: this. I have download Imaging-1.1.6 source code, and I found PIL folder, but not binary file. If I download windows exe installer, it works great, but I want to install manually for installing it on my PDA as the name implies, the source code distribution contains source code only. to turn that into a binary component, you need a working compiler for your target platform. what OS does your PDA run? /F -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Slicing wrapped numpy arrays
Hi, I have created a class that wraps a numpy array of custom objects. I would like to be able to slice respective objects (without copying the array if possible). I have browsed the doc and found some hints at __getitem__. However, I still do not grasp how to do it. How do I implement __getitem__ correctly? from numpy import * class Cell(object): pass class Map(object): def __init__(self, dimensions): self.generate_map(dimensions) def generate_map(self, dimensions): map_range = xrange(reduce(lambda x,y: x*y, dimensions)) self.map = array([Cell() for i in map_range]) self.map = self.map.reshape(dimensions) mymap = Map((100, 100, 100)) mymap[10:20,15:20,:] # This line should work afterwards Thanks in advance Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: time.time or time.clock
On Jan 14, 7:05 am, Ron Adam [EMAIL PROTECTED] wrote: I'm having some cross platform issues with timing loops. It seems time.time is better for some computers/platforms and time.clock others, but Care to explain why it seems so? it's not always clear which, so I came up with the following to try to determine which. import time # Determine if time.time is better than time.clock # The one with better resolution should be lower. if time.clock() - time.clock() time.time() - time.time(): clock = time.clock else: clock = time.time Will this work most of the time, or is there something better? Manual: clock( ) On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of ``processor time'', depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond. [snip] time( ) Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non- decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. AFAICT that was enough indication for most people to use time.clock on all platforms ... before the introduction of the timeit module; have you considered it? It looks like your method is right sometimes by accident. func() - func() will give a negative answer with a high resolution timer and a meaningless answer with a low resolution timer, where high and low are relative to the time taken for the function call, so you will pick the high resolution one most of the time because the meaningless answer is ZERO (no tick, no change). Some small fraction of the time the low resolution timer will have a tick between the two calls and you will get the wrong answer (-big -small). In the case of two low resolution timers, both will give a meaningless answer and you will choose arbitrarily. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Slicing wrapped numpy arrays
Martin Manns wrote: Hi, I have created a class that wraps a numpy array of custom objects. I would like to be able to slice respective objects (without copying the array if possible). I have browsed the doc and found some hints at __getitem__. However, I still do not grasp how to do it. How do I implement __getitem__ correctly? mymap[10:20,15:20,:] # This line should work afterwards The first thing you should do is simply implement a very basic, nonfunctional version just to see what objects come in: In [1]: class Sliceable(object): ...: def __getitem__(self, arg): ...: print arg ...: From the output of that you should be able to figure out how to process each of the various inputs that you want to handle. In [2]: s = Sliceable() In [3]: s[0] 0 In [4]: s[-1] -1 In [5]: s[100] 100 In [6]: s[1:10] slice(1, 10, None) In [7]: s[1:10:2] slice(1, 10, 2) In [8]: s[1:10:-2] slice(1, 10, -2) In [9]: s[:10:2,10] (slice(None, 10, 2), 10) In [10]: s[:10:2,10:100:10] (slice(None, 10, 2), slice(10, 100, 10)) In [11]: s[:10:2,10::10] (slice(None, 10, 2), slice(10, None, 10)) In [12]: s[::2,10::10] (slice(None, None, 2), slice(10, None, 10)) -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: time.time or time.clock
John Machin wrote: AFAICT that was enough indication for most people to use time.clock on all platforms ... which was unfortunate, given that time.clock() isn't even a proper clock on most Unix systems; it's a low-resolution sample counter that can happily assign all time to a process that uses, say, 2% CPU and zero time to one that uses 98% CPU. before the introduction of the timeit module; have you considered it? whether or not timeit suites his requirements, he can at least replace his code with clock = timeit.default_timer which returns a good wall-time clock (which happens to be time.time() on Unix and time.clock() on Windows). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: paging in python shell
Alex K [EMAIL PROTECTED] wrote: Does anyone know if the python shell supports paging or if I should look into iPython? Thank you so much. Paging is an overloaded term. What do you mean, exactly? Do you mean something like piping the output into more? The Python shell does that for the help command, but maybe you could post a more precise example of what you want. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: converting JSON to string
On Jan 12, 2:58 am, Jeroen Ruigrok van der Werven [EMAIL PROTECTED] nomine.org wrote: -On [20080112 08:38], Gowri ([EMAIL PROTECTED]) wrote: Actually, I have one other problem after all this. I see that if I try to construct JSON output as above, it is of the form [{'isbn': u'1-56592-724-9', 'title': u'The Cathedral the Bazaar'}, {'isbn': u'1-56592-051-1', 'title': u'Making TeX Work'}] The extra 'u' seems to causing syntax error in JavaScript which is not able to parse this response string. Any idea how I can fix this? JSON does not support Unicode in the sense of allowing raw Unicode codepoints. Instead JSON uses a \u scheme to encode Unicode characters (a bit flawed to limit it to four hexadecimal digits though, it leaves the whole CJK Unified Ideographs Extension B out of scope.). I use simplejson along with lxml/ElementTree for my JSONXML needs. -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェンhttp://www.in-nomine.org/|http://www.rangaku.org/ Any road leads to the end of the world... Thanks Jeroen. That helped a lot :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Slicing wrapped numpy arrays
On Sun, 13 Jan 2008 16:03:16 -0600 Robert Kern [EMAIL PROTECTED] wrote: Martin Manns wrote: Hi, I have created a class that wraps a numpy array of custom objects. I would like to be able to slice respective objects (without copying the array if possible). I have browsed the doc and found some hints at __getitem__. However, I still do not grasp how to do it. How do I implement __getitem__ correctly? mymap[10:20,15:20,:] # This line should work afterwards The first thing you should do is simply implement a very basic, nonfunctional version just to see what objects come in: In [1]: class Sliceable(object): ...: def __getitem__(self, arg): ...: print arg ...: I did that and got here: (slice(None, None, 2), slice(10, None, 10)) However, I still do not see how I get a Map object that employs a slice of the array without creating a new Map object. Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get user home directory on Windows
Giampaolo Rodola' wrote: Hi all, I'm trying to use the pywin32 extension to find out the user's home directory but currently I didn't find a solution yet. What I'd need to do is not getting the home directory of the currently logged in user but something like: get_homedir(frank) C:\home\users\frank get_homedir(josh) C:\home\users\josh Is there a way to do that? I tried to search through the Pywin32 documentation with no luck. In addition I'm not practiced with the Windows API at all. Well, windows, to my knowledge, uses the same base path for all profiles (this is not true for the My Documents folder which can differ). So what you could do is get the location from the ALLUSERPROFILE environment variable, go one folder higher and iterate through that. Ignoring the folders for the 'pseudo' users: 'All Users', 'Default User', 'LocalService' and 'NetworkService'. hth -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: i am new guy for this discussion group
On Jan 14, 2:03 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: On Jan 13, 3:03 pm, bill.wu [EMAIL PROTECTED] wrote: i am new guy to learn python,also for this discussion group, i am chinese. nice to meet you, everyone. Hi and welcome onboard. If you're new to programming in general, you may want to join the tutor mailing-list.http://mail.python.org/mailman/listinfo/tutor If you're already a programmer, you may want to follow the offficial tutorial, then probably diveintopython:http://docs.python.org/tut/tut.htmlhttp://www.diveintopython.org/ HTH thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: import gzip error (please help)
On Jan 11, 7:14 pm, Fredrik Lundh [EMAIL PROTECTED] wrote: the core zlib library (libz.so) isn't installed on your machine. but in my machine there is file -rwxr-xr-x 1 bin bin48576 Sep 20 2006 /usr/local/lib/ python2.5/lib-dynload/zlib.so if i have to install zlib library core, where i can found it for solaris 10 sparcv. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get user home directory on Windows
Martin P. Hellwig wrote: Giampaolo Rodola' wrote: Hi all, I'm trying to use the pywin32 extension to find out the user's home directory but currently I didn't find a solution yet. What I'd need to do is not getting the home directory of the currently logged in user but something like: get_homedir(frank) C:\home\users\frank get_homedir(josh) C:\home\users\josh Is there a way to do that? I tried to search through the Pywin32 documentation with no luck. In addition I'm not practiced with the Windows API at all. Well, windows, to my knowledge, uses the same base path for all profiles (this is not true for the My Documents folder which can differ). So what you could do is get the location from the ALLUSERPROFILE environment variable, go one folder higher and iterate through that. Ignoring the folders for the 'pseudo' users: 'All Users', 'Default User', 'LocalService' and 'NetworkService'. The trouble with that is that any particular user's profile can be specifically overridden. I'm not attached to an AD network here, but I think a networked user's profile can be network based (whike a local user's won't be, say). And there are other ways to change the profile too, down to hacking the registry as described here: http://support.microsoft.com/kb/314843/#XSLTH3129121125120121120120 That said, it'll probably work for a lot of the people for a lot of the time. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Great Python books for the beginner
In article [EMAIL PROTECTED], GeneralCody [EMAIL PROTECTED] wrote: On 2008-01-12 08:03:42 +0100, Landon [EMAIL PROTECTED] said: Hi, I'm a freshman in college and I'm going to be taking an intro to programming course next semester which mainly uses Python, so I thought it might be a good time to pick up Python beyond the scope of the class as well. The text book for this class is Python for the Absolute Beginner or something similar to that name. I was wondering if anyone had any opinions on what other titles I could look into since this one seems from a glance at reviews to be teaching mainly through game programming (a topic I'm not too interested in) or if this one is a quality book by itself. I would definetly go for Learning Python first, maybe Apress Python, from novice to Professional as well... Second those suggestions. Both are excellent books for the novice with details more experienced pythonistas can use. Although it is an excellent book, stay away from the Python Cookbook for now. Appreciating it requires a good working knowledge first. If you do get Learning Python, make sure its the 3rd edition that just became available. It covers the current 2.5 release. -- http://mail.python.org/mailman/listinfo/python-list
Re: Slicing wrapped numpy arrays
Martin Manns wrote: On Sun, 13 Jan 2008 16:03:16 -0600 Robert Kern [EMAIL PROTECTED] wrote: Martin Manns wrote: Hi, I have created a class that wraps a numpy array of custom objects. I would like to be able to slice respective objects (without copying the array if possible). I have browsed the doc and found some hints at __getitem__. However, I still do not grasp how to do it. How do I implement __getitem__ correctly? mymap[10:20,15:20,:] # This line should work afterwards The first thing you should do is simply implement a very basic, nonfunctional version just to see what objects come in: In [1]: class Sliceable(object): ...: def __getitem__(self, arg): ...: print arg ...: I did that and got here: (slice(None, None, 2), slice(10, None, 10)) However, I still do not see how I get a Map object that employs a slice of the array without creating a new Map object. That's because creating a new Map object is the right thing to do. Instead of making Map.__init__() generate the map array from the dimensions, it should just take a preconstructed map array. You can use a @classmethod or just a factory function to provide an alternate constructor which builds a Map from the dimensions. When designing classes, I usually try to do as little computation as possible in an __init__(). Doing a lot of stuff there limits the ways you can build the object later. For some classes, this doesn't matter a whole lot, but for data structures that can be sliced and concatenated or otherwise transformed, you really want that flexibility. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Threaded server
Hi, I'm trying to run an asynchronous FTP server I wrote into a thread for being able to run a test suite against it. The code below is the threaded FTP server code I'm using: --- snippet --- class FTPd(threading.Thread): def __init__(self): self.active = False threading.Thread.__init__(self) def start(self, flag=None): assert not self.active self.flag = flag threading.Thread.start(self) def run(self): assert not self.active ftpd = ftpserver.FTPServer(address, ftp_handler) if self.flag: self.flag.set() self.active = True while self.active: ftpd.server_forever(timeout=1, count=1) ftpd.close() def stop(self): assert self.active self.active = False flag = threading.Event() ftpd = FTPd() ftpd.start(flag) flag.wait() # wait for it to start unittest.main() # run the test suite ftpd.stop() --- /snippet --- Sometimes I get a strange error when all the tests have finished, the server is stopped and Python is exiting: -- Ran 50 tests in 1.515s OK Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPHandler.__del__ of pyftpdlib.ftpserver.FTPHandler connected 127.0.0.1:2 249 at 0xa4b080 ignored Exception exceptions.TypeError: 'NoneType' object is not callable in bound me thod FTPServer.__del__ of pyftpdlib.ftpserver.FTPServer listening 127.0.0.1:543 21 at 0x9e1a30 ignored I sincerely don't know why that happens but it's likely because I'm not using threads properly. My concern is that this could be caused by a sort of race condition (e.g. Python tries to exit when ftpd.close call is not yet completed). I tried to put a lock in the close() method for waiting the run() method to be completed before returning but I didn't solve the problem. Another information, in case it could be useful, is that this seems to happen with Python 2.3 only. By using 2.4 and Python 2.5 I have no problems. In such cases which is the right way for doing things? Using setDaemon(True)? Could someone point me in the right direction? I've always used the asynchronous approach and dealing with threads is a real pain for me. Thanks in advance. -- Giampaolo -- http://mail.python.org/mailman/listinfo/python-list
Re: time.time or time.clock
John Machin wrote: On Jan 14, 7:05 am, Ron Adam [EMAIL PROTECTED] wrote: I'm having some cross platform issues with timing loops. It seems time.time is better for some computers/platforms and time.clock others, but Care to explain why it seems so? it's not always clear which, so I came up with the following to try to determine which. import time # Determine if time.time is better than time.clock # The one with better resolution should be lower. if time.clock() - time.clock() time.time() - time.time(): clock = time.clock else: clock = time.time Will this work most of the time, or is there something better? Manual: clock( ) On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of ``processor time'', depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond. [snip] time( ) Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non- decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. AFAICT that was enough indication for most people to use time.clock on all platforms ... before the introduction of the timeit module; have you considered it? I use it to time a Visual Python loop which controls frame rate updates and set volocities according to time between frames, rather than frame count. The time between frames depends both on the desired frame rate, and the background load on the computer, so it isn't constant. time.clock() isn't high enough resolution for Ubuntu, and time.time() isn't high enough resolution on windows. I do use timeit for bench marking, but haven't tried using in a situation like this. It looks like your method is right sometimes by accident. func() - func() will give a negative answer with a high resolution timer and a meaningless answer with a low resolution timer, where high and low are relative to the time taken for the function call, so you will pick the high resolution one most of the time because the meaningless answer is ZERO (no tick, no change). Some small fraction of the time the low resolution timer will have a tick between the two calls and you will get the wrong answer (-big -small). If the difference is between two high resolution timers then it will be good enough. I think the time between two consectutive func() calls is probably low enough to rule out low resolution timers. In the case of two low resolution timers, both will give a meaningless answer and you will choose arbitrarily. In the case of two low resolution timers, it will use time.time. In this case I probably need to raise an exception. My program won't work correctly with a low resolution timer. Thanks for the feed back, I will try to find something more dependable. Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: time.time or time.clock
Fredrik Lundh wrote: John Machin wrote: AFAICT that was enough indication for most people to use time.clock on all platforms ... which was unfortunate, given that time.clock() isn't even a proper clock on most Unix systems; it's a low-resolution sample counter that can happily assign all time to a process that uses, say, 2% CPU and zero time to one that uses 98% CPU. before the introduction of the timeit module; have you considered it? whether or not timeit suites his requirements, he can at least replace his code with clock = timeit.default_timer which returns a good wall-time clock (which happens to be time.time() on Unix and time.clock() on Windows). Thanks for the suggestion Fredrik, I looked at timeit and it does the following. import sys import time if sys.platform == win32: # On Windows, the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time I was hoping I could determine which to use by the values returned. But maybe that isn't as easy as it seems it would be. Ron -- http://mail.python.org/mailman/listinfo/python-list
(bit)torrent source code help
Hi, Im using windows XP and I was wondering if anyone had any experience in compiling (using py2exe) the official bittorrent client ( http://download.bittorrent.com/dl/BitTorrent-5.2.0.tar.gz ) or any bittorrent client open source and written in python. I ask since I am trying to make several of my own modification to the protocol but the official open source client keeps on giving me missing modules (I have all the required modules and components and it keeps on failing due to platform-based errors) when I try to create an executable of it using py2exe. Can anyone either suggest another source code for a torrent client or any torrent client in python that compiles nicely with py2exe in windows? Thanks Astan -- http://mail.python.org/mailman/listinfo/python-list
Recieving emails in python
I m trying to create something simple a mailing list similar to yahoo groups I m stumbling at the part where the python recieves messages via say [EMAIL PROTECTED] how to make python recieve emails and process it after that it is straight forward processing in python inserting in db etc -- http://mail.python.org/mailman/listinfo/python-list
Re: Recieving emails in python
ok i dont want to write an mta i want to use another mta to recieve emails on say - [EMAIL PROTECTED] so can i start reading the emails to python from that mta How to set this up to read messages from the mta sending out email we are using sendmail so we ll continue using that for now thanks It depends. If you're trying to write a MTA, think about looking at and stealing parts of mailmain and smtpd.py Mailman: http://www.gnu.org/software/mailman/index.html Smtpd:http://barry.warsaw.us/software/Code/smtpd.py If you're going to use someone else as a MTA then just use IMAP or POP to get the mail out, there are IMAP and POP libraries imap: http://docs.python.org/lib/module-imaplib.html pop: http://docs.python.org/lib/module-poplib.html Else, if you're writing this all from scratch, whip out the RFC and start hacking: http://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt --Michael On 1/13/08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I m trying to create something simple a mailing list similar to yahoo groups I m stumbling at the part where the python recieves messages via say [EMAIL PROTECTED] how to make python recieve emails and process it after that it is straight forward processing in python inserting in db etc -- http://mail.python.org/mailman/listinfo/python-list
Re: Recieving emails in python
[EMAIL PROTECTED] wrote: I m trying to create something simple a mailing list similar to yahoo groups I m stumbling at the part where the python recieves messages via say [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] how to make python recieve emails and process it after that it is straight forward processing in python inserting in db etc Can you use POP to access Yahoo groups? If so, this script will get you started: #!/usr/bin/python Redirect the output to a file to capture the contents of the mailbox. host = 'foo.com' account = 'jennyjenny' password = '8675309' import getpass, poplib M = poplib.POP3(host) #M.user(getpass.getuser()) #M.pass_(getpass.getpass()) M.user(account) M.pass_(password) numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: print j -- Shane Geiger IT Director National Council on Economic Education [EMAIL PROTECTED] | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -- http://mail.python.org/mailman/listinfo/python-list
Re: where do my python files go in linux?
On 2008-01-12, Jorgen Bodde [EMAIL PROTECTED] wrote: Question 1. Where do I put the bulk of python scripts in a normal linux environment? Question 2. Should I use *.pyc rather then *.py files to speed up executing as the user cannot write to /usr/bin or any other dir in the system and everytime my app runs it will recompile it Thanks for any advice or maybe a good tutorial how to set up files in a linux environment Rather than re-inventing the wheel, please have a look at distutils: http://docs.python.org/lib/module-distutils.html It does most if not all of the things you want to do. If you want something more advanced, read about eggs. Sincerely, Albert -- http://mail.python.org/mailman/listinfo/python-list
[issue1816] sys.cmd_flags patch
Christian Heimes added the comment: The new patch is using a struct sequence (like the result of os.stat): import sys sys.flags sys.flags (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) dir(sys.flags) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__str__', 'debug', 'division_new', 'division_warning', 'dont_write_bytecode', 'ingnore_environment', 'inspect', 'interactive', 'n_fields', 'n_sequence_fields', 'n_unnamed_fields', 'no_site', 'optimize', 'py3k_warning', 'tabcheck', 'unicode', 'verbose'] sys.flags.debug 0 Please ignore the other files. They are part of my second PEP. Added file: http://bugs.python.org/file9149/trunk_sys_flags.patch __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1816 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1550] help('modules') broken by several 3rd party libraries (svn patch attached)
Ka-Ping Yee added the comment: Committed the patch in revision 59939. I'm not clear how it was determined that importing every module was necessary in order to list the modules or scan their synopsis lines (this seems to have happened in revision 45510). This can probably be made more efficient in the future. -- resolution: - accepted status: open - closed __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1550 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1367711] Remove usage of UserDict from os.py
Andrew Dalke added the comment: Ahh, so the bug here that the environ dict should use neither UserDict nor dict, it should implement the core {get,set,del}item and keys and use DictMixin. Martin mentioned that the patch doesn't support setdefault. He didn't note though that the current code also doesn't support the dictionary interface consistently. This shows a problem with popitem. import os os.environ[USER] 'dalke' os.environ[USER] = nobody os.system(echo $USER) nobody 0 del os.environ[USER] os.system(echo $USER) 0 os.environ[USER] = dalke while os.environ: print os.environ.popitem() ... ('GROUP', 'staff') ('XDG_DATA_HOME', '/Users/dalke/.local/share') ('TERM_PROGRAM_VERSION', '133') ('CVS_RSH', 'ssh') ('LOGNAME', 'dalke') ('USER', 'dalke') ... removed for conciseness ... ('QTDIR', '/usr/local/qt') os.system(echo $USER) dalke 0 Not enough people know about DictMixin. _ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1367711 _ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1700288] Armin's method cache optimization updated for Python 2.6
Georg Brandl added the comment: Backed out again in r59940 -- test_ctypes fails in test_incomplete.py. Armin reports that with his original patch on 2.4, this test passes. _ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1700288 _ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1700288] Armin's method cache optimization updated for Python 2.6
Kevin Jacobs added the comment: All tests passed when I first ported Armin's patch to 2.6. I'll have a chance to look into this later in the week. If anyone gets to it first, please summarize your findings here to avoid duplication of effort. _ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1700288 _ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1472] Small bat files to build docs on Windows
Georg Brandl added the comment: FTR, I'm currently removing all 2.5isms from Sphinx. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1472 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1814] Victor Stinner's GMP patch for longs
Christian Heimes added the comment: Why was the mpz module removed from Python 2.4 in the first place? 2.3 has it. I see three way to implement the option: * Let somebody implement a mpz type as a 3rd party extension. * Let somebody implement a mpt type and ship it with the Python core * Let somebody write a patch that replaces the built-in long type implementation with a GMP based implementation (./configure --with-gmp-integer) __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1814 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1816] sys.cmd_flags patch
Guido van Rossum added the comment: Can't you use a namedtuple? Then printing it would show the names of the flags... __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1816 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1816] sys.cmd_flags patch
Christian Heimes added the comment: Guido van Rossum wrote: Can't you use a namedtuple? Then printing it would show the names of the flags... ... and increase the startup costs of Python by loading several additional modules. The collections module imports _collections, operator and keyword. I'd rather see a better repr function for the sequence types. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1816 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1816] sys.cmd_flags patch
Guido van Rossum added the comment: I'd rather see a better repr function for the sequence types. Agreed. It's kind of unfortunate that we have two implementations for the same concept, one in C and one in Python. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1816 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1816] sys.cmd_flags patch
Christian Heimes added the comment: I've coded sys.flags for my per-user site-packages PEP. I could make it a function but the function would be called by site.py on every startup. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1816 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1778] SyntaxError.offset sometimes wrong
Achim Gaedke added the comment: sometimes offset is None... Example: def blub(bla, blub=None, blabla): bla causes: non-default argument follows default argument Added file: http://bugs.python.org/file9150/compile_test.py __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1778 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1818] Add named tuple reader to CSV module
New submission from Raymond Hettinger: Here's a proof-of-concept patch. If approved, will change from generator form to match the other readers and will add a test suite. The idea corresponds to what is currently done by the dict reader but returns a space and time efficient named tuple instead of a dict. Field order is preserved and named attribute access is supported. A writer is not needed because named tuples can be feed into the existing writer just like regular tuples. -- assignee: barry components: Library (Lib) files: ntreader.diff messages: 59866 nosy: barry, rhettinger severity: normal status: open title: Add named tuple reader to CSV module versions: Python 2.6 Added file: http://bugs.python.org/file9151/ntreader.diff __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1818 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1771] Remove cmp parameter to list.sort() and builtin.sorted()
Raymond Hettinger added the comment: Let's do this. It is a nice simplification and makes the sort tools easier to learn and use. -- assignee: - rhettinger resolution: - accepted __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1771 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue923643] long - byte-string conversion
Antoine Pitrou added the comment: Unless I'm mistaken, the patch provides only half of the solution: the stringToLong part, but not longToString. I agree this feature is interesting, not for optimization but becomes it avoids using clunky ways (long - hex - bin) to implement something simple. However, perhaps making it part of either the binascii or the struct module would allow more formatting choices (e.g. big-endian or little-endian, fixed-length or not). For example in cryptography you would want a byte string of a fixed size even if your 512-bit number happens to have its 8 most significant bits set to zero. -- nosy: +pitrou Tracker [EMAIL PROTECTED] http://bugs.python.org/issue923643 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1816] sys.cmd_flags patch
Christian Heimes added the comment: Does anybody see a problem with this repr slot implementation for structseq? It gives this output: os.stat(.) posix.stat_result st_mode=16832, st_ino=11666571L, st_dev=65025L, st_nlink=20, st_uid=1000, st_gid=1000, st_size=4096L, st_atime=1200261754, st_mtime=1200261721, st_ctime=1200261721 static PyObject * structseq_repr(PyStructSequence *obj) { PyObject *tup, *val, *repr; PyTypeObject *typ = Py_TYPE(obj); int i, len; char buf[250+5]; /* ...\0 */ char *cname, *crepr; char *pbuf = buf; char *endbuf = buf[250]; *pbuf++ = ''; strncpy(pbuf, typ-tp_name, 50); pbuf += strlen(typ-tp_name) 50 ? 50 : strlen(typ-tp_name); *pbuf++ = ' '; if ((tup = make_tuple(obj)) == NULL) { return NULL; } for (i=0; i VISIBLE_SIZE(obj); i++) { cname = typ-tp_members[i].name; val = PyTuple_GetItem(tup, i); if (cname == NULL || val == NULL) { return NULL; } repr = PyObject_Repr(val); if (repr == NULL) { Py_DECREF(tup); return NULL; } crepr = PyString_AsString(repr); if (crepr == NULL) { Py_DECREF(tup); Py_DECREF(repr); return NULL; } len = strlen(cname) + strlen(crepr) + 3; if ((pbuf+len) endbuf) { strcpy(pbuf, cname); pbuf += strlen(cname); *pbuf++ = '='; strcpy(pbuf, crepr); pbuf += strlen(crepr); *pbuf++ = ','; *pbuf++ = ' '; Py_DECREF(repr); } else { strcpy(pbuf, ...); pbuf += 5; Py_DECREF(repr); break; } } Py_DECREF(tup); pbuf-=2; *pbuf++ = ''; *pbuf = '\0'; repr = PyString_FromString(buf); return repr; } __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1816 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1682] Move Demo/classes/Rat.py to Lib/rational.py and fix it up.
Jeffrey Yasskin added the comment: _binary_float_to_ratio: Oops, fixed. Rational() now equals 0, but I'd like to postpone Rational('3/2') until there's a demonstrated need. I don't think it's as common a use as int('3'), and there's more than one possible format, so some real world experience will help (that is, quite possibly not in 2.6/3.0). I'm also postponing Rational(instance_of_numbers_Rational). +/-inf and nan are gone, and hash is fixed, at least until the next bug. :) Good idea about using tuple. Parentheses in str() help with reading things like %s**2%Rational(3,2), which would otherwise format as 3/2**2. I don't feel strongly about this. Equality and the comparisons now work for complex, but their implementations make me uncomfortable. In particular, two instances of different Real types may compare unequal to the nearest float, but equal to each other and have similar but inconsistent problems with =. I can trade off between false ==s and false !=s, but I don't see a way to make everything correct. We could do better by making the intermediate representation Rational instead of float, but comparisons are inherently doomed to run up against the fact that equality is uncomputable on the computable reals, so it's probably not worthwhile to spend too much time on this. I've added a test that float(Rational(long('2'*400+'7'), long('3'*400+'1'))) returns 2.0/3. This works without any explicit scaling on my part because long.__truediv__ already handles it. If there's something else I'm doing wrong around here, I'd appreciate a failing test case. The open issues I know of are: * Is it a good idea to have both numbers.Rational and rational.Rational? Should this class have a different name? * trim and approximate: Let's postpone them to a separate patch (I do think at least one is worth including in 2.6+3.0). So that you don't waste time on them, we already have implementations in the sandbox and (probably) a good-enough explanation at http://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations. Thanks for the offer to help out with them. :) * Should Rational.from_float() exist and with the current name? If there's any disagreement, I propose to rename it to Rational._from_float() to discourage use until there's more consensus. * Rational.from_decimal(): punted to a future patch. I favor this for 2.6+3.0. * Rational('3/2') (see above) I think this is close enough to correct to submit and fix up the remaining problems in subsequent patches. If you agree, I'll do so. Added file: http://bugs.python.org/file9152/rational.patch __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1682 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1799] Per user site-packages and setup.py install --user patch
Christian Heimes added the comment: The new patch adds the -s option, checks for getuid() == geteuid() and adds sys.flags (see #1816). Added file: http://bugs.python.org/file9153/trunk_usersite3.patch __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1799 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com