Re: [Tutor] quirky multiple inheritance example!?
Works for me. Each class must call super(...).__init__(). The first arg class A(object): ... def __init__(self): ... print 'A.__init__()' ... super(A, self).__init__() ... class B(object): ... def __init__(self): ... print 'B.__init__()' ... super(B, self).__init__() ... class C(A, B): ... def __init__(self): ... print 'C.__init__()' ... super(C, self).__init__() ... C() C.__init__() A.__init__() B.__init__() __main__.C object at 0x00A32BB0 Thats almost exactly what I did but with several extra MI classes to test things like diamond lattice etc. BUT I say almost because the one thing I didn't do is call super() at the highest level. 'A' and 'B' in your case. DUH! Its obvious when I look at it now but in my mind I was thinking they didn't have a superclass, but of course they do - object! Having said that I still don't like that mechanism since it makes the behaviour of the subclass depend on the implementation of the superclass. That is, if I choose to create a sub class of someone elses class then a call to super will only work if the other person has written their class with a call to super... not good. Whereas if I call the class init explicitly it works regardless of how the superclass is written. Thanks for a 'super' explanation Kent :-) Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
That tracks my feelings. I don't find Programming Python to be very useful. It's not the sort of reference book that, say, Programming Perl hasten to add, I've seen enough people swear how much they love that book, that this may just be idiosyncratic to me.) One thing to note about PP is that it is really two very different books. It was originally the second book ever published on Python and as such tried to be both tutorial and reference and cookbook. Naturally it failed (although not too badly or Python would probably not have taken off!) on asll counts. By the time the current (2nd edition) came out there were lots of Python tutorials so this version aims at being an advanced topic guide. It looks at lots of areas that were not very well covbered in other tutorials. It is not a tutorial and not really a reference guide either, its probably closest to the cookbook in spirit but less specific. There is a 3rd edition coming out that is allegedly going to target even more advanced topics and I have my name down with Amazon for that one... :-) I think a good Python *reference* book is invaluable to any Python programmer. And to me, that book is Python in a Nutshell. Me too. Python Essential Reference - When I first started playing with Python, ... The Third Edition is coming out February 24, which means it will be the most current Python reference book, when published. I would be surprised if it didn't cover through 2.4. According to Amazon it does... But despite opwning both of the prevbious editions I don't think I'll be buying this one. The Nutshell is still current enough for me - all the really big changes in Puython happened in 2.2! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] pyGtk using combobox
Hi, I would like to make a combobox with a list of strings, but I have many problems with it. I know how to make the combobox and how to add strings, but is it possible to get a list of strings from the combobox and also is it possible to update the combobox with a list of strings? (something like combo.set_popdown_strings(list)) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quirky multiple inheritance example!?
Alan Gauld wrote: Having said that I still don't like that mechanism since it makes the behaviour of the subclass depend on the implementation of the superclass. That is, if I choose to create a sub class of someone elses class then a call to super will only work if the other person has written their class with a call to super... not good. Whereas if I call the class init explicitly it works regardless of how the superclass is written. It's worse than that - with MI if you call __init__() explicitly and the base classes call super().__init__(), one of the base class __init__() methods will be called twice. See http://fuhm.net/super-harmful/ for an example. super() only works correctly when all the classes involved use it. My conclusion is that it is best reserved for the times it is actually needed (with diamond MI), and direct calling of the base class method should be used everywhere else. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quirky multiple inheritance example!?
It's worse than that - with MI if you call __init__() explicitly and the base classes call super().__init__(), one of the base class __init__() methods will be called twice. See http://fuhm.net/super-harmful/ for an example. Excellent link Kent. This just highlights how woefully inadequate the official documentation for super() is! It has also confirmed my belief that I'm better off sticking to explicit calls and worrying about diamond lattice situations only when I need to (which is very rarely indeed!). Its also confirmed that I did the right thing by ignoring super in my tutor! Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quirky multiple inheritance example!?
Alan Gauld wrote: It's worse than that - with MI if you call __init__() explicitly and the base classes call super().__init__(), one of the base class __init__() methods will be called twice. See http://fuhm.net/super-harmful/ for an example. Excellent link Kent. This just highlights how woefully inadequate the official documentation for super() is! It has also confirmed my belief that I'm better off sticking to explicit calls and worrying about diamond lattice situations only when I need to (which is very rarely indeed!). That is my conclusion too. But to balance it out, here is a page that recommends using super() everywhere (in the Chandler project): http://wiki.osafoundation.org/bin/view/Projects/UsingSuper and here is the heated discussion on python-dev sparked by the Super Considered Harmful essay: http://mail.python.org/pipermail/python-dev/2005-January/050656.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter, widgets not displaying...
Hugo González Monteverde wrote: Hi All, I wrote a small turn delivering graphical app that is supposed to display turns in a queue. def insert(self, turn_string): Insert a new turn into the queue, move the rest upwards, delete oldest. This is overly complicated: current_values = [self.read_panel(i) for i in range(len(self.canvases))] You are going to throw away the first value, there is no need to read it. next_values = current_values[:] There is no need to copy current_values since it is a brand new list already. next_values[:-1] = current_values[1:] next_values[-1] = turn_string This works but you could just copy the part of current_values you want and append turn_string. Taking all this together, you can write just next_values = [self.read_panel(i) for i in range(1, len(self.canvases))] next_values.append(turn_string) But there is a deeper issue here. You seem to be writing some kind of simulation. You might want to consider separating your model - the data and mechanics of the simulation - from the GUI - the visual representation. The way you have it now, the data is stored in the GUI itself. This leads to tight coupling between the model and the GUI. It will be hard to test the model or to put a different front-end on it, and hard to have a clean conceptual model of the simulation. For example, you could have this model class: class QueueModel(object): def __init__(self, length=4): self.data = [None * length ] def insert(self, item): self.data.pop() # remove the first item self.data.append(item) Then in your GUI, your insert() method would become update(self, model). Or maybe instantiate the GUI giving it an instance of the model. Your main program would drive them both. Oversimplifying by leaving out the threading, it would look like model = QueueModel(length=4) gui = TurnQueue(model, pw=200, ph=100) for i in range(100): model.insert(str(i)) gui.update() sleep(0.2) As the model develops, this separation from the GUI will make it much easier to work with. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter, widgets not displaying...
John Fouhy wrote: If you want to do multithreaded programming with a GUI, one good way is to use .after_idle. ie, instead of myturns.insert(str(i)), do top.after_idle(myturns.insert, str(i)) (I think this is the right syntax). This will cause the mainloop thread to run the code instead. Another way to do this without a separate thread is to use top.after() to schedule the inserts. Schedule the first one before calling mainloop(), and have each insert schedule the next one. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
Isn't there supposed to be a new edition of the Nutshell book coming out? I was kinda hanging back for that one...Carl Badgley ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
yeah, one of the guys that posted earlier mentioned late feb as a release of the new one. i think i am going to go ahead and get the cookbook now, and then pick up the new nutshell later. sk On Fri, 2006-02-10 at 09:56 -0600, [EMAIL PROTECTED] wrote: Isn't there supposed to be a new edition of the Nutshell book coming out? I was kinda hanging back for that one... Carl Badgley ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
See I couldn't tell if he was talking about the Nutshell book or the Python Essential Reference book...thanksCarlOn 2/10/06, nephish [EMAIL PROTECTED] wrote:yeah, one of the guys that posted earlier mentioned late feb as a release of the new one. i think i am going to go ahead and get thecookbook now, and then pick up the new nutshell later.sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
nephish wrote: yeah, one of the guys that posted earlier mentioned late feb as a release of the new one. i think i am going to go ahead and get the cookbook now, and then pick up the new nutshell later. It's the third edition of Python Essential Reference that is due Feb 24. Judging from his posts to comp.lang.python, Alex Martelli is working on a second edition of the Nutshell - or at least feeling guilty about *not* working on it - but I haven't seen any dates. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter, widgets not displaying...
Hi Kent and John, Thanks a lot for the advice on how to improve my program. I will look into separating the data and model as John suggests here. I didn't know about after_idle() and after(); seems that dir()'ing the classes sometimes gives out a lot more information than you can chew at any given time :) Thanks, Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] cgi script: how to continue a process in the background and return from cgi script
Hello, I need some pointers in the right direction for the following problem: I have a cgi script which reads in some form elements, uses them to compose an SQL query, sends that query to the postgresql backend, writes the results into a temporary file and sends a mail to the user with the link to the file. The main block of the program is very simple formulaire = cgi.FieldStorage(keep_blank_values=1) adresse=formulaire[email1].value if adresse == : print_error_adresse() else: requete=compose_req(formulaire) #function composing the query print_info_mail(adresse, requete) #function printing a web page telling the user that the query is ongoing and that she will be advised by email when it is done results=req(requete, 91) #function launching the query fname=fichier_resultats(results) #function writing the results to a file if(fname): envoi_res(fname, requete, adresse) #function sending the email to the user The problem I have is that the process obviously remains active throughout the entire program, including the query, and that I, therefore, sometimes get timeout problems with apache. So, what I would like to do is to go through all the steps until the printing of the web page and then somehow fork the process of querying so that the cgi script terminates and the querying, result file writing and email sending are done in the background. I have no experience with either forking or threading, but the way I understand them any child processes die when the parent dies. I have tried the recipe in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 which is supposed to fork a process as daemon, thus decoupling it from the calling terminal, but I don't seem to get it to work (I get one defunct process and the child process, but the timeout problem remains). I am also not sure this is actually what I need (I don't know if what I describe above is decoupling from the calling terminal). So, could some give me a pointer to possible solutions ? Do I have to make the last part of my program a seperate program and go through a system call ? Thank you ! Moritz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
Thanks for the info.../sigh well I shall be waiting with bells onCarlOn 2/10/06, Kent Johnson [EMAIL PROTECTED] wrote:nephish wrote: yeah, one of the guys that posted earlier mentioned late feb as a release of the new one. i think i am going to go ahead and get the cookbook now, and then pick up the new nutshell later.It's the third edition of Python Essential Reference that is due Feb 24. Judging from his posts to comp.lang.python, Alex Martelli is working ona second edition of the Nutshell - or at least feeling guilty about*not* working on it - but I haven't seen any dates.Kent___ Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
Greetings: I have been programming in Python for about a year. We use Python 2.3; we haven't migrated to 2.4 because the Real-time OS we use in our test systems doesn't yet support it. I have the four O'Reilly 'standards' as well (Nutshell, Learning, Cookbook, and Programming). I use Nutshell and Learning the most by far. When I'm looking for a detailed example of some implementation I will look through Cookbook or Programming, but when I need to look up usage or syntax, or remind myself how some feature works, I go to Nutshell first and then Learning I use them both nearly every day. I find that Nutshell supports 2.3 very well. Don't know about 2.4. Another book I have just found that may turn out useful is Python Programming Patterns by Thomas W. Christopher, published by Prentice Hall PTR. From the reviews I've read, It isn't really a 'design patterns' book in the usual sense, but it contains good demonstrations of applying Python to solve real problems. I don't know for myself yet, as I just ordered it yesterday. We'll see. Regards, Barry [EMAIL PROTECTED] 541-302-1107 Never trust anything that can think for itself if you can't see where it keeps its brain JK Rowling -Original Message- -- Message: 10 Date: Fri, 10 Feb 2006 02:18:20 + From: nephish [EMAIL PROTECTED] Subject: [Tutor] nutshell review To: tutor@python.org Message-ID: [EMAIL PROTECTED] Content-Type: text/plain lo there, i know this comes up from time to time. i am considering buying 'python in a nutshell'. All the reviews i have read for it are very good. But it only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4 at home. As good a reference as it is, is it too dated to be that good still ? i have 'Learning Python' and 'Programming Python'. Learning is awesome for me, Programming is a bit over my head. any suggestions? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] cannonical matrix representation?
What's the best way to represent a matrix M with 4 dimensions, such as M[x][y][z][t] where each element in the sparse matrix could be a simple number, or could be an executable Python function snipped that returns a value when that cell is evaluated? The user of the program will type in Python functions to be inserted into particular cells in the 4-D matrix. I did't see any package that exactly does this; do I write my own Matrix class and base it on lists? Thanks! -Mike p.s. This seems to me like it ought to be built into the base language - multidimensional object arrays. (Indeed, maybe it is, and I'm just too dense to notice!) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cgi script: how to continue a process in the backgrou nd and return from cgi script
I think you need to close the IO streams before forking the child process. Something like sys.stdout.flush() sys.stdout.close() sys.stdin.close() sys.stderr.close() os.close(0) os.close(1) os.close(2) This is probably not the best way, but it works for me. Beilin Zhang -Original Message- From: Moritz Lennert [mailto:[EMAIL PROTECTED] Sent: Friday, February 10, 2006 8:03 AM To: tutor@python.org Subject: [Tutor] cgi script: how to continue a process in the background and return from cgi script Hello, I need some pointers in the right direction for the following problem: I have a cgi script which reads in some form elements, uses them to compose an SQL query, sends that query to the postgresql backend, writes the results into a temporary file and sends a mail to the user with the link to the file. The main block of the program is very simple formulaire = cgi.FieldStorage(keep_blank_values=1) adresse=formulaire[email1].value if adresse == : print_error_adresse() else: requete=compose_req(formulaire) #function composing the query print_info_mail(adresse, requete) #function printing a web page telling the user that the query is ongoing and that she will be advised by email when it is done results=req(requete, 91) #function launching the query fname=fichier_resultats(results) #function writing the results to a file if(fname): envoi_res(fname, requete, adresse) #function sending the email to the user The problem I have is that the process obviously remains active throughout the entire program, including the query, and that I, therefore, sometimes get timeout problems with apache. So, what I would like to do is to go through all the steps until the printing of the web page and then somehow fork the process of querying so that the cgi script terminates and the querying, result file writing and email sending are done in the background. I have no experience with either forking or threading, but the way I understand them any child processes die when the parent dies. I have tried the recipe in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 which is supposed to fork a process as daemon, thus decoupling it from the calling terminal, but I don't seem to get it to work (I get one defunct process and the child process, but the timeout problem remains). I am also not sure this is actually what I need (I don't know if what I describe above is decoupling from the calling terminal). So, could some give me a pointer to possible solutions ? Do I have to make the last part of my program a seperate program and go through a system call ? Thank you ! Moritz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cgi script: how to continue a process in the background and return from cgi script
So, could some give me a pointer to possible solutions ? Do I have to make the last part of my program a seperate program and go through a system call ? Hi, I have had this problem before. The timeout problem with Apache remains because STDOUT of both child and the parent are open. Apache keeps thinking the CGI is still sending data until the filehandle is closed. I have solved it in the pas using this recipe, which is similar to the one you used before: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 Hope that helps, Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Iterating over a string: index and value
I seem to recall reading somewhere that it is possible to concurrently generate the index and value of a strings characters in a single for statement. Is this true or did imagine it? Here is the scenario: Given an ASCII string of arbitrary length and content, generate a sequence of tuples whose elements are: the index of each character in the string, and data based on the ordinal value of the character in the ASCII collating sequence. The brute force way to do this is tuplseq = () for idx in mystr: char = mystr[idx] ordval = ord(char) data = ""> tuplseq.append(idx, data) Is there a way to generate the character (or its ord value) along with the index? E.g.: tuplseq = () for idx ordval in X: tuplseq.append(idx, process(ordval)) Where X is some construct using mystr. BTW, this is for internal software for our test group. Thanks in advance for your help. Barry [EMAIL PROTECTED] 541-302-1107 Never trust anything that can think for itself if you can't see where it keeps its brain JK Rowling ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IDE - Editors - Python
Try with Python Card. ; )-- Edgar A. Rodriguez V. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating over a string: index and value
Here's a list comprehension which does it: print [(i, ord(v)) for i, v in enumerate(abcdefg)][(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)]and a for loop: for i, v in enumerate(abcdefg):... tuplseq.append((i, ord(v)))... tuplseq[(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)]how's that? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Change files
I wrote a little program that replaces all files called 'abcde' with the file in the directory from which you riun the program. However it does not find them (there is another one). What have I done wrong :- #this program copies the file x to all other places in the directory. #however it does not go to the right places def getfiles(file1,file2,top): for root, dirs, files in os.walk(top): for name in dirs: for name in files: if name == file1:shutil.copy(file2,name) print "copied one file" import os import shutil #main top = '/home' a = os.getcwd() filename = 'abcde' file1 = filename file2 = a+'/'+filename getfiles(file1, file2,top) print "finished" To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Trying a csv error
Hello: I'm using the csv module, and resources are imported as in import csv My exception trapping uses etype, value, tb = sys.exc_info() and I'm getting the following value = newline inside string type = _csv.Error I would like to proceed with the assumption for now that this error should not abort processing. The relevant code snippet is as follows: while(1): try: reader.next() ## csv object method except StopIteration: break I'd like to do the following while(1): try: reader.next() ## csv object method except cvs._csv.Error: ## or something like this print bad csv record, skipping continue except StopIteration: break The problem is that python does not recognize the error objects and gives me: 'module' object has no attribute '_csv'. Any ideas on how to trap this error? Thanks tim -- Tim Johnson [EMAIL PROTECTED] http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating over a string: index and value
Adam, That is super! Just what I was looking for. Thanks! And whaddya know? There it is in the Python 2.3 Library reference, section 2.1! Regards, Barry [EMAIL PROTECTED] 541-302-1107 Never trust anything that can think for itself if you can't see where it keeps its brain JK Rowling From: Adam [mailto:[EMAIL PROTECTED] Sent: Friday, February 10, 2006 1:42 PM To: Carroll, Barry Cc: tutor@python.org Subject: Re: [Tutor] Iterating over a string: index and value Here's a list comprehension which does it: print [(i, ord(v)) for i, v in enumerate(abcdefg)] [(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)] and a for loop: for i, v in enumerate(abcdefg): ... tuplseq.append((i, ord(v))) ... tuplseq [(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)] how's that? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cannonical matrix representation?
On 2/10/06, Mike Cheponis [EMAIL PROTECTED] wrote: What's the best way to represent a matrix M with 4 dimensions, such as M[x][y][z][t] where each element in the sparse matrix could be a simple number, or could be an executable Python function snipped that returns a value when that cell is evaluated? The user of the program will type in Python functions to be inserted into particular cells in the 4-D matrix. I did't see any package that exactly does this; do I write my own Matrix class and base it on lists? Thanks! -Mike If it is a truly sparse matrix, I would use a dictionary with tuples as keys; i.e., m{(x, y, z, t) = element} André p.s. This seems to me like it ought to be built into the base language - multidimensional object arrays. (Indeed, maybe it is, and I'm just too dense to notice!) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying a csv error
I'd like to do the following while(1): try: reader.next() ## csv object method except cvs._csv.Error: ## or something like this print bad csv record, skipping continue except StopIteration: break The problem is that python does not recognize the error objects and gives me: 'module' object has no attribute '_csv'. Any ideas on how to trap this error? Hi Tim, According to the bottom of: http://www.python.org/doc/lib/csv-contents.html you should be able to check for csv.Error. The csv module defines the following exception: exception Error Raised by any of the functions when an error is detected. Here's what it looks like: ## import csv csv.Error class _csv.Error at 0x81b4f8c ## So internally, csv.Error is the thing you've been seeing, but from the API, you should try to ignore that particular internal implementation detail, and just use csv.Error instead. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cannonical matrix representation?
p.s. This seems to me like it ought to be built into the base language - multidimensional object arrays. The only languages I know that truly support anything like what you want are programmes like Mathematica and arguably MS Excel Basic... There is a pseudo mathematica somewhere in Python but otherwise its roll your own time ... I think... Which usually means its time for somebody to find a ready wrapped solution :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating over a string: index and value
generate the index and value of a string's characters in a single for statement. Is this true or did imagine it? for i,c in enumerate('fred'): print i,c ... 0 f 1 r 2 e 3 d Like that? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying a csv error
Hi Danny: Thanks! tim (who_should_have_read_the_docs) * Danny Yoo [EMAIL PROTECTED] [060210 13:56]: I'd like to do the following while(1): try: reader.next() ## csv object method except cvs._csv.Error: ## or something like this print bad csv record, skipping continue except StopIteration: break The problem is that python does not recognize the error objects and gives me: 'module' object has no attribute '_csv'. Any ideas on how to trap this error? Hi Tim, According to the bottom of: http://www.python.org/doc/lib/csv-contents.html you should be able to check for csv.Error. The csv module defines the following exception: exception Error Raised by any of the functions when an error is detected. Here's what it looks like: ## import csv csv.Error class _csv.Error at 0x81b4f8c ## So internally, csv.Error is the thing you've been seeing, but from the API, you should try to ignore that particular internal implementation detail, and just use csv.Error instead. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson [EMAIL PROTECTED] http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting long string into same len parts
Aha!!! I believe this is what I was looking for in the first place (not that I will use it anyway, given the alternatives provided by others). I guess that coming from a Perl background, which as you know includes regexes as part of the core language, you tend to look to all solutions through this lens. I faced this problem before and solved it using regexes but could not remember how. Your re.findall() suggestion is nice though. Very clean. Thanks Danny. On Wed, 2006-02-08 at 18:55 -0800, Danny Yoo wrote: On Wed, 8 Feb 2006, Victor Bouffier wrote: Hi to all, I'd like to split a long string into equally long strings (len(str) = 3). I did the following using regexes: n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf' o = re.split(r'(...)', n) print o ['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '', 'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq', '', 'w0s', '', 'dq3', '', 'zjf', ''] Which gives me empty strings between each value. Hi Victor, Try using re.findall() instead of re.split(). The behavior you're seeing with split is perfectly logical: each pair of empty strings is being split by that three-character sequence. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting long string into same len parts
On Thu, 2006-02-09 at 09:45 +, Alan Gauld wrote: Define easier :-) Right! You could just use string slicing and a stepsize of 3 in range: lst = [mystring[index : index+3] for index in range(0,len(mystring),3)] Ever since I found them, list comprehensions are my favorites. ... and you still have problems where the string is not exactly divisible by 3, should you add padding? Alan, I understand where you are coming from. However, in this case I don't have a problem since the incoming string will always be divisible by 3, in this particular case. Thanks for pointing it out though. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cannonical matrix representation?
| 3. cannonical matrix representation? (Mike Cheponis) | | What's the best way to represent a matrix M with 4 dimensions, such | as M[x][y][z][t] where each element in the sparse matrix could be a | simple number, or could be an executable Python function snipped that | returns a value when that cell is evaluated? | | The user of the program will type in Python functions to be inserted | into particular cells in the 4-D matrix. | | I did't see any package that exactly does this; do I write my own | Matrix class and base it on lists? I don't know how full-blown of a solution that you need, but a little helper function for dictionaries (as was noted as a good way to deal with a sparse pmatric) might suffice, something like this,maybe. ### def setdict(d,v,*k): #args = dictionary, value, key all separated by commas d[tuple(k)]=str(v) def evaldict(d,*k): #return the evaluated entry at key k in dictionary d return eval(d[tuple(k)]) d={} setdict(d,1,1,2) setdict(d,'x+3',2) print d x=3 print evaldict(d,1,2) print evaldict(d,2) ### output {(1, 2): '1', (2,): 'x+3'} 1 6 ### The evaluation will pull its values from the context in which the evaldict is being made. There are ways to get around this, but just ask if you need/want to go this direction. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating over a string: index and value
On Fri, 2006-02-10 at 12:42 -0800, Carroll, Barry wrote: I seem to recall reading somewhere that it is possible to concurrently generate the index and value of a string’s characters in a single for statement. Is this true or did imagine it? Here is the scenario: Given an ASCII string of arbitrary length and content, generate a sequence of tuples whose elements are: the index of each character in the string, and data based on the ordinal value of the character in the ASCII collating sequence. Hi Barry, Have a look at enumerate: list(enumerate('abcdefghijk')) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k')] You need to work on each tuple in the iterable, but the function takes you halfway. Hope it helps. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
It's the Python Essential Reference book, Third Edition due out February 24. I'm not aware of a new Nutshell coming out. On Fri, 10 Feb 2006 [EMAIL PROTECTED] wrote: See I couldn't tell if he was talking about the Nutshell book or the Python Essential Reference book...thanks Carl On 2/10/06, nephish [EMAIL PROTECTED] wrote: yeah, one of the guys that posted earlier mentioned late feb as a release of the new one. i think i am going to go ahead and get the cookbook now, and then pick up the new nutshell later. sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nutshell review
On Fri, 10 Feb 2006, Carroll, Barry wrote: Another book I have just found that may turn out useful is Python Programming Patterns by Thomas W. Christopher, published by Prentice Hall PTR. I got that from the library about a year ago. I found it interesting, but not too helpful. One problem is that it explains a Python feature in terms of other python features only, and you don't really get the flavor of what the heck the feature being described actually can do for you; although I'm sure the description of the feature is technically correct. I recently happened across a cheap copy used, and bought it; it was worth the money for the used copy, but I wouldn't have bought it new. (Unfortunately, the copy is at my office, and I'm at home, so unable to provide a good concrete example.) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
Alan G wrote: I've been using MySQL up this day, but would like to convert my program to use Postgresql. I'm curious. Why? Is there some advantage to Postgres over MySql? Yes and no. Postgresql offers more features and is IMO more flexible than most SQL servers out there. Example: postgresql enables you to set up editable sql views. This means that you can concatenate several tables into a view (A stored SQL query), and use this as if it was an ordinary table by adding, deleting and editing data within it. Very handy if you want to set up infinite keyword systems. E.g. MemoTable with an integer memoid field and a text field for a memo KeywordTable with an integer keyid field and a text keyword field. MemoKeyTable with an integer memokeyid field, an integer memoid field, and an integer keyid field - with a UNIQUE index/constraint across the memoid and keyid fields. To get the keywords for each memo, use a view that contains something like the following SQL query. (Warning, the syntax is probably incorrect.) FROM MemoTable, KeywordTable, MemoKeyTable GET MemoTable.memoid, MemoTable.memo, KeywordTable.keyword WHERE (MemoTable.memoid == MemoKeyTable.memoid) AND (KeywordTable.keyid == MemoKeyTable.keyid) SORT BY MemoTable.memoid; In MySQL, this would let you retrieve the data from the tables, but Postgresql will let you add entirely new memos, add a new keyword to a memo, remove a memo cleanly, remove a keyword from a memo, etc. all from the view. However, MySQL is used a lot in web pages because it can return queries much faster than any other database - the catch is that it can only do this with transaction-less tables. (I don't know your level of SQL experience, so please forgive me if I explain things you already know.) Transactions enable you to have a whole series of SQL commands fail if one fails. Useful if you want to add interconnected data across a series of tables. E.g. a finance company moving money from one account to another. You definitely don't want the money to be removed from the first account unless you can add it to the second account. (MySQL can use transactions, however, you immediately lose the speed advantage.) Finally, Postgresql does some things differently from other databases (Calling a function to fill a default value for autoincrementing, rather than a dedicated SERIAL field type.) If you're planing to access the database directly from python, this is no hassle, but if you want to use it through something like OpenOffice.org or ODBC drivers, some things don't work to well. Hope that helped? Joal Heagney ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IDE - Editors - Python
Paul Kraus wrote: Which editors does everyone use and why. Please keep the discussion to IDE's rather then any editors. I am well versed on Emacs and VI so anything beyond them would be appreciative. Why you like the editor and how it helps reduce your development time would be productive and helpfull. TIA, Idle. Purely because I don't do much programming and all I need is a text editor with a built in command line to test ideas and check completed modules. The types of things I use python for are: - semi-quick scripts for one-off automation problems that bash scripting can't solve, - small programs to explore computer or math's based problems. e.g. sorting algorithms, genetic algorithms, Fourier transforms of waves to analyze frequency distributions (Trying to make a white/pink noise generator and ran it's output into the computer's soundcard) - as a handy-dandy scientific calculator when I can't be bothered hunting down my RL scientific calculator :). Most of these have console-argument, interactive console (raw_input) or file-based input methods, with a text console output. Joal Heagney ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] small floating point number problem
On Wed, 08 Feb 2006 03:08:25 -0500, Raymond Hettinger [EMAIL PROTECTED] wrote: [Smith] I just ran into a curious behavior with small floating points, trying to find the limits of them on my machine (XP). Does anyone know why the '0.0' is showing up for one case below but not for the other? According to my tests, the smallest representable float on my machine is much smaller than 1e-308: it is 2.470328229206234e-325 but I can only create it as a product of two numbers, not directly. Here is an attempt to create the much larger 1e-308: a=1e-308 a 0.0 The clue is in that the two differ by 17 orders of magnitude (325-308) which is about 52 bits. The interpreter builds 1-e308 by using the underlying C library string-to-float function and it isn't constructing numbers outside the normal range for floats. When you enter a value outside that range, the function underflows it to zero. In contrast, your computed floats (such as 1*1e-307) return a denormal result (where the significand is stored with fewer bits than normal because the exponent is already at its outer limit). That denormal result is not zero and the C library float-to-string conversion successfully generates a decimal string representation. The asymmetric handling of denormals by the atof() and ftoa() functions is why you see a difference. A consequence of that asymmetry is the breakdown of the expected eval(repr(f))==f invariant: f = f = .1*1e-307 eval(repr(f)) == f False BTW, for the OP, chasing minimum float values is probably best done with powers of 2 math.ldexp(1, -1074) 4.9406564584124654e-324 math.ldexp(1, -1075) 0.0 .5**1074 4.9406564584124654e-324 .5**1075 0.0 math.frexp(.5**1074) (0.5, -1073) math.frexp(.5**1075) (0.0, 0) Regards, Bengt Richter ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
On Sat, Feb 11, 2006, Joal Heagney wrote: Alan G wrote: I've been using MySQL up this day, but would like to convert my program to use Postgresql. I'm curious. Why? Is there some advantage to Postgres over MySql? Yes and no. Postgresql offers more features and is IMO more flexible than most SQL servers out there. ... However, MySQL is used a lot in web pages because it can return queries much faster than any other database - the catch is that it can only do this with transaction-less tables. ... (MySQL can use transactions, however, you immediately lose the speed advantage.) Postgresql is a far more mature product than mysql when it comes to the critical ACID features, transactions, stored procedures, and triggers. Postgresql is also far more compliant with SQL standards. As I understand it, mysql's transaction capabilities are only available when it's built with the innodb back end storage. Mysql and innodb licensing isn't GPL, and the company that provides innodb has recently been purchased by a commercial databae vendor (I don't remeber which one offhand). The licensing issues with mysql make me very leary of doing anything commercial with it. There is also the python sqlobject system which provides a very object oriented wrapper on top of relational databases. Using sqlobject can make many database functions very easy, and largely independent of the underlying database. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``I don't make jokes, I just watch the Government and report the facts...'' Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor