Introduction to Python Masterclass, May 11-13, 2009 in Chicago
* * Introduction to Python Masterclass * * May 11-13, 2009 Chicago, Illinois with David Beazley, author Python Essential Reference http://www.dabeaz.com/chicago Take your Python programming skills to the next level. David Beazley is pleased to offer a comprehensive hands-on course for programmers, scientists, and engineers who want to master the essential elements of Python programming in order to solve real-world problems in data processing, systems administration, databases, and software integration. If you are new to Python, this class will quickly bring you up to speed and allow you to immediately apply Python to problems you face everyday. If you already know some Python, this course will give you new insights, inspire you to improve the programs you have already written, and give you a roadmap towards Python 3 and beyond. This is the same class that Dave has taught on-site to more than 400 students including rocket scientists, robot builders, hardware engineers, financial wizards, and web programmers. Forget about the midwest winter and mind-numbing suburban technology parks---the venue for this class is centrally located in the heart of Chicago's vibrant downtown financial/theater district. When class is not in session, you will be just steps away from many of Chicago's most famous cultural attractions, shopping districts, and lakefront parks. Come prepared for three days of serious Python instruction and springtime urban exploration. More details about the class including discounts for early registration can be found at: http://www.dabeaz.com/chicago I hope to see you there! -- Dave Beazley http://www.dabeaz.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Subprocess module: running an interactive shell
On Mar 13, 6:39 pm, Roman Medina-Heigl Hernandez ro...@rs-labs.com wrote: Hi, I'm experimenting with Python and I need a little help with this. What I'd like is to launch an interactive shell, having the chance to send first several commands from python. I've written the following code: = #!/usr/bin/env python import sys, subprocess exe = /bin/sh params = -i -i says shell to be interactive. So looks like it is directly trying to read from the terminal. proc = subprocess.Popen([exe, params], stdin=subprocess.PIPE) proc = subprocess.Popen([exe,], stdin=subprocess.PIPE) works for me; but if there is an error 'sh' terminates. If you want to simulate interactive, explore the pexpect module. proc.stdin.write(id\n) while True: line = sys.stdin.readline() if not line: note that a simple enter terminates the shell which you may not want. break proc.stdin.write(line) sys.exit() = The problem is that when I launch it, python proggy is automatically suspended. The output I got is: ro...@rslabs:~/pruebas$ ./shell.py ro...@rslabs:~/pruebas$ uid=1000(roman) gid=1000(roman) groups=1000(roman) ro...@rslabs:~/pruebas$ [2]+ Stopped ./shell.py ro...@rslabs:~/pruebas$ Why and how to fix it? Would you suggest a better and more elegant way to do what I want? As I see it, 'sh' is attempting to read from the keyboard and not from stdin. Karthik Thank you. -- Saludos, -Roman PGP Fingerprint: 09BB EFCD 21ED 4E79 25FB 29E1 E47F 8A7D EAD5 6742 [Key ID: 0xEAD56742. Available at KeyServ] -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
[Lie Ryan] My proposition is: make the format specifier a simpler API to locale aware You do know that we already have one, right? That's what the existing n specifier does. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find in in the documentation
Colin J. Williams wrote: Piet van Oostrum wrote: tinn...@isbd.co.uk (t) wrote: t I've had this trouble before, how do I find the details of how in t works in the documentation. E.g. the details of:- t if string in bigstring: t It gets a mention in the if section but not a lot. It is explained in The Python Language Reference, chapter Expressions, section Comparisons. At least that's were it is in the 2.6 doc. Lots of people have been very helpful but isn't the OP's real problem that in is not included in the 2.6.1 Help index? Well, this may not solve the OP's problem, but the current (2.7a0) .chm file has a much better index for operators and keywords. And in is in there. If you're interested in comparing, there's a copy here: http://timgolden.me.uk/python/downloads/snapshots/trunk/Python27a0.chm TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: python book for a C programmer
On Fri, Mar 13, 2009 at 10:29 PM, Paul Rubin http wrote: Saurabh nirkh...@gmail.com writes: Hi all, I am an experienced C programmer, I have done some perl code as well. But while thinking about large programs,I find perl syntax a hinderance. I would say read the online tutorial, then Python in a Nutshell. Wholeheartedly seconded! Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Integer arithmetic in hardware descriptions
I am the author of MyHDL, a Python package that turns Python into a hardware description language (HDL). Integer arithmetic is very important in hardware design, but with traditional HDLs such as Verilog and VHDL it is complicated and confusing. MyHDL has a better solution, inspired by Python's native integer type, int. I have written an essay that explores these issues in detail: http://www.jandecaluwe.com/hdldesign/counting.html -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Python as a hardware description language: http://www.myhdl.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads and temporary files
In message 302dd4f5-e9b3-4b0a-b80c- ae43810d8...@e18g2000yqo.googlegroups.com, aiwarrior wrote: I recently am meddling with threads and wanted to make a threaded class that instead of processing anything just retrieves data from a file and returns that data to a main thread that takes all the gathered data and concatenates it sequentially. Any reason you're using threads instead of processes? -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
I don't get *why* someone would like to write that. Does it look cool? Is it some kind of Look, ma, I know those hidden names! syndrome? Is it contagious? I think thats what it is. It does look cool, thats for telling me about the fact that prevents the interpreter from doing many optimizations... that makes sense to me, where would I read more about python optimizations? I want to see code more, I like code, comments are good too :) I have this piece of code I would like to turn into a generator, can some one please help me do it? I want to make it very optimized. The data comes from a options file that is parsed and used for this header/field function mapping function . I need to generate this, unless you advise against it then what are my options? How to wrap my head around this? def loop_lines(self): self.soc.me_him(['ENTER:',__name__],self.func_me_color) print self.lines for k in range(len(self.lines)): #for every line in csv file self.line=self.lines[k] for optv in self.order: for optvv in self._optv[optv][headers]: if self._optv[optv][headers][optvv]!=: _optvk=string.split(self._optv[optv][headers][optvv],,) for optvk in _optvk: for optvvv in self._optv[optv][mappings]: if optvk == optvvv: if self._optv[optv][mappings][optvvv].find(self.fun.func) = 0: self.field=optvvv self.value=self.parsed[k][optvv].replace('', '\\').replace(', \\') try: exec (self._optv[optv][mappings][optvvv]) #execute custom function self.last_value=self.value except NameError, e: self.soc.w([\n\nERROR: %s \n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER % e],'white_on_red') sys.exit(1) #print self.opt['data'] #self.opt['data'][self.field]=self.fun.data[self.field] #print self.opt['data'] else: #self.soc.write([FUNC NOT FOUND:,pfhpv[pfhpvi],self._pfmp[pfhpv[pfhpvi]]],'red') #if self._pfmp[pfhpv[pfhpvi]]== pfhp: self.opt['data']['defaults'][optv][optvvv]=self.value self.last_item=self.value for ff in self.final_funcs.keys(): if self.final_funcs[ff]: exec ( ff ) self.soc.me_him(['EXIT:',__name__],self.func_me_color) Thank you, -Alex Goretoy http://www.goretoy.com On Fri, Mar 13, 2009 at 11:56 PM, Gabriel Genellina gagsl-...@yahoo.com.arwrote: prevents the interpreter from doing many optimizations... -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
I'm actually still getting to this section of my code, I've been working a logging,stdout colors lately, Although I am going to need __import__ in several places in this program -Alex Goretoy http://www.goretoy.com On Sat, Mar 14, 2009 at 3:05 AM, alex goretoy aleksandr.gore...@gmail.comwrote: I don't get *why* someone would like to write that. Does it look cool? Is it some kind of Look, ma, I know those hidden names! syndrome? Is it contagious? I think thats what it is. It does look cool, thats for telling me about the fact that prevents the interpreter from doing many optimizations... that makes sense to me, where would I read more about python optimizations? I want to see code more, I like code, comments are good too :) I have this piece of code I would like to turn into a generator, can some one please help me do it? I want to make it very optimized. The data comes from a options file that is parsed and used for this header/field function mapping function . I need to generate this, unless you advise against it then what are my options? How to wrap my head around this? def loop_lines(self): self.soc.me_him(['ENTER:',__name__],self.func_me_color) print self.lines for k in range(len(self.lines)): #for every line in csv file self.line=self.lines[k] for optv in self.order: for optvv in self._optv[optv][headers]: if self._optv[optv][headers][optvv]!=: _optvk=string.split(self._optv[optv][headers][optvv],,) for optvk in _optvk: for optvvv in self._optv[optv][mappings]: if optvk == optvvv: if self._optv[optv][mappings][optvvv].find(self.fun.func) = 0: self.field=optvvv self.value=self.parsed[k][optvv].replace('', '\\').replace(', \\') try: exec (self._optv[optv][mappings][optvvv]) #execute custom function self.last_value=self.value except NameError, e: self.soc.w([\n\nERROR: %s \n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER % e],'white_on_red') sys.exit(1) #print self.opt['data'] #self.opt['data'][self.field]=self.fun.data[self.field] #print self.opt['data'] else: #self.soc.write([FUNC NOT FOUND:,pfhpv[pfhpvi],self._pfmp[pfhpv[pfhpvi]]],'red') #if self._pfmp[pfhpv[pfhpvi]]== pfhp: self.opt['data']['defaults'][optv][optvvv]=self.value self.last_item=self.value for ff in self.final_funcs.keys(): if self.final_funcs[ff]: exec ( ff ) self.soc.me_him(['EXIT:',__name__],self.func_me_color) Thank you, -Alex Goretoy http://www.goretoy.com On Fri, Mar 13, 2009 at 11:56 PM, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: prevents the interpreter from doing many optimizations... -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
I can show you people more code if you want :) I like to learn -Alex Goretoy http://www.goretoy.com On Sat, Mar 14, 2009 at 3:09 AM, alex goretoy aleksandr.gore...@gmail.comwrote: I'm actually still getting to this section of my code, I've been working a logging,stdout colors lately, Although I am going to need __import__ in several places in this program -Alex Goretoy http://www.goretoy.com On Sat, Mar 14, 2009 at 3:05 AM, alex goretoy aleksandr.gore...@gmail.com wrote: I don't get *why* someone would like to write that. Does it look cool? Is it some kind of Look, ma, I know those hidden names! syndrome? Is it contagious? I think thats what it is. It does look cool, thats for telling me about the fact that prevents the interpreter from doing many optimizations... that makes sense to me, where would I read more about python optimizations? I want to see code more, I like code, comments are good too :) I have this piece of code I would like to turn into a generator, can some one please help me do it? I want to make it very optimized. The data comes from a options file that is parsed and used for this header/field function mapping function . I need to generate this, unless you advise against it then what are my options? How to wrap my head around this? def loop_lines(self): self.soc.me_him(['ENTER:',__name__],self.func_me_color) print self.lines for k in range(len(self.lines)): #for every line in csv file self.line=self.lines[k] for optv in self.order: for optvv in self._optv[optv][headers]: if self._optv[optv][headers][optvv]!=: _optvk=string.split(self._optv[optv][headers][optvv],,) for optvk in _optvk: for optvvv in self._optv[optv][mappings]: if optvk == optvvv: if self._optv[optv][mappings][optvvv].find(self.fun.func) = 0: self.field=optvvv self.value=self.parsed[k][optvv].replace('', '\\').replace(', \\') try: exec (self._optv[optv][mappings][optvvv]) #execute custom function self.last_value=self.value except NameError, e: self.soc.w([\n\nERROR: %s \n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER % e],'white_on_red') sys.exit(1) #print self.opt['data'] #self.opt['data'][self.field]=self.fun.data[self.field] #print self.opt['data'] else: #self.soc.write([FUNC NOT FOUND:,pfhpv[pfhpvi],self._pfmp[pfhpv[pfhpvi]]],'red') #if self._pfmp[pfhpv[pfhpvi]]== pfhp: self.opt['data']['defaults'][optv][optvvv]=self.value self.last_item=self.value for ff in self.final_funcs.keys(): if self.final_funcs[ff]: exec ( ff ) self.soc.me_him(['EXIT:',__name__],self.func_me_color) Thank you, -Alex Goretoy http://www.goretoy.com On Fri, Mar 13, 2009 at 11:56 PM, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: prevents the interpreter from doing many optimizations... -- http://mail.python.org/mailman/listinfo/python-list
Re: finally successful in ods with python, just one help needed.
On Thu, 2009-03-12 at 14:49 -0700, John Machin wrote: I see that you haven't had the evil spirits exorcised from your mail/ news client ... it's hijacked a thread again :-( don't worry, won't happen this time. It seams I did some thing wrong with the settings and it drops out mails. Now the problem is sorted out. The cell merging is happening but no text centering in those merged cells. If any one is interested I can send my part of code snippid. to just tell in short, it just has the sudo code as create document create a style to set centered text create table and add rows to which cells are added. the cell has a p (paragraph ) element with the style of centered text applied. cells are merged but no centering happens. Please let me know if any one wanted me to send the code off the list. Even better, if some one has a code snippid which can just do that. You might like to try: (a) checking that you can get text centred in an UNmerged cell Tryed, it works perfectly. The text gets centered in an unmerged cell. (b) using Calc, creating a small ods file with your desired formatting, then comparing the XML in that ods file with the one your script has created This is the first thing I tryed and even got some insight into the xml. However when I apply the same elements and attributes to the one I am creating with odfpy, I get attribute not allowed errors. If some one is interested to look at the code, please let me know, I can send an attachment off the list so that others are not forced to download some thing they are not concerned about. (c) contacting the author/maintainer of the odfpy package Done and awaiting the reply for last 4 days. It was then that I came to this thread. happy hacking. Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
This is a chunk of what its starting to look like now, thanks from colors import _available_colors as _ck from has_colors import _has_colors as _ha from log import _brush as _er class stdout_colors(object): def __init__(self,colors_active=1,output_caller=1,caller_color=red,default=1, show_lineno_write=1,show_lineno_caller=1,break_all=1, logging=1,log_type=INFO,depth=10): self.caller_color = caller_color #stdout_colors function caller called output color self.output_caller = output_caller # output caller and called function self.colors_active = colors_active #active colors for output self.colors = _ck().colors crack=_er(colors_active,default,show_lineno_write,show_lineno_caller, break_all,logging,log_type,depth) #Thanks Gabriel Genellina, no crack was smoked during the making #list( ( self.__setattr__(x.replace(b_,),getattr(B,x)) for x in dir(B) if x.startswith(b_) ) ) for smoke in dir(crack): if smoke.startswith(b_): setattr(self, smoke[2:], getattr(crack, smoke)) -Alex Goretoy http://www.goretoy.com On Sat, Mar 14, 2009 at 3:13 AM, alex goretoy aleksandr.gore...@gmail.comwrote: I can show you people more code if you want :) I like to learn -Alex Goretoy http://www.goretoy.com On Sat, Mar 14, 2009 at 3:09 AM, alex goretoy aleksandr.gore...@gmail.com wrote: I'm actually still getting to this section of my code, I've been working a logging,stdout colors lately, Although I am going to need __import__ in several places in this program -Alex Goretoy http://www.goretoy.com On Sat, Mar 14, 2009 at 3:05 AM, alex goretoy aleksandr.gore...@gmail.com wrote: I don't get *why* someone would like to write that. Does it look cool? Is it some kind of Look, ma, I know those hidden names! syndrome? Is it contagious? I think thats what it is. It does look cool, thats for telling me about the fact that prevents the interpreter from doing many optimizations... that makes sense to me, where would I read more about python optimizations? I want to see code more, I like code, comments are good too :) I have this piece of code I would like to turn into a generator, can some one please help me do it? I want to make it very optimized. The data comes from a options file that is parsed and used for this header/field function mapping function . I need to generate this, unless you advise against it then what are my options? How to wrap my head around this? def loop_lines(self): self.soc.me_him(['ENTER:',__name__],self.func_me_color) print self.lines for k in range(len(self.lines)): #for every line in csv file self.line=self.lines[k] for optv in self.order: for optvv in self._optv[optv][headers]: if self._optv[optv][headers][optvv]!=: _optvk=string.split(self._optv[optv][headers][optvv],,) for optvk in _optvk: for optvvv in self._optv[optv][mappings]: if optvk == optvvv: if self._optv[optv][mappings][optvvv].find(self.fun.func) = 0: self.field=optvvv self.value=self.parsed[k][optvv].replace('', '\\').replace(', \\') try: exec (self._optv[optv][mappings][optvvv]) #execute custom function self.last_value=self.value except NameError, e: self.soc.w([\n\nERROR: %s \n\nFUNCTION or VARIABLE IS DEFINED IN JAR_CONTROLLER % e],'white_on_red') sys.exit(1) #print self.opt['data'] #self.opt['data'][self.field]=self.fun.data[self.field] #print self.opt['data'] else: #self.soc.write([FUNC NOT FOUND:,pfhpv[pfhpvi],self._pfmp[pfhpv[pfhpvi]]],'red') #if self._pfmp[pfhpv[pfhpvi]]== pfhp: self.opt['data']['defaults'][optv][optvvv]=self.value self.last_item=self.value for ff in self.final_funcs.keys(): if self.final_funcs[ff]: exec ( ff ) self.soc.me_him(['EXIT:',__name__],self.func_me_color) Thank you, -Alex Goretoy http://www.goretoy.com On Fri, Mar 13, 2009 at 11:56 PM, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: prevents the interpreter from doing many optimizations... -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: loading file before entering mainloop
Peter Billam wrote: I've got this tkinter program which allows you to load a file with File/LoadFile or Ctrl-L or from the Alt-F menu, as usual. But I'd also like to be able to invoke it with: shellprompt midimix x.mid and have it invoke its usual loadFile method on x.mid But with the top-level code: application = tkinter.Tk() window = MainWindow(application) if (len(sys.argv) 1) and os.path.exists(sys.argv[1]): window.loadFile(sys.argv[1]) application.mainloop() it crashes: File ./midimix, line 465, in loadFile space0.grid(row=grid_row, pady=round(0.5*(ymid[track_num]-ymid[track_num-1]))-50) File /usr/local/lib/python3.0/tkinter/__init__.py, line 1845, in grid_configure + self._options(cnf, kw)) _tkinter.TclError: bad pad value -50: must be positive screen distance presumably because the window doesn't have dimensions before mainloop is entered. Can I force the window to be laid out before entering mainloop? Or can I invoke loadFile() after mainloop has started ? The latter. Try application = tkinter.Tk() window = MainWindow(application) if (len(sys.argv) 1) and os.path.exists(sys.argv[1]): application.after_idle(window.loadFile, sys.argv[1]) application.mainloop() Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
John Nagle na...@animats.com wrote: Yes. In COBOL, one writes PICTURE $999,999,999.99 which is is way ahead of most of the later approaches. That was fixed width. For zero suppression: PIC ,$$$,$99.99 This will format 1000 as $1,000.00 For fixed width zero suppression: PIC $ZZZ,ZZZ,Z99.99 gives a fixed width field - $ 1,000.00 with a fixed width font, this will line the column up, so that the decimals are under each other. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
String to sequence
How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] Thanks a lot, Mattia -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
a = eval([%s] % 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC','EGC','SXF','BZR','BIQ','BLL','BHX','BLQ') a ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC', 'EGC', 'SXF', 'BZR', 'BIQ', 'BLL', 'BHX', 'BLQ'] On Sat, Mar 14, 2009 at 5:09 PM, mattia ger...@gmail.com wrote: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] Thanks a lot, Mattia -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: loading file before entering mainloop
Peter Billam wrote: window = MainWindow(application) if (len(sys.argv) 1) and os.path.exists(sys.argv[1]): window.loadFile(sys.argv[1]) application.mainloop() File ./midimix, line 465, in loadFile space0.grid(row=grid_row, pady=round(0.5*(ymid[track_num]-ymid[track_num-1]))-50) ... _tkinter.TclError: bad pad value -50: must be positive screen distance presumably because the window doesn't have dimensions before mainloop is entered. Can I force the window to be laid out before entering mainloop? Or can I invoke loadFile() after mainloop has started ? On 2009-03-14, Peter Otten __pete...@web.de wrote: The latter. Try application.after_idle(window.loadFile, sys.argv[1]) Thank you! That almost worked :-) It opened a window (which it didn't do last time), and it laid out the frames and so on apparently OK, and even posted a Loaded v.mid message on the StatusBar, but then just drew a couple of zero-thickness lines right at the top of the canvas, and failed with the same message: File ./midimix, line 465, in loadFile space0.grid(row=grid_row, pady=round(0.5*(ymid[track_num]-ymid[track_num-1]))-50) File /usr/local/lib/python3.0/tkinter/__init__.py, line 1845, in grid_configure + self._options(cnf, kw)) _tkinter.TclError: bad pad value -50: must be positive screen distance but I say almost because I googled after_idle, and the very similar: application.after(500, window.loadFile, sys.argv[1]) does work, exactly as intended :-) except of course that it's a race condition, and will fail for very impatient people or on very slow machines. On my machine it still works with 20ms, but fails with 10ms. Is there one extra magic trick I need to know? I also tried invoking after_idle on the canvas widget: window.canvas.after_idle(window.loadFile, sys.argv[1]) but that fails with the same message. (I am using python 3.0.1 in case that's, er, relevant.) Thanks for your help, Regards, Peter -- Peter Billam www.pjb.com.auwww.pjb.com.au/comp/contact.html -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
mattia wrote: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] import string string.split(a,b,c, ',') Now, I'm not 100% clear if this fits your above example because it's not clear what of the above is Python code and what is actual string content, but I hope this will get you started. cheers! Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
2009/3/14 mattia ger...@gmail.com: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] Thanks a lot, Mattia -- http://mail.python.org/mailman/listinfo/python-list Apart from the obvious and rather discouraged list(eval('AAR','ABZ','AGA','AHO')) ['AAR', 'ABZ', 'AGA', 'AHO'] you may try e.g.: [item[1:-1] for item in 'AAR','ABZ','AGA','AHO'.split(,)] ['AAR', 'ABZ', 'AGA', 'AHO'] hth, vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
mattia wrote: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' csv.reader(StringIO.StringIO(s), quotechar=').next() ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] or s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' list(compile(s, nofile, eval).co_consts[-1]) ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
Il Sat, 14 Mar 2009 10:24:38 +0100, Ulrich Eckhardt ha scritto: mattia wrote: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] import string string.split(a,b,c, ',') Now, I'm not 100% clear if this fits your above example because it's not clear what of the above is Python code and what is actual string content, but I hope this will get you started. cheers! Uli Well, it was quite easy (although I'm new to python ;-)). I scrape a list of flights by their code [A-Z]{3} and then I save them into a sequence. Reading the documentation now I've got: dests = dests.replace(', ) dests = dests.split(,) and everything is OK -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: loading file before entering mainloop
Peter Billam wrote: Peter Billam wrote: window = MainWindow(application) if (len(sys.argv) 1) and os.path.exists(sys.argv[1]): window.loadFile(sys.argv[1]) application.mainloop() File ./midimix, line 465, in loadFile space0.grid(row=grid_row, pady=round(0.5*(ymid[track_num]-ymid[track_num-1]))-50) ... _tkinter.TclError: bad pad value -50: must be positive screen distance presumably because the window doesn't have dimensions before mainloop is entered. Can I force the window to be laid out before entering mainloop? Or can I invoke loadFile() after mainloop has started ? On 2009-03-14, Peter Otten __pete...@web.de wrote: The latter. Try application.after_idle(window.loadFile, sys.argv[1]) Thank you! That almost worked :-) It opened a window (which it didn't do last time), and it laid out the frames and so on apparently OK, and even posted a Loaded v.mid message on the StatusBar, but then just drew a couple of zero-thickness lines right at the top of the canvas, and failed with the same message: File ./midimix, line 465, in loadFile space0.grid(row=grid_row, pady=round(0.5*(ymid[track_num]-ymid[track_num-1]))-50) File /usr/local/lib/python3.0/tkinter/__init__.py, line 1845, in grid_configure + self._options(cnf, kw)) _tkinter.TclError: bad pad value -50: must be positive screen distance but I say almost because I googled after_idle, and the very similar: application.after(500, window.loadFile, sys.argv[1]) does work, exactly as intended :-) except of course that it's a race condition, and will fail for very impatient people or on very slow machines. On my machine it still works with 20ms, but fails with 10ms. Is there one extra magic trick I need to know? I also tried invoking after_idle on the canvas widget: window.canvas.after_idle(window.loadFile, sys.argv[1]) but that fails with the same message. (I am using python 3.0.1 in case that's, er, relevant.) Thanks for your help, Regards, Peter Well, I don't know where the ymid[...] values come from. If you can guarantee that ymid[track_num] - ymit[track_num-1] 50 at some point you could reschedule loadFile() from within loadFile() and return immediately as long as that condition is not met. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Subprocess module: running an interactive shell
Karthik Gurusamy escribió: On Mar 13, 6:39 pm, Roman Medina-Heigl Hernandez ro...@rs-labs.com wrote: Hi, I'm experimenting with Python and I need a little help with this. What I'd like is to launch an interactive shell, having the chance to send first several commands from python. I've written the following code: = #!/usr/bin/env python import sys, subprocess exe = /bin/sh params = -i -i says shell to be interactive. So looks like it is directly trying to read from the terminal. Well, then the question will be: is there any way to tell python to directly map the terminal to the subprocess? proc = subprocess.Popen([exe, params], stdin=subprocess.PIPE) proc = subprocess.Popen([exe,], stdin=subprocess.PIPE) works for me; but if there is an error 'sh' terminates. If you want to simulate interactive, explore the pexpect module. I'll get it a try :))) proc.stdin.write(id\n) while True: line = sys.stdin.readline() if not line: note that a simple enter terminates the shell which you may not want. Test my code and you'll see that this is not true :) When you hit enter line will contain '\n' so it's not empty. break proc.stdin.write(line) Btw, another curiosity I have: is it possible to make a print not automatically add \n (which is the normal case) neither (which happens when you add a , to the print sentence)? I found an alternative not using print at all, eg: sys.stdout.write(K). But it resulted strange to me having to do that trick :) Thank you for all your comments and comprenhension. -r sys.exit() = The problem is that when I launch it, python proggy is automatically suspended. The output I got is: ro...@rslabs:~/pruebas$ ./shell.py ro...@rslabs:~/pruebas$ uid=1000(roman) gid=1000(roman) groups=1000(roman) ro...@rslabs:~/pruebas$ [2]+ Stopped ./shell.py ro...@rslabs:~/pruebas$ Why and how to fix it? Would you suggest a better and more elegant way to do what I want? As I see it, 'sh' is attempting to read from the keyboard and not from stdin. Karthik Thank you. -- Saludos, -Roman PGP Fingerprint: 09BB EFCD 21ED 4E79 25FB 29E1 E47F 8A7D EAD5 6742 [Key ID: 0xEAD56742. Available at KeyServ] -- http://mail.python.org/mailman/listinfo/python-list -- Saludos, -Roman PGP Fingerprint: 09BB EFCD 21ED 4E79 25FB 29E1 E47F 8A7D EAD5 6742 [Key ID: 0xEAD56742. Available at KeyServ] -- http://mail.python.org/mailman/listinfo/python-list
Re: c++ extension, problem passing argument
On 14 Mar, 02:08, Aaron Brady castiro...@gmail.com wrote: On Mar 13, 5:42 pm, Matteo tadweles...@gmail.com wrote: On 13 Mar, 22:35, Aaron Brady castiro...@gmail.com wrote: On Mar 13, 1:34 pm, Matteo tadweles...@gmail.com wrote: hmmm... looks like SWIG has a problem with double pointers. I googled around a bit and found: http://osdir.com/ml/programming.swig/2003-02/msg00029.html anyone knows how to write a small wrapper to do the appropriate dereferencing? 'ctypes' may be able to do it. I've done something like this in the past: double_ptr= ctypes._cast( PyObject, sing_ptr ) Up your alley? Thanks for your suggestions, but still no luck here. ctypes appears to work only with its own types, I tried its cast, byref and pointer functions, but only received TypeError exceptions such as: TypeError: byref() argument must be a ctypes instance, not 'list' TypeError: _type_ must have storage info This is getting really annoying :( The following link may contain useful info, but I find it somewhat obscurehttp://embedded.eecs.berkeley.edu/Alumni/pinhong/scriptEDA/pyTypemapF... I'm on my last one (suggestion). To get a pointer to the actual address of an mmap instance, (and access it's 'data' attribute), I used the following: from _ctypes import _cast_addr from ctypes import * _mmap_cast= _data_cast= PYFUNCTYPE(py_object, py_object, py_object, py_object)(_cast_addr) _offset_cast= _record_cast = PYFUNCTYPE(py_object, c_void_p, py_object, py_object)(_cast_addr) class MMAP(Structure): _fields_= [ #(next,c_int), #(prev,c_int), (refcnt,c_int), (type,c_int), (data,c_long) ] def pdata( map ): a= _data_cast( map, None, POINTER( MMAP ) ) return a.contents.data It worked on my machine in 2.5, no promises. It was a workaround for the '_type_ must have storage info' error. Lo and behold, 'a.contents' was an MMAP, so '.data' was a 'c_long' interpretation of the 'char* data' member of the C structure, PyMmapObject or something. I found it by studying the 'ctypes.cast' code. Well good luck and sorry for the suggestions. Umph... couldn't get this to work either. I'm starting a new thread, reproducing the problem with the minimum amount of c++ and python code, now that I know where the problem lies. Again, thanks for your time. -- http://mail.python.org/mailman/listinfo/python-list
SWIG, c++ to Python: array of pointers (double pointer) not working
Re-posting in more simple and precise terms from a previous thread http://groups.google.it/group/comp.lang.python/browse_thread/thread/6dd7bd9a09b8a011/5119cf15ebfa38b8 Problem: SWIG doesn't properly wrap c++ arrays of pointers, therefore when you try to call a c++ function which requires them, a TypeError exception is raised. Similar story here: http://osdir.com/ml/programming.swig/2003-02/msg00064.html Already tried: - some ctypes functions - tuple or string instead of list Possibile solutions: something like http://embedded.eecs.berkeley.edu/Alumni/pinhong/scriptEDA/pyTypemapFAQ.html#20 that didn't work either, but I think I was not able to adapt the code to my case, since the example is poorly explained. Code to reproduce error: I made a dptest.cpp function that calculates the sum of an array of pointers to ints. #include dptest.h //the header file is just //int sum(int**, int); int sum(int** dp, int len){ int sum = 0; for (int i = 0; i len; i++){ sum += *(dp[i]); } return sum; } swig -c++ -python, then setup.py build_ext --inplace gets it nicely compiled and wrapped for python use. It also is imported without problems, but then... mat...@matteo:~/lab/sandbox$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type help, copyright, credits or license for more information. import dptest as dp l = [1, 2, 3, 4] size = len(l) dp.sum(l,size) Traceback (most recent call last): File stdin, line 1, in module TypeError: in method 'sum', argument 1 of type 'int **' NOTE: A pure c++ program works as expected: #include iostream int sum(int**, int); int main(){ int **array_of_ptr = new int*[4]; for (int i = 0; i 4; i++){ array_of_ptr[i] = new int; *array_of_ptr[i] = i+1; //fill it with 1,2,3,4: 1+2+3+4 = 10 } std::cout sum(array_of_ptr, 4) std::endl; } int sum(int** dp, int len){ int sum = 0; for (int i = 0; i len; i++){ sum += *(dp[i]); } return sum; } compiling and running prints the correct result: mat...@matteo:~/lab/sandbox$ ./purecpp 10 -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
Il Sat, 14 Mar 2009 10:30:43 +0100, Vlastimil Brom ha scritto: 2009/3/14 mattia ger...@gmail.com: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] Thanks a lot, Mattia -- http://mail.python.org/mailman/listinfo/python-list Apart from the obvious and rather discouraged list(eval('AAR','ABZ','AGA','AHO')) ['AAR', 'ABZ', 'AGA', 'AHO'] Why discouraged? you may try e.g.: [item[1:-1] for item in 'AAR','ABZ','AGA','AHO'.split(,)] ['AAR', 'ABZ', 'AGA', 'AHO'] hth, vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
mattia wrote: Il Sat, 14 Mar 2009 10:30:43 +0100, Vlastimil Brom ha scritto: 2009/3/14 mattia ger...@gmail.com: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] Thanks a lot, Mattia -- http://mail.python.org/mailman/listinfo/python-list Apart from the obvious and rather discouraged list(eval('AAR','ABZ','AGA','AHO')) ['AAR', 'ABZ', 'AGA', 'AHO'] Why discouraged? Because it uses eval(). Eval can execute arbitrary python code, including some of the dangerous ones. -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
mattia wrote: Il Sat, 14 Mar 2009 10:30:43 +0100, Vlastimil Brom ha scritto: 2009/3/14 mattia ger...@gmail.com: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] Thanks a lot, Mattia -- http://mail.python.org/mailman/listinfo/python-list Apart from the obvious and rather discouraged list(eval('AAR','ABZ','AGA','AHO')) ['AAR', 'ABZ', 'AGA', 'AHO'] Why discouraged? The guys controlling the website you are scraping could feed you something you didn't expect, e. g.: supposed_to_be_flight_codes = __import__('os').system('rm whatever') eval(supposed_to_be_flight_codes) # oops, crash landing Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
Il Sat, 14 Mar 2009 10:35:59 +0100, Peter Otten ha scritto: mattia wrote: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' csv.reader(StringIO.StringIO(s), quotechar=').next() ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] or s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' list(compile(s, nofile, eval).co_consts[-1]) ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] Peter Ok, and what about if the string is ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC'] I wanted to use eval(string) but it is discouraged, they say. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find in in the documentation
On Mar 14, 7:00 am, Tim Golden m...@timgolden.me.uk wrote: Well, this may not solve the OP's problem, but the current (2.7a0) .chm file has a much better index for operators and keywords. And in is in there. If you're interested in comparing, there's a copy here: http://timgolden.me.uk/python/downloads/snapshots/trunk/Python27a0.chm Thanks for the link (should be a lowercase 'p' - python27a0.chm - BTW). But having had a look at this file (under kchmviewer rather than the Windows help viewer) Ye Gods - it's almost unreadable. Not because of the content, but because of the page style. I'm getting black text on a sort of slate blue background. Is this the expected appearance? Jon N -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonWin, python thread and PostQuitMessage?
On 13 mrt, 23:30, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Fri, 13 Mar 2009 17:59:34 -0200, aloons...@gmail.com escribió: On 12 mrt, 18:43, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Thu, 12 Mar 2009 07:21:35 -0200, arn...@sphaero.org escribió: I'm not so much involved in any Windows programming however I needed to write a client for the Windows platform. I have this very simple question which I've been unable to answer. I'm listening for keyboard strokes using the pyhook library. I'm doing this in a dedicated thread. The gui just controls the thread. When I want to pause listening for keyboard strokes I wanted to do a PostQuitMessage() to the thread. However this does not work since it either kills the whole app or just does not happen in the thread it's supposed to. I've now made an ugly workaround using PumpWaitingMessages and a delay. If you have a GUI, then very likely it has its own message loop, so you should not create another. def run(self): print Wkeylog run called # Hook Keyboard self.hm.HookKeyboard() while self.log: win32gui.PumpWaitingMessages() time.sleep(0.02) i can now just cancel the process by setting self.log to False. I wanted to do just: def run(self): print Wkeylog run called # Hook Keyboard self.hm.HookKeyboard() win32gui.PumpMessages() Then, if you remove PumpMesages and PumpWaitingMessages, there is nothing left... so this thread is useless. Perhaps you want to *process* keyboard events in another thread - in this case, use a Queue object to send events to the worker thread, from the main thread where the message loop resides. You are right however this case is a bit different. The application is a keylogger which listens for keyboard events. The GUI is done using Wx. They are different message loops. Under Linux I have no problem however in the case of Windows I don't know how to stop the keylogger. The Keylogger for Windows is very simple, see: http://retypingdante.svn.sourceforge.net/viewvc/retypingdante/trunk/i... This code uses PumpMessages just because it's a console application, and those do not have a message loop by default. A windowed application written in wx *already* has a message loop, so you don't have to provide your own. Stopping the keylogger, in that code, means calling the cancel() method, by any means you want. It has nothing to do with a message loop, AFAICT. As you can see in the cancel function I cannot use win32gui.PostQuitMessage(1) since it kills the whole app, including Wx, and not just the thread. I cannot mix the eventloops of Windows and Wx AFAIK so I put it in its own thread. I'm already using Queue objects to pass the data between threads. I still don't understand why you use a separate message loop. wx provides its own, and it should be enough - worse, a second message loop may adversely affect the application. And without a separate message loop, the separate thread has no sense either. Anyway, if you insist, it's more efficient to wait using an Event object: def __init__(...): ... self.finished = threading.Event() def run(self): self.hm.HookKeyboard() self.finished.wait() def cancel(self): self.hm.UnhookKeyboard() self.finished.set() -- Gabriel Genellina You're right. Last night I dived into all this message looping thing and I don't even have to use PumpMessages(). I got it working from within wx using its messageloop. So I don't need a seperate thread no more. Thanks for your suggestions. Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find in in the documentation
Colin J. Williams c...@ncf.ca wrote: Piet van Oostrum wrote: tinn...@isbd.co.uk (t) wrote: t I've had this trouble before, how do I find the details of how in t works in the documentation. E.g. the details of:- t if string in bigstring: t It gets a mention in the if section but not a lot. It is explained in The Python Language Reference, chapter Expressions, section Comparisons. At least that's were it is in the 2.6 doc. Lots of people have been very helpful but isn't the OP's real problem that in is not included in the 2.6.1 Help index? Yes, I think that is/was my problem. To find the information I had to know that I should look in the Expressions chapter and while that is (possibly) obvious for some things (+, -, AND, OR, etc.) it isn't quite so obvious for in. -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
mattia wrote: Il Sat, 14 Mar 2009 10:35:59 +0100, Peter Otten ha scritto: mattia wrote: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' csv.reader(StringIO.StringIO(s), quotechar=').next() ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] or s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' list(compile(s, nofile, eval).co_consts[-1]) ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] Peter Ok, and what about if the string is ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC'] I wanted to use eval(string) but it is discouraged, they say. If you use the csv module you can remove the [] manually assert s.startswith([) assert s.endswith(]) s = s[1:-1] compile() will work without the enclosing list(...) call. Yet another one is flights = re.compile('([A-Z]+)').findall(s) if any(len(f) != 3 for f in flights): raise ValueError Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
Il Sat, 14 Mar 2009 12:13:31 +0100, Peter Otten ha scritto: mattia wrote: Il Sat, 14 Mar 2009 10:35:59 +0100, Peter Otten ha scritto: mattia wrote: How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' csv.reader(StringIO.StringIO(s), quotechar=').next() ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] or s = 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC' list(compile(s, nofile, eval).co_consts[-1]) ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] Peter Ok, and what about if the string is ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC'] I wanted to use eval(string) but it is discouraged, they say. If you use the csv module you can remove the [] manually assert s.startswith([) assert s.endswith(]) s = s[1:-1] compile() will work without the enclosing list(...) call. Yet another one is flights = re.compile('([A-Z]+)').findall(s) if any(len(f) != 3 for f in flights): raise ValueError Peter Yeah, I'll also havo he handle some simple cases, for now I just used c2 = re.compile(a(?Pfrom[A-Z]{3})=\[(?Pseqto[^\]]+)\]) from_to = dict((x.group(from), str_to_seq(x.group(seqto))) for x in c2.finditer(rest)) Thanks a lot (I also didn't know of the any function)! -- http://mail.python.org/mailman/listinfo/python-list
multiprocessing.sharedctypes and built-in locks
I'm trying this on Python 3.0.1 Consider the following code: import multiprocessing as mp def jambu(b,i,gl): for n in range(10): with gl[i]: b[i]+=2 with gl[3-i]: b[3-i]-=1 def main(): b = mp.RawArray('i',4) gl = [] proc = [] for i in range(len(b)): gl.append(mp.Lock()) proc.append(mp.Process(target=jambu,args=(b,i,gl))) for p in proc: p.start() for p in proc: p.join() print(b[:]) print(sum(b[:])) main() (Yes, I'm aware that I didn't pass the lock array as shared variable, but since they're not reassigned, it should be okay) The above code should produce an output like this: [10, 10, 10, 10] 40 Now, in the documentation for multiprocessing module, it says that multiprocessing.Array will automatically create a lock to ensure process-safe synchronization. So I suppose the above code can be simplified as follows: import multiprocessing as mp def jambu(b,i): for n in range(10): b[i]+=2 b[3-i]-=1 def main(): b = mp.Array('i',4) proc = [] for i in range(len(b)): gl.append(mp.Lock()) proc.append(mp.Process(target=jambu,args=(b,i))) for p in proc: p.start() for p in proc: p.join() print(b[:]) print(sum(b[:])) main() The output of this second code isn't consistent with the first one, implying multiprocessing.Array (or even multiprocessing.Value; I've also tried with this one) isn't as atomic as I understand it should be. So what is the actual meaning of having a Lock object which will be used to synchronize access to the value? Is it only for getting, and not for assigning values? Regards, Ahmad Syukri -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find in in the documentation
jkn wrote: On Mar 14, 7:00 am, Tim Golden m...@timgolden.me.uk wrote: Well, this may not solve the OP's problem, but the current (2.7a0) .chm file has a much better index for operators and keywords. And in is in there. If you're interested in comparing, there's a copy here: http://timgolden.me.uk/python/downloads/snapshots/trunk/Python27a0.chm Thanks for the link (should be a lowercase 'p' - python27a0.chm - BTW). But having had a look at this file (under kchmviewer rather than the Windows help viewer) Ye Gods - it's almost unreadable. Not because of the content, but because of the page style. I'm getting black text on a sort of slate blue background. Is this the expected appearance? Ummm. No. It uses the same css as the standard Python docs. Frankly I think the contrast could be better, but it's certainly readable. Maybe some issue with the kchmviewer rendering? Might be easier for non-Windows users to look at the dev docs online: http://docs.python.org/dev/ since that's built from the same source / index. I find the .chm far easier to search but the online docs are pretty good. The (js-based) online search feature does work but, unfortunately, is naive in its selection, so searching for in turns up any page with the word in in it! The index page is rather better: http://docs.python.org/dev/genindex-I.html Hope that helps TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: question on msvcrt.dll versioning
Thanks much. -=roger Yet more specifically: if the extension module or Python host opens a file with fopen(), and passes it to PyRun_{Any|Simple}File[Ex][Flags], Python will crash. HTH, Martin P.S. There may be more cases in which you get crashes - the list above includes just the known ones. -- http://mail.python.org/mailman/listinfo/python-list
Compute working days
I found no solution on the net so I am posting my solution here. It can be called with python cwd 1-1-2009 14-3-2009 from dateutil.rrule import * from dateutil.parser import * from datetime import * from sys import * start = parse( argv[1] ) #end = datetime.now() end = parse( argv[2] ) workdays = ( MO, TU, WE, TH, FR ) r = rrule(DAILY, byweekday=workdays, dtstart = start, until = end) print len( list( r ) ) g -- http://mail.python.org/mailman/listinfo/python-list
Re: python book for a C programmer
On Mar 14, 12:04 pm, Chris Rebert c...@rebertia.com wrote: On Fri, Mar 13, 2009 at 10:29 PM, Paul Rubin http wrote: Saurabh nirkh...@gmail.com writes: Hi all, I am an experienced C programmer, I have done some perl code as well. But while thinking about large programs,I find perl syntax a hinderance. I would say read the online tutorial, then Python in a Nutshell. Wholeheartedly seconded! Cheers, Chris -- I have a blog:http://blog.rebertia.com Thanks a lot paul and chris. -- http://mail.python.org/mailman/listinfo/python-list
Re: /a is not /a ?
Gary Herron wrote: Robert Kern wrote: On 2009-03-06 14:23, Gary Herron wrote: Robert Kern wrote: On 2009-03-06 13:46, Gary Herron wrote: Emanuele D'Arrigo wrote: Hi everybody, while testing a module today I stumbled on something that I can work around but I don't quite understand. *Do NOT use is to compare immutable types.* **Ever! ** Well, foo is None is actually recommended practice But since newbies are always falling into this trap, it is still a good rule to say: Newbies: Never use is to compare immutable types. and then later point out, for those who have absorbed the first rule: Experts: Singleton immutable types *may* be compared with is, although normal equality with == works just as well. That's not really true. If my object overrides __eq__ in a funny way, is None is much safer. Use is when you really need to compare by object identity and not value. But that definition is the *source* of the trouble. It is *completely* meaningless to newbies. Until one has experience in programming in general and experience in Python in particular, the difference between object identity and value is a mystery. So in order to lead newbies away from this *very* common trap they often fall into, it is still a valid rule to say Newbies: Never use is to compare immutable types. I think this is addressing the wrong problem. I;d prefer to say Newbies: never assume that the interpreter keeps just one copy of any value. Just because a == b that doesn't mean that a is b. *Sometimes* it will be, but it isn't usually guaranteed. of even better Newbies: Never use is to compare anything. This will help them avoid traps, and won't hurt their use of the language. If they get to a point that they need to contemplate using is, then almost be definition, they are not a newbie anymore, and the rule is still valid. personally I believe newbies should be allowed the freedom to shoot themselves in the foot occasionally, and will happily explain the issues that arise when they do so. It's all good learning. I think using is to compare mutable objects is a difficult topic to explain, and I think your division of objects into mutable and immutable types is unhelpful and not to-the-point. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Want to know? Come to PyCon - soon! http://us.pycon.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: /a is not /a ?
Paul Rubin wrote: Steven D'Aprano st...@pearwood.info writes: It is never correct to avoid using is when you need to compare for identity. When is it ever necessary to compare for identity? For example when providing a unique sentinel value as a function argument. The parameter must be tested for identity with the sentinel. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Want to know? Come to PyCon - soon! http://us.pycon.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: /a is not /a ?
Carl Banks wrote: On Mar 8, 5:32 am, Lie Ryan lie.1...@gmail.com wrote: Mel wrote: wrote: Steven D'Aprano st...@pearwood.info writes: It is never correct to avoid using is when you need to compare for identity. When is it ever necessary to compare for identity? Ho-hum. MUDD game. def broadcast (sender, message): for p in all_players: if p is not sender: p.tell (message)# don't send a message to oneself Since in a MUD game, a player would always have a unique username, I'd rather compare with that. It doesn't rely on some internals. There is very, very rare case where 'is' is really, really needed. Well, by that criterion you can dismiss almost anything. Of course you can assign unique ids to most objects and perform your identity tests that way. The point is that sometimes you do need to test for the identity of the object, not merely the equivalent semantic value. If, faced with this problem (and I'm guessing you haven't faced it much) your approach is always to define a unique id, so that you can avoid ever having to use the is operator, be my guest. As for me, I do program in the sort of areas where identity testing is common, and I don't care to define ids just to test for identity alone, so for me is is useful. Well, the obvious identity is id(p), but then a is b is entirely equivalent to id(a) == id(b) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Want to know? Come to PyCon - soon! http://us.pycon.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Get pixel colors from images in Python 3
Daniel Fetchinson wrote: I've noticed that Pygame has some similar implementation. It's a little harder to use, but efficient. And i think it depends on PIL too. And Pygame is Python 2.x too... ... When I asked about it there I was told that some work already has started on porting PIL to python 3. I'm guessing if you ask again at least it will be viewed as a +1 vote on the project and that will probably not hurt :) Sure not, and I think a helping hand wouldn't hurt either ;) In case mr OP wants it fast, I'd suggest sticking with python2.x Regards Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Neatest way to do a case insensitive in?
tinn...@isbd.co.uk wrote: ... But I was wondering if there's a neater/easier way? How is if stringA.lower() in stringB.lower(): complex/messy? Well I guess I was just looking for incase a bit like strcasecmp in C. Which locales case folding do you want to have applied? Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: 2.6.1 - simple division
farsi...@gmail.com wrote: Thanks all, that's very helpful, sorry to waste your time with a common question. I have tried the decimal module and will definitely keep using it if I need to do this kind of calculation again. I have 1 more question that the floating point article that was linked didn't really answer: x = 0.8 x 0.804 x * 5 4.0 Shouldn't I be expecting something like 4.2 ? How different is 4.0? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Want to know? Come to PyCon - soon! http://us.pycon.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Compute working days
On Mar 15, 12:13 am, Gonsolo gons...@gmail.com wrote: I found no solution on the net so I am posting my solution here. It can be called with python cwd 1-1-2009 14-3-2009 from dateutil.rrule import * from dateutil.parser import * from datetime import * from sys import * H ... I wonder what the style police will have to say about that little lot :-) start = parse( argv[1] ) #end = datetime.now() end = parse( argv[2] ) workdays = ( MO, TU, WE, TH, FR ) r = rrule(DAILY, byweekday=workdays, dtstart = start, until = end) print len( list( r ) ) # Look, Ma, no 3rd party modules! import datetime for start in range(1, 8): print d1 = datetime.date(2009, 3, start) day1 = d1.toordinal() dow1 = (day1 - 1) % 7 for delta in range(8): d2 = datetime.date(2009, 3, start + delta) day2 = d2.toordinal() dow2 = (day2 - 1) % 7 workdays = (day2 + 7 - dow2 - day1 + dow1) // 7 * 5 - min (dow1, 5) - max(4 - dow2, 0) print d1, d2, dow1, dow2, workdays # Assumes both endpoints are included e.g. Mon 2 March to Tue 3 March is 2 work-days. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Special keyword argument lambda syntax
Beni Cherniavsky beni.cherniav...@gmail.com wrote: This proposal outrageously suggests a special syntax for in-line functions passed as keyword arguments:: sorted(range(9), key(n)=n%3) [0, 3, 6, 1, 4, 7, 2, 5, 8] The claim is that such specialization hits a syntax sweet spot, and that this use case is frequent enough to contemplate eventually making it the only in-line function syntax. -1 from me. I think that lambda / inline functions should be discouraged as it moves python away from, there should be one-- and preferably only one --obvious way to do it. IMHO Guido was right in his original impulse to kill this second class way of making functions... I would write the above as def compute_key(n): Compute the sort key so that x, y and z are true return n % 3 sorted(range(9), key=compute_key) Which I think is clearer and more obvious. It gives you the opportunity for a docstring also. Yes it is a bit more typing, but who wants to play code golf all day? -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: converting a string to a function parameter
My new class I've been working on might help you. It does what you are asking without eval (I'm still working on it) Anyone have any ideas aswell along with the OP, thank you #!/usr/bin env python # # -*- coding: UTF-8 -*- # # PyNutButter BETA Version 0.1.0.1 # # Copyright 2009 - Infinity by Alex Goretoy, All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # SEE ALSO LICENSE FILE IN PROJECT ROOT DIRECTORY # __author__ = Aleksandr Ilyich Goretoy agore...@gmail.com __status__ = beta __version__ = 0.1.0.1 __date__= 14 March 2009 import sys, os from colors import colors as _ck from has_colors import _has_colors as _ha from logg import _brush as _ers class colors(object): def __init__(self,colors_active=1,output_caller=1,caller_color=red,default=1, show_lineno_write=1,show_lineno_caller=1,break_all=1, logging=1,log_type=INFO,depth=10): stdout colorization class - prints messages in color to stdout colors_active - output to stdout in color? 1 or 0 output_caller - print output when control enters this class/functions ,output caller and called function caller_color - color to use to output caller only if output_caller is 1 self.caller_color = caller_color #stdout_colors function caller called output color self.output_caller = output_caller # output caller and called function self.colors_active = colors_active #active colors for output self.has_colors = _ha(sys.stdout) self.colors = _ck crack=_ers(logger=simpleExample,level=INFO, log_file=log_file=os.environ[PWD]+/logs/eggo,spc=1,brk=1,slk=1,fn=1) #Thanks Gabriel Genellina, no crack was smoked while making crack like this #list( ( self.__setattr__(x.replace(b_,),getattr(B,x)) for x in dir(B) if x.startswith(b_) ) ) for smoke in dir(crack): if smoke.startswith(b_): setattr(self, smoke[2:], getattr(crack, smoke)) these colors may not be correct: depending on how you have your terminal configured #if self.output_caller: #self.me_him(['ENTER COLORS',__name__],self.caller_color) color and value self.color=default#display color self.value=#used to store displayed message def w(self,value,color=red,level=INFO): self.write(value,color,level) def write(self,value,color=red,level=INFO): write - output message,take value string or list,color= self._hero(value,color,level) def h(self,color=red,level=DEBUG): self.him(color,level) def him(self,color=red,level=DEBUG): him - determines caller function name, takes color= if self.output_caller: value=sys._getframe(2).f_code.co_name#+inspect.currentframe().f_back.f_lineno self._hero(value,color,level) def m_h(self,value,color=purple,level=DEBUG): self.me_him(value,color,level) def me_him(self,value,color=purple,log_type=DEBUG): me_him - determines current function prepends class name and displays caller function if self.output_caller: value=.join(value)+.+sys._getframe(1).f_code.co_name+self.colors['default']+sys._getframe(2).f_code.co_name+\x1b[00m self._hero(value,color,level) def m(self,value,color=blue,level=DEBUG): self.me(value,color,level) def me(self,value,color=blue,level=DEBUG): me - determines current function prepends class name, takes value=__name__,color= #self.frames() value=.join(str(value)) + . + .join(sys._getframe(1).f_code.co_name) self._hero(value,color,level) def _hero(self,value,color,level=INFO): if self.colors_active: try: if self.colors[color] and self.has_colors != None: self.reaper(value,self.colors[color],level) self.spacer() else:
Re: How to find in in the documentation
Tim Golden wrote: Colin J. Williams wrote: Piet van Oostrum wrote: tinn...@isbd.co.uk (t) wrote: t I've had this trouble before, how do I find the details of how in t works in the documentation. E.g. the details of:- t if string in bigstring: t It gets a mention in the if section but not a lot. It is explained in The Python Language Reference, chapter Expressions, section Comparisons. At least that's were it is in the 2.6 doc. Lots of people have been very helpful but isn't the OP's real problem that in is not included in the 2.6.1 Help index? Well, this may not solve the OP's problem, but the current (2.7a0) .chm file has a much better index for operators and keywords. And in is in there. If you're interested in comparing, there's a copy here: http://timgolden.me.uk/python/downloads/snapshots/trunk/Python27a0.chm TJG Thanks. in is now in the index twice, but I wasn't able to follow the links. I trust that the improved docs will go back to 2.6, unless 2.7 is almost ready. Colin W -- http://mail.python.org/mailman/listinfo/python-list
Style question - defining immutable class data members
Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? - Max -- http://mail.python.org/mailman/listinfo/python-list
ElementTree: How to return only unicode?
Hallöchen! I parse an XML file with ElementTree and get the contets with the .attrib, .text, .get etc methods of the tree's nodes. Additionally, I use the find and findtext methods. My problem is that if there is only ASCII, these methods return ordinary strings instead of unicode. So sometimes I get str, sometimes I get unicode. Can one change this globally so that they only return unicode? Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bron...@jabber.rwth-aachen.de -- http://mail.python.org/mailman/listinfo/python-list
don't understand behaviour of recursive structure
I'm new to python. Could someone please explain the following behaviour of a recursive data structure? def new_node(id='', daughters=[]): return dict(id=id, daughters=daughters) n0 = new_node(id='n0') n1 = new_node(id='n1') ## Seems OK so far: n0 # {'id': 'n0', 'daughters': []} n1 # {'id': 'n1', 'daughters': []} ## Now try to make n1 a daughter of n0: n0['daughters'].append(n1) ## But that seems to have made something funny happen to n1: n1 # {'id': 'n1', 'daughters': [{...}]} ## In fact, n1 seems to have become its own daughter n1['daughters'][0] # {'id': 'n1', 'daughters': [{...}]} ## and grand-daughter, etc etc n1['daughters'][0]['daughters'][0] # {'id': 'n1', 'daughters': [{...}]} ## These changes to n1 are present in n0 (as I would expect) n0 # {'id': 'n0', 'daughters': [{'id':'n1', 'daughters': [...]}]} n0['daughters'][0]['daughters'][0] # {'id': 'n1', 'daughters': [...]} Why did the append() operation have this effect? Straight assignment seems to do what I expected, i.e. n0['daughters'] = [n1] n1# still the same {'id': 'n1', 'daughters': []} n0# {'id': 'n0', 'daughters': [{'id': 'n1', 'daughters': []}]} Thanks for any enlightenment, Dan ~ python --version Python 2.5.2 ~ uname -a Linux Tichodroma 2.6.27-11-generic #1 SMP Thu Jan 29 19:24:39 UTC 2009 i686 GNU/Linux Ubuntu 8.10 -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Maxim Khitrov wrote: Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? In the first case each instance has its own attributes, whereas in the second case the attributes belong to the class and are thus shared by all the instances. Which you use depends on whether you want them shared or not. -- http://mail.python.org/mailman/listinfo/python-list
Re: don't understand behaviour of recursive structure
On Sat, Mar 14, 2009 at 12:31 PM, Dan Davison wrote: I'm new to python. Could someone please explain the following behaviour of a recursive data structure? def new_node(id='', daughters=[]): return dict(id=id, daughters=daughters) This is something of a FAQ: http://effbot.org/zone/default-values.htm http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: don't understand behaviour of recursive structure
Dan Davison wrote: I'm new to python. Could someone please explain the following behaviour of a recursive data structure? def new_node(id='', daughters=[]): return dict(id=id, daughters=daughters) n0 = new_node(id='n0') n1 = new_node(id='n1') [snip] See http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects -- http://mail.python.org/mailman/listinfo/python-list
Re: Compute working days
How about: from datetime import date, timedelta # Define the weekday mnemonics to match the date.weekday function (MON, TUE, WED, THU, FRI, SAT, SUN) = range(7) def workdays(start_date, end_date, whichdays=(MON,TUE,WED,THU,FRI)): ''' Calculate the number of working days between two dates inclusive (start_date = end_date). The actual working days can be set with the optional whichdays parameter (default is MON-FRI) ''' delta_days = (end_date - start_date).days + 1 full_weeks, extra_days = divmod(delta_days, 7) # num_workdays = how many days/week you work * total # of weeks num_workdays = (full_weeks + 1) * len(whichdays) # subtract out any working days that fall in the 'shortened week' for d in range(1, 8 - extra_days): if (end_date + timedelta(d)).weekday() in whichdays: num_workdays -= 1 return num_workdays -- http://mail.python.org/mailman/listinfo/python-list
Re: don't understand behaviour of recursive structure
On 14 Mar, 17:31, Dan Davison davi...@stats.ox.ac.uk wrote: I'm new to python. Could someone please explain the following behaviour of a recursive data structure? def new_node(id='', daughters=[]): return dict(id=id, daughters=daughters) Most probably, here is the problem : try this instead: def new_node(id='', daughters=None): if not daughters: daughters = [] return dict(id=id, daughters=daughters) This is one of the less intuitive points in python: default values are evaluated only once, at 'compile' time I think. So when you call twice 'new_node' without specifying the daughters parameters, both dict will have the _same_ list. Hence chaos In other words, it is exactly as if you wrote: EmptyList = [] def new_node(id='', daughters=EmptyList): return dict(id=id, daughters=daughters) See the problem now? If not try this: l1 = [] l2 = l1 l1.append(1) print l2 See now? The same happens inside your 'nodes'. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sat, Mar 14, 2009 at 12:50 PM, MRAB goo...@mrabarnett.plus.com wrote: Maxim Khitrov wrote: Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? In the first case each instance has its own attributes, whereas in the second case the attributes belong to the class and are thus shared by all the instances. Which you use depends on whether you want them shared or not. When the types are immutable, there is no difference. The second case is faster and consumes less memory (initially), but nothing else changes. I'm simply asking if it is considered poor style to define data members for the class when they are only used by instances. - Max -- http://mail.python.org/mailman/listinfo/python-list
multiprocessing module - isn't it a bug?
# THIS WORKS OK from multiprocessing import Pool N = 400 K = 800 processes = 2 def costlyFunction2(z): r = 0 for k in xrange(1, K+2): r += z ** (1 / k**1.5) return r class ABC: def __init__(self): pass def testParallel(self): po = Pool(processes=processes) r = po.map(costlyFunction2, xrange(N), chunksize = N/ (10*processes)) A=ABC() A.testParallel() print 'done' # But when I define costlyFunction2 inside of class, it doesn't work: from multiprocessing import Pool N = 400 K = 800 processes = 2 class ABC: def __init__(self): pass def testParallel(self): po = Pool(processes=processes) def costlyFunction2(z): r = 0 for k in xrange(1, K+2): r += z ** (1 / k**1.5) return r r = po.map(costlyFunction2, xrange(N), chunksize = N/ (10*processes)) A=ABC() A.testParallel() print 'done' Exception in thread Thread-1: Traceback (most recent call last): File /usr/lib/python2.6/threading.py, line 522, in __bootstrap_inner self.run() File /usr/lib/python2.6/threading.py, line 477, in run self.__target(*self.__args, **self.__kwargs) File /usr/lib/python2.6/multiprocessing/pool.py, line 225, in _handle_tasks put(task) PicklingError: Can't pickle type 'function': attribute lookup __builtin__.function failed This doesn't work for costlyFunction2 = lambda x: 11 as well; and it doesn't work for imap, apply_async as well (same error). So, isn't it a bug, or it can be somehow fixed? Thank you in advance, D. -- http://mail.python.org/mailman/listinfo/python-list
Re: finally successful in ods with python, just one help needed.
Krishnakant hackin...@gmail.com writes: However when I apply the same elements and attributes to the one I am creating with odfpy, I get attribute not allowed errors. If some one is interested to look at the code, please let me know, I can send an attachment off the list so that others are not forced to download some thing they are not concerned about. I just tried this myself and the following creates a 3x3 spreadsheet with the first row spanning all three columns (no special formatting like centering or anything), using odf2py 0.8: import sys from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TableColumnProperties from odf.table import Table, TableRow, TableColumn, \ TableCell, CoveredTableCell from odf.text import P def make_ods(): ods = OpenDocumentSpreadsheet() col = Style(name='col', family='table-column') col.addElement(TableColumnProperties(columnwidth='1in')) table = Table() table.addElement(TableColumn(numbercolumnsrepeated=3, stylename=col)) ods.spreadsheet.addElement(table) # Add first row with cell spanning columns A-C tr = TableRow() table.addElement(tr) tc = TableCell(numbercolumnsspanned=3) tc.addElement(P(text=ABC1)) tr.addElement(tc) # Uncomment this to more accurately match native file ##tc = CoveredTableCell(numbercolumnsrepeated=2) ##tr.addElement(tc) # Add two more rows with non-spanning cells for r in (2,3): tr = TableRow() table.addElement(tr) for c in ('A','B','C'): tc = TableCell() tc.addElement(P(text='%s%d' % (c, r))) tr.addElement(tc) ods.save(ods-test.ods) Maybe that will give you a hint as to what is happening in your case. Note that it appears creating such a spreadsheet directly in Calc also adds covered table cells for those cells beneath the spanned cell, but Calc loads a file fine without those and still lets you later split the merge and edit the underlying cells. So I'm not sure how required that is as opposed to just how Calc manages its own internal structure. -- David -- http://mail.python.org/mailman/listinfo/python-list
Re: Special keyword argument lambda syntax
On Mar 14, 5:30 pm, Nick Craig-Wood n...@craig-wood.com wrote: BeniCherniavskybeni.cherniav...@gmail.com wrote: This proposal outrageously suggests a special syntax for in-line functions passed as keyword arguments:: sorted(range(9), key(n)=n%3) [0, 3, 6, 1, 4, 7, 2, 5, 8] The claim is that such specialization hits a syntax sweet spot, and that this use case is frequent enough to contemplate eventually making it the only in-line function syntax. -1 from me. I think thatlambda/ inline functions should be discouraged as it moves python away from, there should be one-- and preferably only one --obvious way to do it. IMHO Guido was right in his original impulse to kill this second class way of making functions... On a second thought, considering the LL(1) problem (which indicates a real problem for humans parsing it) and the f(x)== confusion, I agree. Given that ``lambda`` usage is negligible compared to ``def`` (1.5% in python3.0 stdlib, ~3% counting most Python files in ubuntu repository), it should have been killed altogether per YAGNI and the one way principle. [Or is it just my if you don't do it my way, don't do it at all emotion talking? Don't know. But I did the statistics only after formulating the proposal, and I think now that 3% is definitely YAGNI.] -- http://mail.python.org/mailman/listinfo/python-list
PyWin32 for Python 3.x
Any idea when PyWin32 will be available for Python 3.x? John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Maxim Khitrov: When the types are immutable, there is no difference. But you may want different instances to have different immutable data. Generally if the data (immutable or not) is the same for all the instances, use class attributes, otherwise use instance attributes. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Maxim Khitrov wrote: Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? - Max -- http://mail.python.org/mailman/listinfo/python-list Such things are often called class attributes, and the are fine. If you look through Python's standard library, you will find many examples of class attributes. However, you appear to have either a misuse or misconception of the word immutable' here. Whether the value you assign to a class attribute is mutable or immutable is irrelevant. Also whether you plan on leaving the value constant or not is also not relevant. What does matter is this: If every instance wants access to a single value (immutable or not), use a class attribute, otherwise use an instance attribute. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find in in the documentation
Colin J. Williams wrote: Tim Golden wrote: Colin J. Williams wrote: Piet van Oostrum wrote: tinn...@isbd.co.uk (t) wrote: t I've had this trouble before, how do I find the details of how in t works in the documentation. E.g. the details of:- t if string in bigstring: t It gets a mention in the if section but not a lot. It is explained in The Python Language Reference, chapter Expressions, section Comparisons. At least that's were it is in the 2.6 doc. Lots of people have been very helpful but isn't the OP's real problem that in is not included in the 2.6.1 Help index? Well, this may not solve the OP's problem, but the current (2.7a0) .chm file has a much better index for operators and keywords. And in is in there. If you're interested in comparing, there's a copy here: http://timgolden.me.uk/python/downloads/snapshots/trunk/Python27a0.chm TJG Thanks. in is now in the index twice, but I wasn't able to follow the links. Worked for me. What was the problem? TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: python book for a C programmer
On 3/13/2009 10:29 PM, Paul Rubin wrote: Saurabhnirkh...@gmail.com writes: Hi all, I am an experienced C programmer, I have done some perl code as well. But while thinking about large programs,I find perl syntax a hinderance. I would say read the online tutorial, then Python in a Nutshell. That exactly was what I did! I second that too. I knew only C/C++/Java fairly well before jumping into Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWin32 for Python 3.x
John Nagle wrote: Any idea when PyWin32 will be available for Python 3.x? John Nagle Release 213 is out already: http://sourceforge.net/project/showfiles.php?group_id=78018package_id=79063release_id=661475 I think it's still considered a little bit beta. There have been a *lot* of changes involved. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Integer arithmetic in hardware descriptions
Jan Decaluwe wrote: I am the author of MyHDL, a Python package that turns Python into a hardware description language (HDL). Integer arithmetic is very important in hardware design, but with traditional HDLs such as Verilog and VHDL it is complicated and confusing. MyHDL has a better solution, inspired by Python's native integer type, int. I have written an essay that explores these issues in detail: http://www.jandecaluwe.com/hdldesign/counting.html I went through this exercise many years ago, from a program verification perspective, and somewhere I have an article entitled Type Integer Considered Harmful. The position I took was: Integer results should be the same on all platforms. The basic integer type should be the range, with an explicit upper and lower bound. (Pascal had something like this, called a subrange, but it it wasn't done quite right.) Violating the range of a variable is an error. It is the job of the compiler to ensure that intermediate values in integer expressions can handle all possible values given the declared ranges of the user variables. The last item has to do with expressions like (in Pascal-like syntax) x,a,b,c: range[0..2^32-1]; x = (a * b) / c; The compiler has to work out that (a * b) needs to be bigger than x,a,b,c. CPython uses a bignum approach to escape this problem, but that has costs. It's also not an option when compiling to hardware, as with VHDL. I used to do proof of correctness work. See this manual, from the early 1980s. http://www.animats.com/papers/verifier/verifiermanual.pdf I gave up on this when C came in; the C crowd was so casual about integer overflow that nobody cared about this level of correctness. Today, of course, buffer overflows are a way of life. This is really off topic for the group. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Maxim Khitrov wrote: On Sat, Mar 14, 2009 at 12:50 PM, MRAB goo...@mrabarnett.plus.com wrote: Maxim Khitrov wrote: Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? In the first case each instance has its own attributes, whereas in the second case the attributes belong to the class and are thus shared by all the instances. Which you use depends on whether you want them shared or not. When the types are immutable, there is no difference. The second case is faster and consumes less memory (initially), but nothing else changes. I'm simply asking if it is considered poor style to define data members for the class when they are only used by instances. If they are class constants (the same for all instances, I would define them as such. If duplicated for all instances in __init__, I would expect there to be methods that replace them. I particular, I would expect that .some_value would possibly get a value other than 0. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing module - isn't it a bug?
dmitrey wrote: # THIS WORKS OK from multiprocessing import Pool N = 400 K = 800 processes = 2 def costlyFunction2(z): r = 0 for k in xrange(1, K+2): r += z ** (1 / k**1.5) return r class ABC: def __init__(self): pass def testParallel(self): po = Pool(processes=processes) r = po.map(costlyFunction2, xrange(N), chunksize = N/ (10*processes)) A=ABC() A.testParallel() print 'done' # But when I define costlyFunction2 inside of class, it doesn't work: from multiprocessing import Pool N = 400 K = 800 processes = 2 class ABC: def __init__(self): pass def testParallel(self): po = Pool(processes=processes) def costlyFunction2(z): r = 0 for k in xrange(1, K+2): r += z ** (1 / k**1.5) return r r = po.map(costlyFunction2, xrange(N), chunksize = N/ (10*processes)) A=ABC() A.testParallel() print 'done' Exception in thread Thread-1: Traceback (most recent call last): File /usr/lib/python2.6/threading.py, line 522, in __bootstrap_inner self.run() File /usr/lib/python2.6/threading.py, line 477, in run self.__target(*self.__args, **self.__kwargs) File /usr/lib/python2.6/multiprocessing/pool.py, line 225, in _handle_tasks put(task) PicklingError: Can't pickle type 'function': attribute lookup __builtin__.function failed This doesn't work for costlyFunction2 = lambda x: 11 as well; and it doesn't work for imap, apply_async as well (same error). So, isn't it a bug, or it can be somehow fixed? Since the multiproccessing Programming Guidelines say Picklability Ensure that the arguments to the methods of proxies are picklable. and you got a PicklingError, perhaps 'no' and 'no', but I would research the pickle module and 'picklability' to be sure. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: don't understand behaviour of recursive structure
bieff...@gmail.com wrote: On 14 Mar, 17:31, Dan Davison davi...@stats.ox.ac.uk wrote: I'm new to python. Could someone please explain the following behaviour of a recursive data structure? def new_node(id='', daughters=[]): return dict(id=id, daughters=daughters) Most probably, here is the problem : try this instead: def new_node(id='', daughters=None): if not daughters: daughters = [] return dict(id=id, daughters=daughters) This is one of the less intuitive points in python: default values are evaluated only once, at 'compile' time I think. So when you call twice 'new_node' without specifying the daughters parameters, both dict will have the _same_ list. Hence chaos [snip] It's not really 'compile' time. 'def' is a _statement_, not a declaration. Its effect is to create a function and bind it to a name in the current namespace. Any default parameters are evaluated when the function is created and they are shared by all the function calls. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing module - isn't it a bug?
dmitrey wrote: This doesn't work for costlyFunction2 = lambda x: 11 as well; and it doesn't work for imap, apply_async as well (same error). So, isn't it a bug, or it can be somehow fixed? Thank you in advance, D. It's not a bug but a limitation of the pickle protocol. Pickle can't handle nested functions or classes. As a rule of thumb pickle can only handle functions and classes that are accessible via a dotted name, e.g. package.module.SomeClass.somefunction or anothermodule.afunction. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sat, Mar 14, 2009 at 2:07 PM, Gary Herron gher...@islandtraining.com wrote: Maxim Khitrov wrote: Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? - Max -- http://mail.python.org/mailman/listinfo/python-list Such things are often called class attributes, and the are fine. If you look through Python's standard library, you will find many examples of class attributes. However, you appear to have either a misuse or misconception of the word immutable' here. Whether the value you assign to a class attribute is mutable or immutable is irrelevant. Also whether you plan on leaving the value constant or not is also not relevant. What does matter is this: If every instance wants access to a single value (immutable or not), use a class attribute, otherwise use an instance attribute. Gary Herron Perhaps a different example would help explain what I'm trying to do: class Case1(object): def __init__(self): self.count = 0 self.list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) class Case2(object): count = 0 list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) for i in xrange(10): c1 = Case1() c2 = Case2() for j in xrange(i): c1.inc() c2.inc() v1, l1 = c1.val() v2, l2 = c2.val() print v1 == v2, l1 == l2 The only difference between Case1 and Case2 classes is where the count and list attributes are defined. You will notice that for an immutable type (count), this doesn't matter. On the last line, v1 == v2 is always True. When the type is mutable (list), you must define it in __init__. This isn't about class attributes or shared instance attributes/constants. This is about a small optimization in defining per-instance variables. This optimization only applies to immutable types. - Max -- http://mail.python.org/mailman/listinfo/python-list
Re: converting a string to a function parameter
This is a file that is going into the new version of python-stdout-colors project location: http://code.google.com/p/python-stdout-colors/ -Alex Goretoy http://www.goretoy.com On Sat, Mar 14, 2009 at 10:45 AM, alex goretoy aleksandr.gore...@gmail.comwrote: My new class I've been working on might help you. It does what you are asking without eval (I'm still working on it) Anyone have any ideas aswell along with the OP, thank you #!/usr/bin env python # # -*- coding: UTF-8 -*- # # PyNutButter BETA Version 0.1.0.1 # # Copyright 2009 - Infinity by Alex Goretoy, All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # SEE ALSO LICENSE FILE IN PROJECT ROOT DIRECTORY # __author__ = Aleksandr Ilyich Goretoy agore...@gmail.com __status__ = beta __version__ = 0.1.0.1 __date__= 14 March 2009 import sys, os from colors import colors as _ck from has_colors import _has_colors as _ha from logg import _brush as _ers class colors(object): def __init__(self,colors_active=1,output_caller=1,caller_color=red,default=1, show_lineno_write=1,show_lineno_caller=1,break_all=1, logging=1,log_type=INFO,depth=10): stdout colorization class - prints messages in color to stdout colors_active - output to stdout in color? 1 or 0 output_caller - print output when control enters this class/functions ,output caller and called function caller_color - color to use to output caller only if output_caller is 1 self.caller_color = caller_color #stdout_colors function caller called output color self.output_caller = output_caller # output caller and called function self.colors_active = colors_active #active colors for output self.has_colors = _ha(sys.stdout) self.colors = _ck crack=_ers(logger=simpleExample,level=INFO, log_file=log_file=os.environ[PWD]+/logs/eggo,spc=1,brk=1,slk=1,fn=1) #Thanks Gabriel Genellina, no crack was smoked while making crack like this #list( ( self.__setattr__(x.replace(b_,),getattr(B,x)) for x in dir(B) if x.startswith(b_) ) ) for smoke in dir(crack): if smoke.startswith(b_): setattr(self, smoke[2:], getattr(crack, smoke)) these colors may not be correct: depending on how you have your terminal configured #if self.output_caller: #self.me_him(['ENTER COLORS',__name__],self.caller_color) color and value self.color=default#display color self.value=#used to store displayed message def w(self,value,color=red,level=INFO): self.write(value,color,level) def write(self,value,color=red,level=INFO): write - output message,take value string or list,color= self._hero(value,color,level) def h(self,color=red,level=DEBUG): self.him(color,level) def him(self,color=red,level=DEBUG): him - determines caller function name, takes color= if self.output_caller: value=sys._getframe(2).f_code.co_name#+inspect.currentframe().f_back.f_lineno self._hero(value,color,level) def m_h(self,value,color=purple,level=DEBUG): self.me_him(value,color,level) def me_him(self,value,color=purple,log_type=DEBUG): me_him - determines current function prepends class name and displays caller function if self.output_caller: value=.join(value)+.+sys._getframe(1).f_code.co_name+self.colors['default']+sys._getframe(2).f_code.co_name+\x1b[00m self._hero(value,color,level) def m(self,value,color=blue,level=DEBUG): self.me(value,color,level) def me(self,value,color=blue,level=DEBUG): me - determines current function prepends class name, takes value=__name__,color= #self.frames() value=.join(str(value)) + . +
Re: Guidance on writing a top-like console
In article mailman.922.1235774125.11746.python-l...@python.org, Tim Chase python.l...@tim.thechases.com wrote: I am interested in writing an application that functions like a Unix or Linux top in the way it displays data. It should be command-line based but dynamically refreshing. You might look at the sourcecode for iotop[1] which would make a good example (it's a top-like program written in Python, used for monitoring I/O transactions on a per-process basis) For all my disagreements with Richard Stallman, this simple post illustrates why his philosophy is in some degree essential. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads and temporary files
On Mar 14, 3:01 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Fri, 13 Mar 2009 19:07:46 -0200, aiwarrior zube...@yahoo.com.br escribió: I recently am meddling with threads and wanted to make a threaded class that instead of processing anything just retrieves data from a file and returns that data to a main thread that takes all the gathered data and concatenates it sequentially. An example is if we want to get various ranges of an http resource in paralell The usual way to communicate between threads is using a Queue object. Instead of (create a thread, do some work, exit/destroy thread) you could create the threads in advance (a thread pool of worker threads) and make them wait for some work to do from a queue (in a quasi-infinite loop). When work is done, they put results in another queue. The main thread just places work units on the first queue; another thread reassembles the pieces from the result queue. For an I/O bound application like yours, this should work smoothly. You should be able to find examples on the web - try the Python Cookbook. -- Gabriel Genellina I already tried a double queue implementation as you suggest with a queue for the threads to get info from and another for the threads to put the info in. My implementation test was using a file with some lines of random data. Here it is class DownloadUrl(threading.Thread): def __init__(self,queue_in,queue_out): threading.Thread.__init__( self ) #self.url = url #self.starts = starts #self.ends = ends self.queue_in = queue_in self.queue_out = queue_out def run(self): (fp,i) = self.queue_in.get() self.queue_in.task_done() #print var #self.queue_out.put(i,False) worknr = 5 queue_in = Queue.Queue(worknr) queue_out = Queue.Queue(worknr) threads = [] fp = open(./xi,r) #print fp.readlines() for i in xrange(10): queue_in.put((fp,i)) DownloadUrl(queue_in,queue_out).start() queue_in.join() while queue_out.qsize(): print queue_out.get() queue_out.task_done() Any reason you're using threads instead of processes? Perhaps because of more flexible way to share data between threads than processes -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sat, Mar 14, 2009 at 12:32 PM, Maxim Khitrov mkhit...@gmail.com wrote: Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? In general I think it can be fine as long as you do use immutable values. I use this pattern when I create data transfer objects[0]. Normally these objects don't have any methods. So you want to be careful that you are doing it for the right reason. When I create objects that are not DTOs I don't do this. [0] http://martinfowler.com/eaaCatalog/dataTransferObject.html -- David blog: http://www.traceback.org twitter: http://twitter.com/dstanek -- http://mail.python.org/mailman/listinfo/python-list
Re: don't understand behaviour of recursive structure
bieff...@gmail.com writes: On 14 Mar, 17:31, Dan Davison davi...@stats.ox.ac.uk wrote: I'm new to python. Could someone please explain the following behaviour of a recursive data structure? def new_node(id='', daughters=[]): return dict(id=id, daughters=daughters) Most probably, here is the problem : try this instead: def new_node(id='', daughters=None): if not daughters: daughters = [] return dict(id=id, daughters=daughters) This is one of the less intuitive points in python: default values are evaluated only once, at 'compile' time I think. So when you call twice 'new_node' without specifying the daughters parameters, both dict will have the _same_ list. Hence chaos In other words, it is exactly as if you wrote: EmptyList = [] def new_node(id='', daughters=EmptyList): return dict(id=id, daughters=daughters) See the problem now? If not try this: Yes, that's very clear. Thanks for all the answers on this thread. Dan l1 = [] l2 = l1 l1.append(1) print l2 See now? The same happens inside your 'nodes'. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: String to sequence
How can I convert the following string: 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' into this sequence: ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] Though several other options have come through: s = 'EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' import re r = re.compile('([^']*)',?) r.findall(s) ['EGC', 'SXF', 'BZR', 'BIQ', 'BLL', 'BHX', 'BLQ'] If you want to get really fancy, you can use the built-in csv parser: import cStringIO st = cStringIO.StringIO(s) import csv class SingleQuoteDialect(csv.Dialect): ... quotechar = ' ... quoting = csv.QUOTE_MINIMAL ... delimiter = , ... doublequote = True ... escapechar = \\ ... lineterminator = '\r\n' ... skipinitialspace = True ... r = csv.reader(st, dialect=SingleQuoteDialect) r.next() ['EGC', 'SXF', 'BZR', 'BIQ', 'BLL', 'BHX', 'BLQ'] This gives you control over how any craziness gets handled, prescribing escaping, and allowing you to stream in the data from a file if you need. However, if they're airport codes, I suspect the easy route of just using a regex will more than suffice. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Maxim Khitrov wrote: On Sat, Mar 14, 2009 at 2:07 PM, Gary Herron gher...@islandtraining.com wrote: Maxim Khitrov wrote: Very simple question on the preferred coding style. I frequently write classes that have some data members initialized to immutable values. For example: class Test(object): def __init__(self): self.some_value = 0 self.another_value = None Similar effect can be achieved by defining some_value and another_value for the entire class, like so: class Test(object): some_value = 0 another_value = None The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? - Max -- http://mail.python.org/mailman/listinfo/python-list Such things are often called class attributes, and the are fine. If you look through Python's standard library, you will find many examples of class attributes. However, you appear to have either a misuse or misconception of the word immutable' here. Whether the value you assign to a class attribute is mutable or immutable is irrelevant. Also whether you plan on leaving the value constant or not is also not relevant. What does matter is this: If every instance wants access to a single value (immutable or not), use a class attribute, otherwise use an instance attribute. Gary Herron Perhaps a different example would help explain what I'm trying to do: class Case1(object): def __init__(self): self.count = 0 self.list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) class Case2(object): count = 0 list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) for i in xrange(10): c1 = Case1() c2 = Case2() for j in xrange(i): c1.inc() c2.inc() v1, l1 = c1.val() v2, l2 = c2.val() print v1 == v2, l1 == l2 The only difference between Case1 and Case2 classes is where the count and list attributes are defined. You will notice that for an immutable type (count), this doesn't matter. On the last line, v1 == v2 is always True. When the type is mutable (list), you must define it in __init__. This isn't about class attributes or shared instance attributes/constants. This is about a small optimization in defining per-instance variables. This optimization only applies to immutable types. - Max -- http://mail.python.org/mailman/listinfo/python-list But now you are not listening to what people are telling you. It has *nothing* to do with the mutability/immutability of the integer and the list your two classes create. The difference is this: For C1: You create 10 instances of C1. Each one creates its own count, and a list variables, and manipulates them calls to inc and val. Then each on is discarded as you go through the next pass on the outer loop. For C2; You create 10 instances of C2, but these 10 instances each manipulate values created once in the class itself. The values manipulated by one instance of C2 in one pass through the loop are not affected when, on the next pass through the loop, that instance is destroyed and another instance is created. So... If you want a variable that records/supplies some value across *all* instances of a class, use a class variable. (Or use a global variable -- it would have the same effect.) If you want a variable whose value is unique to each instance of a class, then make it an instance variable. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Maxim Khitrov wrote: Perhaps a different example would help explain what I'm trying to do: class Case1(object): def __init__(self): self.count = 0 self.list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) OK, so .count and .list (BAD IDEA TO USE BUILT-IN NAME) are not constants, as you previously implied. class Case2(object): count = 0 list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) for i in xrange(10): You really only need one value of i for a test. But you need multiple instances of each class c1 = Case1() c2 = Case2() c1a, c1b = Case1(), Case1() c2a, c2b = Case2(), Case2() for j in xrange(i): c1.inc() c2.inc() c1a.inc(), c1b.inc() c2a.inc(), c2b,inc() v1, l1 = c1.val() v2, l2 = c2.val() print(c1a.val(), c1b.val(), c2a.val(), c2b.val()) print v1 == v2, l1 == l2 # just look as all four tuples The only difference between Case1 and Case2 classes is where the count and list attributes are defined. and that 'only difference makes a major difference. Make two instances of each class and you will see how. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
little question speed encondings
I know that this can be evident for most of the people but i would like to know the reply and the reasoning if possible: Should my python application have a difference in speed of execution after change the encoding header of the file from nothing (ascii) to latin-1 or utf-8? If yes, only when the .pyc files are created or even with .pyc or .pyo files? Regards, Miguel Angel. -- http://mail.python.org/mailman/listinfo/python-list
Re: finally successful in ods with python, just one help needed.
Hi David, based on your code snippid I added a couple of lines to actually center align text in the merged cell in first row. Please note in the following code that I have added ParagraphProperties in the imports and created one style with textalign=center as an attribute. *** code follows *** import sys from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TableColumnProperties, ParagraphProperties from odf.table import Table, TableRow, TableColumn, TableCell, CoveredTableCell from odf.text import P class makeods: def make_ods(self): ods = OpenDocumentSpreadsheet() col = Style(name='col', family='table-column') col.addElement(TableColumnProperties(columnwidth='1in')) tablecontents = Style(name=Table Contents, family=paragraph) tablecontents.addElement(ParagraphProperties(textalign=center)) table = Table() table.addElement(TableColumn(numbercolumnsrepeated=3, stylename=col)) ods.spreadsheet.addElement(table) # Add first row with cell spanning columns A-C tr = TableRow() table.addElement(tr) tc = TableCell(numbercolumnsspanned=3) tc.addElement(P(stylename=tablecontents, text=ABC1)) tr.addElement(tc) # Uncomment this to more accurately match native file ##tc = CoveredTableCell(numbercolumnsrepeated=2) ##tr.addElement(tc) # Add two more rows with non-spanning cells for r in (2,3): tr = TableRow() table.addElement(tr) for c in ('A','B','C'): tc = TableCell() tc.addElement(P(text='%s%d' % (c, r))) tr.addElement(tc) ods.save(ods-test.ods) m = makeods() m.make_ods() Still the text in the cell is not centered. happy hacking. Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing.sharedctypes and built-in locks
On Mar 14, 7:11 am, Ahmad Syukri bin Abdollah syoc...@gmail.com wrote: I'm trying this on Python 3.0.1 Consider the following code: import multiprocessing as mp def jambu(b,i,gl): for n in range(10): with gl[i]: b[i]+=2 with gl[3-i]: b[3-i]-=1 def main(): b = mp.RawArray('i',4) gl = [] proc = [] for i in range(len(b)): gl.append(mp.Lock()) proc.append(mp.Process(target=jambu,args=(b,i,gl))) for p in proc: p.start() for p in proc: p.join() print(b[:]) print(sum(b[:])) main() (Yes, I'm aware that I didn't pass the lock array as shared variable, but since they're not reassigned, it should be okay) The above code should produce an output like this: [10, 10, 10, 10] 40 Now, in the documentation for multiprocessing module, it says that multiprocessing.Array will automatically create a lock to ensure process-safe synchronization. So I suppose the above code can be simplified as follows: import multiprocessing as mp def jambu(b,i): for n in range(10): b[i]+=2 b[3-i]-=1 def main(): b = mp.Array('i',4) proc = [] for i in range(len(b)): gl.append(mp.Lock()) proc.append(mp.Process(target=jambu,args=(b,i))) for p in proc: p.start() for p in proc: p.join() print(b[:]) print(sum(b[:])) main() The output of this second code isn't consistent with the first one, implying multiprocessing.Array (or even multiprocessing.Value; I've also tried with this one) isn't as atomic as I understand it should be. So what is the actual meaning of having a Lock object which will be used to synchronize access to the value? Is it only for getting, and not for assigning values? Regards, Ahmad Syukri Your code hung on my machine. The call to 'main()' should be in an 'if __name__' block: if __name__== '__main__': main() Is it possible you are just seeing the effects of the non-atomic '__iadd__' operation? That is, the value is read, added, and written at different times, between which other processes might have intervened. -- http://mail.python.org/mailman/listinfo/python-list
Re: little question speed encondings
Linos wrote: I know that this can be evident for most of the people but i would like to know the reply and the reasoning if possible: Should my python application have a difference in speed of execution after change the encoding header of the file from nothing (ascii) to latin-1 or utf-8? If yes, only when the .pyc files are created or even with .pyc or .pyo files? There _might_ be a difference in the time taken to parse the .py file to create the .pyc, but I doubt it would be significant, and it would be done only once. It would have no effect on the speed of the resulting .pyc file. Recommendation: use UTF-8. -- http://mail.python.org/mailman/listinfo/python-list
tkinter: start window without window managers frame (linux,KDE)
Hi, is tkinter able to start a windows without the frame of the according window manager? (only needed for Linux, KDE desktop) The window should only be closed by click on a button within the window! I should not be moved, it should not be close, ... and so on. The solution would be: start without the frame of the window manager! thx Ekkard -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Gary Herron gher...@islandtraining.com writes: But now you are not listening to what people are telling you. It has *nothing* to do with the mutability/immutability of the integer and the list your two classes create. No! Did you run the code he posted? The immutability makes all the difference. The difference is this: For C1: You create 10 instances of C1. Each one creates its own count, and a list variables, and manipulates them calls to inc and val. Then each on is discarded as you go through the next pass on the outer loop. For C2; You create 10 instances of C2, but these 10 instances each manipulate values created once in the class itself. The values manipulated by one instance of C2 in one pass through the loop are not affected when, on the next pass through the loop, that instance is destroyed and another instance is created. If you try it, you will see that this isn't true for C2, in the case of the immutable object. That's because given this code: class Foo(object): x = 0 def inc(self): self.x += 1 when inc is called, it creates an 'x' attribute on the instance, even though one didn't exist before, and it doesn't change the value of the class attribute. If 'x' were a list, the new instance attribute would refer to the same object as the class attribute, so it wouldn't make much difference. But when the original class attribute was an immutable object, they become 'decoupled'. I think this code is in poor taste: it's clear that it will confuse people (which is what Maxim was asking about in the first place). -M- -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sat, Mar 14, 2009 at 4:31 PM, Gary Herron gher...@islandtraining.com wrote: Perhaps a different example would help explain what I'm trying to do: class Case1(object): def __init__(self): self.count = 0 self.list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) class Case2(object): count = 0 list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) for i in xrange(10): c1 = Case1() c2 = Case2() for j in xrange(i): c1.inc() c2.inc() v1, l1 = c1.val() v2, l2 = c2.val() print v1 == v2, l1 == l2 The only difference between Case1 and Case2 classes is where the count and list attributes are defined. You will notice that for an immutable type (count), this doesn't matter. On the last line, v1 == v2 is always True. When the type is mutable (list), you must define it in __init__. This isn't about class attributes or shared instance attributes/constants. This is about a small optimization in defining per-instance variables. This optimization only applies to immutable types. - Max -- http://mail.python.org/mailman/listinfo/python-list But now you are not listening to what people are telling you. It has *nothing* to do with the mutability/immutability of the integer and the list your two classes create. The difference is this: For C1: You create 10 instances of C1. Each one creates its own count, and a list variables, and manipulates them calls to inc and val. Then each on is discarded as you go through the next pass on the outer loop. Correct, though the discarded part makes no difference. For C2; You create 10 instances of C2, but these 10 instances each manipulate values created once in the class itself. The values manipulated by one instance of C2 in one pass through the loop are not affected when, on the next pass through the loop, that instance is destroyed and another instance is created. So... Incorrect. Only the count is unaffected, which was the whole point of my question. If you want a variable that records/supplies some value across *all* instances of a class, use a class variable. (Or use a global variable -- it would have the same effect.) If you want a variable whose value is unique to each instance of a class, then make it an instance variable. Gary Herron I never thought that such simple question would turn into this. David Stanek gave me the answer I was looking for (thank you). You, on the other hand, are still going after the wrong issue. Once again, here's the same example using Terry's suggestions. No class instances are being destroyed until the very end. class Case1(object): def __init__(self): self.count = 0 self.list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) class Case2(object): count = 0 list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) c1a, c1b = Case1(), Case1() c2a, c2b = Case2(), Case2() c1a.inc(), c1b.inc() c2a.inc(), c2b.inc() print c1a.val(), c1b.val(), c2a.val(), c2b.val() And the output: (1, [1]), (1, [1]), (1, [1, 1]), (1, [1, 1]) The first element of every tuple is the same. This is the count, which is immutable. The second element is not the same for c2[a,b]. This is the list, which is mutable. My question was about immutable values, and for those the who cases are identical. In the second case, c2a and c2b begin with count referring to the same '0' object. This is where the time and space savings are made. But because that object is immutable, when += 1 operation is performed, a copy is made for each instance. At that point, I am not sharing any values between class instances. The whole point is that this is a quick(er) way of providing initial values for class instance variables when those values are immutable. When/if that initial value is changed, a copy is made. In Case1, that copy is made from the very begging in __init__. Please try to understand what the question is about before responding to it. - Max -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sat, Mar 14, 2009 at 5:38 PM, Matthew Woodcraft matt...@woodcraft.me.uk wrote: Gary Herron gher...@islandtraining.com writes: I think this code is in poor taste: it's clear that it will confuse people (which is what Maxim was asking about in the first place). Yes, I see that now, thanks :) - Max -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Hallöchen! Maxim Khitrov writes: [...] The advantage of doing this is that the assignments are evaluated once and thus the creation of that class is a bit faster. Access is still performed through self.some_value and self.another_value. Is there a reason to prefer the first style over the second? I think that tools like epydoc can generate more accurate API documentation if you write them as instance attributes. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bron...@jabber.rwth-aachen.de -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree: How to return only unicode?
Hallöchen! Stefan Behnel writes: Torsten Bronger wrote: [...] My problem is that if there is only ASCII, these methods return ordinary strings instead of unicode. So sometimes I get str, sometimes I get unicode. Can one change this globally so that they only return unicode? That's a convenience measure to reduce memory and processing overhead. But is this really worth the inconsistency of having partly str and partly unicode, given that the common origin is unicode XML data? Could you explain why this is a problem for you? I feed ElementTree's output to functions in the unicodedata module. And they want unicode input. While it's not a big deal to write e.g. unicodedata.category(unicode(my_character)), I find this rather wasteful. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bron...@jabber.rwth-aachen.de -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree: How to return only unicode?
Torsten Bronger wrote: I parse an XML file with ElementTree and get the contets with the .attrib, .text, .get etc methods of the tree's nodes. Additionally, I use the find and findtext methods. My problem is that if there is only ASCII, these methods return ordinary strings instead of unicode. So sometimes I get str, sometimes I get unicode. Can one change this globally so that they only return unicode? That's a convenience measure to reduce memory and processing overhead. Could you explain why this is a problem for you? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: finally successful in ods with python, just one help needed.
Krishnakant hackin...@gmail.com writes: based on your code snippid I added a couple of lines to actually center align text in the merged cell in first row. Sorry, guess I should have verified handling all the requirements :-) I think there's two issues: * I neglected to add the style I created to the document, so even in my first example, columns had a default style (not the 1in) style I thought I was creating. * I don't think you want a paragraph style applied to the paragraph text within the cell, but to the cell as a whole. I think if you just try to associate it with the text.P() element the width of the paragraph is probably just the text itself so there's nothing to center, although that's just a guess. I've attached an adjusted version that does center the spanned cell for me. Note that I'll be the first to admit I don't necessarily understand all the ODF style rules. In particular, I got into a lot of trouble trying to add my styles to the overall document styles (e.g., ods.styles) which I think can then be edited afterwards rather than the automatic styles (ods.automaticstyles). The former goes into the styles.xml file whereas the latter is included right in contents.xml. For some reason using ods.styles kept causing OpenOffice to crash trying to load the document, so I finally just went with the flow and used automaticstyles. It's closer to how OO itself creates the spreadsheet anyway. -- David from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TableColumnProperties, ParagraphProperties from odf.table import Table, TableRow, TableColumn, \ TableCell, CoveredTableCell from odf.text import P def make_ods(): ods = OpenDocumentSpreadsheet() col = Style(name='col', family='table-column') col.addElement(TableColumnProperties(columnwidth='1in')) centered = Style(name='centered', family='table-cell') centered.addElement(ParagraphProperties(textalign='center')) ods.automaticstyles.addElement(col) ods.automaticstyles.addElement(centered) table = Table() table.addElement(TableColumn(numbercolumnsrepeated=3, stylename=col)) ods.spreadsheet.addElement(table) # Add first row with cell spanning columns A-C tr = TableRow() table.addElement(tr) tc = TableCell(numbercolumnsspanned=3, stylename=centered) tc.addElement(P(text=ABC1)) tr.addElement(tc) # Add two more rows with non-spanning cells for r in (2,3): tr = TableRow() table.addElement(tr) for c in ('A','B','C'): tc = TableCell() tc.addElement(P(text='%s%d' % (c, r))) tr.addElement(tc) ods.save(ods-test.ods) if __name__ == __main__: make_ods() -- http://mail.python.org/mailman/listinfo/python-list
how to repeat function definitions less
I'm doing this in my code, how to make it define all this functions for me with lambda, I've been up for a while and cant seem to figure it out, whats the most efficient way to do it? with lambda? how? thx def red(self,value,color='red',level='INFO'): self.write(value,color,level) def gold(self,value,color='gold',level='INFO'): self.write(value,color,level) def green(self,value,color='green',level='INFO'): self.write(value,color,level) def blue(self,value,color='blue',level='INFO'): self.write(value,color,level) def yellow(self,value,color='yellow',level='INFO'): self.write(value,color,level) def purple(self,value,color='purple',level='INFO'): self.write(value,color,level) def w_red(self,value,color='white_on_red',level='INFO'): self.write(value,color,level) def w_gold(self,value,color='white_on_gold',level='INFO'): self.write(value,color,level) def w(self,value,color=red,level=INFO): self.write(value,color,level) def write(self,value,color=red,level=INFO): write - output message,take value string or list,color= self._hero(value,color,level) -Alex Goretoy http://www.goretoy.com -- http://mail.python.org/mailman/listinfo/python-list
TypeError when creating frozenset with no hash
I was going to file a bug report for this, but then I wondered if it was considered normal behaviour. Am I wrong in thinking there should be a better error message? class NoHash: ... def __hash__(self): ... pass ... frozenset([NoHash()]) Traceback (most recent call last): File stdin, line 1, in module TypeError: an integer is required I understand that there is a real problem here (in my code I had forgotten the return); the issue is whether the stack trace should contain some reference to __hash__ or similar. Perhaps that is impossible for containers implemented in C? Thanks, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: start window without window managers frame (linux,KDE)
Ekkard Gerlach wrote: Hi, is tkinter able to start a windows without the frame of the according window manager? (only needed for Linux, KDE desktop) The window should only be closed by click on a button within the window! I should not be moved, it should not be close, ... and so on. The solution would be: start without the frame of the window manager! thx Ekkard Try a google search on: tkinter overrideredirect -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: how to repeat function definitions less
I'm doing this in my code, how to make it define all this functions for me with lambda, I've been up for a while and cant seem to figure it out, whats the most efficient way to do it? with lambda? how? thx def red(self,value,color='red',level='INFO'): self.write(value,color,level) def gold(self,value,color='gold',level='INFO'): self.write(value,color,level) ... How about using __getattr__? Something like: def __getattr(self, attr): if attr in (red, gold, ...): return self.write_color def write_color(self, value, color, level=INFO): self.write(value,color,level) That still leaves you with the need to pass in the color though: self.red(value, red) which violates the DRY principle. I'm sure brighter minds than mine will come up with a better solution. -- Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: start window without window managers frame (linux,KDE)
Martin P. Hellwig schrieb: Try a google search on: tkinter overrideredirect thx! That's it! -- http://mail.python.org/mailman/listinfo/python-list
Re: how to repeat function definitions less
I would suggest using functools.partial like this from functools import partial class Foo(object): #... red = partial(color='red') -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
Maxim Khitrov wrote: On Sat, Mar 14, 2009 at 4:31 PM, Gary Herron gher...@islandtraining.com wrote: Perhaps a different example would help explain what I'm trying to do: class Case1(object): def __init__(self): self.count = 0 self.list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) class Case2(object): count = 0 list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) for i in xrange(10): c1 = Case1() c2 = Case2() for j in xrange(i): c1.inc() c2.inc() v1, l1 = c1.val() v2, l2 = c2.val() print v1 == v2, l1 == l2 The only difference between Case1 and Case2 classes is where the count and list attributes are defined. You will notice that for an immutable type (count), this doesn't matter. On the last line, v1 == v2 is always True. When the type is mutable (list), you must define it in __init__. This isn't about class attributes or shared instance attributes/constants. This is about a small optimization in defining per-instance variables. This optimization only applies to immutable types. - Max -- http://mail.python.org/mailman/listinfo/python-list But now you are not listening to what people are telling you. It has *nothing* to do with the mutability/immutability of the integer and the list your two classes create. The difference is this: For C1: You create 10 instances of C1. Each one creates its own count, and a list variables, and manipulates them calls to inc and val. Then each on is discarded as you go through the next pass on the outer loop. Correct, though the discarded part makes no difference. For C2; You create 10 instances of C2, but these 10 instances each manipulate values created once in the class itself. The values manipulated by one instance of C2 in one pass through the loop are not affected when, on the next pass through the loop, that instance is destroyed and another instance is created. So... Incorrect. Only the count is unaffected, which was the whole point of my question. No, you are still misinterpreting your results. But you can be forgiven because this is quite a subtle point about Python's attribute access. Here's how it works: On access, self.count (or self.anything) attempts to find count in the instance variable self. If that fails, it attempts to lookup count in the class. If that fails it attempts to lookup count in a global context, ...).However, on assignment self.count=... *must* necessarily mean the local instance variable -- no defaulting to a class variable on assignment. So ... With your class C2, the line self.count +=1 which really translates into self.count = self.count + 1 has two different actions depending on the pass through the inner loop. The first time through (when no instance variable count exists), that line means create and assign instance variable count = class variable count + 1 and succeeding passes through (now that self.count is defined) become instance count = instance count +1 which is now the same as your class C1 To complete the subtlety, if you were to do self.list = self.list + [i] you would see list behaving just as count. However since, list.append(...) is an in-place operation, and not an assignment, the creation of an instance variable is not provoked, and so all instances continue using the single class variable. There is a lesson to be learned here. Class variables can't be the target of an assignment through self, because that creates an instance variable. You can, however, assign to a class variable through the class: C2.count = ... If you want a variable that records/supplies some value across *all* instances of a class, use a class variable. (Or use a global variable -- it would have the same effect.) If you want a variable whose value is unique to each instance of a class, then make it an instance variable. Gary Herron I never thought that such simple question would turn into this. David Stanek gave me the answer I was looking for (thank you). You, on the other hand, are still going after the wrong issue. Once again, here's the same example using Terry's suggestions. No class instances are being destroyed until the very end. class Case1(object): def __init__(self): self.count = 0 self.list = [] def inc(self): self.count += 1 self.list.append(self.count) def val(self): return (self.count, self.list) class Case2(object): count = 0 list = [] def inc(self): self.count += 1